{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Import des librairies","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nimport os\nimport re\nfrom sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2021-07-09T09:15:20.235167Z","iopub.execute_input":"2021-07-09T09:15:20.235602Z","iopub.status.idle":"2021-07-09T09:15:27.389719Z","shell.execute_reply.started":"2021-07-09T09:15:20.235505Z","shell.execute_reply":"2021-07-09T09:15:27.388692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Mise en place du TPU","metadata":{}},{"cell_type":"code","source":"SEED = 123\n\nnp.random.seed(SEED)\ntf.random.set_seed(SEED)\n\nDEVICE = \"TPU\"\nBASEPATH = \"../input/siim-isic-melanoma-classification\"","metadata":{"execution":{"iopub.status.busy":"2021-07-09T09:16:29.702421Z","iopub.execute_input":"2021-07-09T09:16:29.702792Z","iopub.status.idle":"2021-07-09T09:16:29.707465Z","shell.execute_reply.started":"2021-07-09T09:16:29.702761Z","shell.execute_reply":"2021-07-09T09:16:29.706495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is\n    # set: this is always the case on Kaggle.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\nAUTO = tf.data.experimental.AUTOTUNE","metadata":{"execution":{"iopub.status.busy":"2021-07-09T09:16:32.411441Z","iopub.execute_input":"2021-07-09T09:16:32.411931Z","iopub.status.idle":"2021-07-09T09:16:32.425088Z","shell.execute_reply.started":"2021-07-09T09:16:32.411901Z","shell.execute_reply":"2021-07-09T09:16:32.423839Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Chargement des données","metadata":{}},{"cell_type":"code","source":"df_train = pd.read_csv(os.path.join(BASEPATH, 'train.csv'))\ndf_test = pd.read_csv(os.path.join(BASEPATH, 'test.csv'))\n\nGCS_PATH = KaggleDatasets().get_gcs_path('siim-isic-melanoma-classification')\nprint(GCS_PATH)\nTRAINING_FILENAMES = np.array(tf.io.gfile.glob(GCS_PATH + '/tfrecords/train*.tfrec'))\nTEST_FILENAMES = np.array(tf.io.gfile.glob(GCS_PATH + '/tfrecords/test*.tfrec'))\n\nCLASSES = [0,1]   ","metadata":{"execution":{"iopub.status.busy":"2021-07-09T09:16:35.461568Z","iopub.execute_input":"2021-07-09T09:16:35.462273Z","iopub.status.idle":"2021-07-09T09:16:36.56592Z","shell.execute_reply.started":"2021-07-09T09:16:35.462225Z","shell.execute_reply":"2021-07-09T09:16:36.564836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Définition des fonctions","metadata":{}},{"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.image.resize(image, [*IMAGE_SIZE])\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        #\"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n        \"target\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    #label = tf.cast(example['class'], tf.int32)\n    label = tf.cast(example['target'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"image_name\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['image_name']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\n\n##### FONCTION A DEVELOPPER POUR AMELIORER LE MODELE\n\ndef data_augment(image, label):\n    \n    #image = tf.image.#implémentez ici les fonctions des transformations\n\n    return image, label   \n\ndef get_training_dataset(augment = False):\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    \n    if augment == True:\n        dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    \n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(SEED)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\ndef display_training_curves(training, validation, title, subplot):\n    \"\"\"\n    Source: https://www.kaggle.com/mgornergoogle/getting-started-with-100-flowers-on-tpu\n    \"\"\"\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(20,15), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])\n    \ndef prediction_test_csv(model,nom_model, df_sub):\n    \n    test_ds = get_test_dataset(ordered=True)\n    print('Computing predictions...')\n    test_images_ds = test_ds.map(lambda image, idnum: image)\n    probabilities = model.predict(test_images_ds)\n    print('Generating submission.csv file...')\n    test_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\n    test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\n    pred_df = pd.DataFrame({'image_name': test_ids, 'target': np.concatenate(probabilities)})\n    pred_df.head()\n    del df_sub['target']\n    df_sub = df_sub.merge(pred_df, on='image_name')\n    #sub.to_csv('submission_label_smoothing.csv', index=False)\n    df_sub.to_csv('submission_' + nom_model + '.csv', index=False)\n    print(df_sub.head())","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Premier modèle: LeNet5","metadata":{}},{"cell_type":"markdown","source":"###### Les méta paramètres","metadata":{}},{"cell_type":"code","source":"EPOCHS =  # le nombre d'itération pour l'apprentissage du modèle\nBATCH_SIZE = 8 * strategy.num_replicas_in_sync # le nombre d'images traitées à la fois\nIMAGE_SIZE = [32,32] # liste [hauteur, largeur] de l'image\nIMAGE_CHANNEL = 3 # 1 en gris, 3 en couleur\nLR =  # le taux d'apprentissage","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"###### Création du jeu de validation","metadata":{}},{"cell_type":"code","source":"TRAINING_FILENAMES,VALIDATION_FILENAMES = train_test_split(TRAINING_FILENAMES,test_size = 0.2,random_state = SEED)\n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"###### Création de la structure du modèle","metadata":{}},{"cell_type":"code","source":"with strategy.scope():\n    \n    lenet5_model = tf.keras.Sequential([\n        tf.keras.layers.Conv2D(6, (5,5), activation='relu', input_shape=(IMAGE_SIZE[0],IMAGE_SIZE[1], IMAGE_CHANNEL)),\n        tf.keras.layers.MaxPooling2D(),\n        # une autre couche de convolution: 16 filtres 5x5, également avec une activation relu. Ne pas spécifier de format d'entrée (input shape)\n        # une autre couche maxpooling 2D\n        tf.keras.layers.Flatten(),\n        # une couche de neurones tf.keras.layers.Dense: 120 neurones, activation relu\n        # une couche de neurones tf.keras.layers.Dense: 84 neurones, activation relu\n        # une couche de neurones tf.keras.layers.Dense: 1 neurones, activation sigmoid\n        ])\n    \n    lenet5_model.summary()\n    \n\n    adam = tf.keras.optimizers.Adam(lr=LR, beta_1=0.9, beta_2=0.999, amsgrad=False)\n    loss = tf.keras.losses.BinaryCrossentropy(from_logits=False)\n\n    lenet5_model.compile(loss=loss, metrics=[tf.keras.metrics.AUC(name='auc')],optimizer=adam)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"###### Entraînement du modèle","metadata":{}},{"cell_type":"code","source":"history = lenet5_model.fit(get_training_dataset(), steps_per_epoch=STEPS_PER_EPOCH,\n                        epochs=EPOCHS, validation_data=get_validation_dataset())","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"###### Visualisation de l'apprentissage","metadata":{}},{"cell_type":"code","source":"display_training_curves(\n    history.history['loss'], \n    history.history['val_loss'], \n    'loss', 311)\ndisplay_training_curves(\n    history.history['auc'], \n    history.history['val_auc'], \n    'auc', 312)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"###### Création du fichier excel contenant les prédictions des données de test","metadata":{}},{"cell_type":"code","source":"df_sub = pd.read_csv(os.path.join(BASEPATH, 'sample_submission.csv'))\nnom_model = 'lenet5' #servira simplement à nommer votre fichier excel\nprediction_test_csv(lenet5_model,nom_model, df_sub)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}