{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Import des librairies","execution_count":null},{"metadata":{"trusted":true},"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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Mise en place du TPU","execution_count":null},{"metadata":{"trusted":true},"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\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Chargement des données","execution_count":null},{"metadata":{"trusted":true},"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')\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]   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class MyCallBack(tf.keras.callbacks.Callback):\n    def on_epoch_end(self, epoch, logs=None):\n        keys = list(logs.keys())\n        print(\"End epoch {} of training; got log keys: {}\".format(epoch, keys))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Définition des fonctions","execution_count":null},{"metadata":{"trusted":true},"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_augmentFlip(image, label):    \n    image = tf.image.flip_left_right(image)#implémentez ici les fonctions des transformations    \n    return image, label   \n\ndef data_augmentCrop(image,label):\n    image=tf.image.central_crop(image, central_fraction=0.5)\n    return image,label\n\ndef data_augmentRot(image,label):\n    image=tf.image.rot90(image)\n    return image,label\n    \n\n\ndef get_training_dataset(augment = True):\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    \n    if augment == True:\n        dataset = dataset.map(data_augmentFlip, num_parallel_calls=AUTO)\n       # dataset = dataset.map(data_augmentCrop, num_parallel_calls=AUTO)\n        #dataset = dataset.map(data_augmentRot, 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) \n    # 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())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Premier modèle: LeNet5","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"###### Les méta paramètres","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"EPOCHS = 25 # 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*2*2*2,32*2*2*2] # liste [hauteur, largeur] de l'image\nIMAGE_CHANNEL = 3 # 1 en gris, 3 en couleur\nLR = 0.000001 # le taux d'apprentissage","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"###### Création du jeu de validation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAINING_FILENAMES,VALIDATION_FILENAMES = train_test_split(TRAINING_FILENAMES,test_size = 0.25,random_state = SEED)\n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\ntotal_images=NUM_TRAINING_IMAGES+NUM_VALIDATION_IMAGES\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint('Dataset: {} Total images  {} training images, {} validation images, {} unlabeled test images'.format(total_images,NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"###### Création de la structure du modèle","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():    \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(strides=2),\n        tf.keras.layers.Conv2D(16,(5,5),activation='relu',padding='same'),\n        tf.keras.layers.MaxPooling2D(strides=2),\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        tf.keras.layers.Dense(120,activation='relu'), \n        tf.keras.layers.Dense(84,activation='relu'), \n        #tf.keras.layers.Dense(2000,activation='relu'),       \n        tf.keras.layers.Dense(1,activation='sigmoid')        \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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"###### Entraînement du modèle","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"history = lenet5_model.fit(get_training_dataset(),\n                           steps_per_epoch=STEPS_PER_EPOCH,\n                           epochs=EPOCHS,\n                           validation_data=get_validation_dataset())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"###### Visualisation de l'apprentissage","execution_count":null},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"###### Création du fichier excel contenant les prédictions des données de test","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"val_auc=history.history['val_auc'] \nval_loss=history.history['val_loss']\nprint(max(val_auc))\nprint(min(val_loss))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}