{"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":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-07-29T18:09:35.836331Z","iopub.execute_input":"2021-07-29T18:09:35.836850Z","iopub.status.idle":"2021-07-29T18:09:46.549147Z","shell.execute_reply.started":"2021-07-29T18:09:35.836817Z","shell.execute_reply":"2021-07-29T18:09:46.545328Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# IMPORTS\n","metadata":{}},{"cell_type":"code","source":"import 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\n\n\nSEED = 123\n\nnp.random.seed(SEED)\ntf.random.set_seed(SEED)\n\nDEVICE = \"TPU\"\nBASEPATH = \"../input/siim-isic-melanoma-classification\"\n\n# 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-29T18:09:46.550839Z","iopub.execute_input":"2021-07-29T18:09:46.551135Z","iopub.status.idle":"2021-07-29T18:09:46.560978Z","shell.execute_reply.started":"2021-07-29T18:09:46.551106Z","shell.execute_reply":"2021-07-29T18:09:46.560037Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Importation des données\n","metadata":{}},{"cell_type":"code","source":"f_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]   ","metadata":{"execution":{"iopub.status.busy":"2021-07-29T18:09:46.562753Z","iopub.execute_input":"2021-07-29T18:09:46.563086Z","iopub.status.idle":"2021-07-29T18:09:47.246960Z","shell.execute_reply.started":"2021-07-29T18:09:46.563056Z","shell.execute_reply":"2021-07-29T18:09:47.245897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# CODE des fonctions principales","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":{"iopub.status.busy":"2021-07-29T18:09:47.248428Z","iopub.execute_input":"2021-07-29T18:09:47.248733Z","iopub.status.idle":"2021-07-29T18:09:47.268249Z","shell.execute_reply.started":"2021-07-29T18:09:47.248682Z","shell.execute_reply":"2021-07-29T18:09:47.267523Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Chargement et exploration du dataset","metadata":{}},{"cell_type":"code","source":"train_df = pd.read_csv('../input/siim-isic-melanoma-classification/train.csv')\ntrain_df.shape","metadata":{"execution":{"iopub.status.busy":"2021-07-29T18:35:00.403792Z","iopub.execute_input":"2021-07-29T18:35:00.404170Z","iopub.status.idle":"2021-07-29T18:35:00.463930Z","shell.execute_reply.started":"2021-07-29T18:35:00.404138Z","shell.execute_reply":"2021-07-29T18:35:00.463032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2021-07-29T18:34:58.153825Z","iopub.execute_input":"2021-07-29T18:34:58.154217Z","iopub.status.idle":"2021-07-29T18:34:58.171417Z","shell.execute_reply.started":"2021-07-29T18:34:58.154184Z","shell.execute_reply":"2021-07-29T18:34:58.170339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Chercher d'éventuelles valeurs nulles","metadata":{}},{"cell_type":"code","source":"train_df.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2021-07-29T18:35:40.131018Z","iopub.execute_input":"2021-07-29T18:35:40.131386Z","iopub.status.idle":"2021-07-29T18:35:40.151087Z","shell.execute_reply.started":"2021-07-29T18:35:40.131351Z","shell.execute_reply":"2021-07-29T18:35:40.149547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Modèle utilisé : LeNet5","metadata":{}},{"cell_type":"markdown","source":"Définition des méta paramètres\n","metadata":{}},{"cell_type":"code","source":"EPOCHS = 1500  # 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 =  100 # le taux d'apprentissage","metadata":{"execution":{"iopub.status.busy":"2021-07-29T18:09:47.269182Z","iopub.execute_input":"2021-07-29T18:09:47.269561Z","iopub.status.idle":"2021-07-29T18:09:47.287380Z","shell.execute_reply.started":"2021-07-29T18:09:47.269531Z","shell.execute_reply":"2021-07-29T18:09:47.285981Z"},"trusted":true},"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":{"iopub.status.busy":"2021-07-29T18:09:47.288779Z","iopub.execute_input":"2021-07-29T18:09:47.289060Z","iopub.status.idle":"2021-07-29T18:09:47.302075Z","shell.execute_reply.started":"2021-07-29T18:09:47.289033Z","shell.execute_reply":"2021-07-29T18:09:47.301017Z"},"trusted":true},"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":{"iopub.status.busy":"2021-07-29T18:09:47.303540Z","iopub.execute_input":"2021-07-29T18:09:47.304113Z","iopub.status.idle":"2021-07-29T18:09:47.355893Z","shell.execute_reply.started":"2021-07-29T18:09:47.304072Z","shell.execute_reply":"2021-07-29T18:09:47.355091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Code d'entrainement du modèle","metadata":{}},{"cell_type":"code","source":"NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\n","metadata":{"execution":{"iopub.status.busy":"2021-07-29T18:09:47.356825Z","iopub.execute_input":"2021-07-29T18:09:47.357197Z","iopub.status.idle":"2021-07-29T18:09:47.360883Z","shell.execute_reply.started":"2021-07-29T18:09:47.357169Z","shell.execute_reply":"2021-07-29T18:09:47.359919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv('../input/siim-isic-melanoma-classification/train.csv')\ntrain_df.shape\ntrain_df['target'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2021-07-29T18:33:08.555718Z","iopub.execute_input":"2021-07-29T18:33:08.556071Z","iopub.status.idle":"2021-07-29T18:33:08.617134Z","shell.execute_reply.started":"2021-07-29T18:33:08.556041Z","shell.execute_reply":"2021-07-29T18:33:08.616103Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Visualisation 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":{"iopub.status.busy":"2021-07-29T18:09:47.364732Z","iopub.execute_input":"2021-07-29T18:09:47.365033Z","iopub.status.idle":"2021-07-29T18:09:47.395082Z","shell.execute_reply.started":"2021-07-29T18:09:47.365001Z","shell.execute_reply":"2021-07-29T18:09:47.393699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"iopub.status.busy":"2021-07-29T18:09:47.396192Z","iopub.status.idle":"2021-07-29T18:09:47.396575Z"},"trusted":true},"execution_count":null,"outputs":[]}]}