{"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\n\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":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.execute_input":"2021-02-05T18:42:16.054509Z","iopub.status.busy":"2021-02-05T18:42:16.05376Z","iopub.status.idle":"2021-02-05T18:42:16.056323Z","shell.execute_reply":"2021-02-05T18:42:16.056979Z"},"papermill":{"duration":0.026985,"end_time":"2021-02-05T18:42:16.05726","exception":false,"start_time":"2021-02-05T18:42:16.030275","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import re, math, os, cv2, random, warnings\nimport math, re, os\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom tensorflow import keras\nfrom functools import partial\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, Dense, Dropout, Flatten, BatchNormalization, MaxPool2D\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom tensorflow.keras.models import load_model\nimport datetime\nfrom tensorflow.keras import regularizers","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:16.099336Z","iopub.status.busy":"2021-02-05T18:42:16.098805Z","iopub.status.idle":"2021-02-05T18:42:21.825046Z","shell.execute_reply":"2021-02-05T18:42:21.823924Z"},"papermill":{"duration":5.749959,"end_time":"2021-02-05T18:42:21.825192","exception":false,"start_time":"2021-02-05T18:42:16.075233","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import math, re, os\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom tensorflow import keras\nfrom functools import partial\nfrom sklearn.model_selection import train_test_split\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:21.879928Z","iopub.status.busy":"2021-02-05T18:42:21.879213Z","iopub.status.idle":"2021-02-05T18:42:21.890189Z","shell.execute_reply":"2021-02-05T18:42:21.890993Z"},"papermill":{"duration":0.04678,"end_time":"2021-02-05T18:42:21.891209","exception":false,"start_time":"2021-02-05T18:42:21.844429","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# GCS_PATH = '/kaggle/input/cassava-leaf-disease-classification'\nGCS_PATH = KaggleDatasets().get_gcs_path()","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:21.961469Z","iopub.status.busy":"2021-02-05T18:42:21.96061Z","iopub.status.idle":"2021-02-05T18:42:21.962849Z","shell.execute_reply":"2021-02-05T18:42:21.962194Z"},"papermill":{"duration":0.038873,"end_time":"2021-02-05T18:42:21.963","exception":false,"start_time":"2021-02-05T18:42:21.924127","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"papermill":{"duration":0.032331,"end_time":"2021-02-05T18:42:22.02437","exception":false,"start_time":"2021-02-05T18:42:21.992039","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Device:', tpu.master())\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nexcept:\n    strategy = tf.distribute.get_strategy()\nprint('Number of replicas:', strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:22.088546Z","iopub.status.busy":"2021-02-05T18:42:22.087811Z","iopub.status.idle":"2021-02-05T18:42:22.096915Z","shell.execute_reply":"2021-02-05T18:42:22.09747Z"},"papermill":{"duration":0.044836,"end_time":"2021-02-05T18:42:22.097622","exception":false,"start_time":"2021-02-05T18:42:22.052786","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"AUTOTUNE = tf.data.experimental.AUTOTUNE\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nIMAGE_SIZE = [256, 256]\nHEIGHT = IMAGE_SIZE[0]\nWIDTH = IMAGE_SIZE[1]\nCLASSES = ['0', '1', '2', '3', '4']\nEPOCHS = 100","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:22.178201Z","iopub.status.busy":"2021-02-05T18:42:22.176447Z","iopub.status.idle":"2021-02-05T18:42:22.178909Z","shell.execute_reply":"2021-02-05T18:42:22.179354Z"},"papermill":{"duration":0.039662,"end_time":"2021-02-05T18:42:22.179488","exception":false,"start_time":"2021-02-05T18:42:22.139826","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from functools import partial\n# Source : https://keras.io/examples/keras_recipes/tfrecord/\n\n\ndef decode_image(image):\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0\n    image = tf.image.resize(image, [*IMAGE_SIZE])\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image\n\ndef read_tfrecord(example, labeled):\n    tfrecord_format = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"target\": tf.io.FixedLenFeature([], tf.int64)\n    } if labeled else {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"image_name\": tf.io.FixedLenFeature([], tf.string)\n    }\n    example = tf.io.parse_single_example(example, tfrecord_format)\n    image = decode_image(example['image'])\n    if labeled:\n        label = tf.cast(example['target'], tf.int32)\n        return image, label\n    idnum = example['image_name']\n    return image, idnum\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTOTUNE) # 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(partial(read_tfrecord, labeled=labeled), num_parallel_calls=AUTOTUNE)\n    return dataset\n\ndef count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:22.229193Z","iopub.status.busy":"2021-02-05T18:42:22.228531Z","iopub.status.idle":"2021-02-05T18:42:22.232171Z","shell.execute_reply":"2021-02-05T18:42:22.231407Z"},"papermill":{"duration":0.033127,"end_time":"2021-02-05T18:42:22.232289","exception":false,"start_time":"2021-02-05T18:42:22.199162","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TEST_SIZE=0.10\nTRAINING_FILENAMES, VALID_FILENAMES = train_test_split(\n    tf.io.gfile.glob(GCS_PATH + '/train_tfrecords/*.tfrec'),\n    test_size=TEST_SIZE, random_state=5\n)\n\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test_tfrecords/ld_test*.tfrec')\n","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:22.274751Z","iopub.status.busy":"2021-02-05T18:42:22.274242Z","iopub.status.idle":"2021-02-05T18:42:22.289102Z","shell.execute_reply":"2021-02-05T18:42:22.288227Z"},"papermill":{"duration":0.037318,"end_time":"2021-02-05T18:42:22.289207","exception":false,"start_time":"2021-02-05T18:42:22.251889","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef data_augment(image, label):\n    # Thanks to the dataset.prefetch(AUTO) statement in the following function this happens essentially for free on TPU. \n    # Data pipeline code is executed on the \"CPU\" part of the TPU while the TPU itself is computing gradients.\n#     image = tf.cond(tf.random.uniform([], 0, 1) > 0.2, lambda: tf.image.random_crop(image, [int(HEIGHT*0.8), int(WIDTH*0.8), 3]), lambda: image)\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    image = tf.image.random_saturation(image, 0.6, 1.6)\n    image = tf.image.random_brightness(image, 0.05)\n    image = tf.image.random_contrast(image, 0.7, 1.3)\n    image = tf.image.random_jpeg_quality(image, 10, 100)\n    image = tf.cond(tf.random.uniform([], 0, 1) > 0.5, lambda: tf.image.rot90(image, tf.random.uniform(shape=[], minval=0, maxval=4, dtype=tf.int32)), lambda: image)\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image, label\n","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:22.335418Z","iopub.status.busy":"2021-02-05T18:42:22.333477Z","iopub.status.idle":"2021-02-05T18:42:22.335989Z","shell.execute_reply":"2021-02-05T18:42:22.336374Z"},"papermill":{"duration":0.028064,"end_time":"2021-02-05T18:42:22.336493","exception":false,"start_time":"2021-02-05T18:42:22.308429","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES)  \n    dataset = dataset.map(data_augment, num_parallel_calls=AUTOTUNE)  \n    dataset = dataset.repeat()\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTOTUNE)\n\n    return dataset\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALID_FILENAMES, labeled=True, ordered=ordered) \n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset\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(AUTOTUNE)\n    return dataset","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:22.381388Z","iopub.status.busy":"2021-02-05T18:42:22.380884Z","iopub.status.idle":"2021-02-05T18:42:22.384484Z","shell.execute_reply":"2021-02-05T18:42:22.383988Z"},"papermill":{"duration":0.028989,"end_time":"2021-02-05T18:42:22.384585","exception":false,"start_time":"2021-02-05T18:42:22.355596","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TRAINING_FILENAMES","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:22.428689Z","iopub.status.busy":"2021-02-05T18:42:22.428177Z","iopub.status.idle":"2021-02-05T18:42:22.433036Z","shell.execute_reply":"2021-02-05T18:42:22.433437Z"},"papermill":{"duration":0.029647,"end_time":"2021-02-05T18:42:22.433551","exception":false,"start_time":"2021-02-05T18:42:22.403904","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"NUM_TRAINING_IMAGES = len(TRAINING_FILENAMES) * 1024\nNUM_VALIDATION_IMAGES = len(VALID_FILENAMES) * 1024\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\n\nprint('Dataset: {} training images, {} validation images, {} (unlabeled) test images'.format(\n    NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:22.47724Z","iopub.status.busy":"2021-02-05T18:42:22.476413Z","iopub.status.idle":"2021-02-05T18:42:22.480918Z","shell.execute_reply":"2021-02-05T18:42:22.480269Z"},"papermill":{"duration":0.028088,"end_time":"2021-02-05T18:42:22.481065","exception":false,"start_time":"2021-02-05T18:42:22.452977","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Building model #","metadata":{"papermill":{"duration":0.019873,"end_time":"2021-02-05T18:42:22.522014","exception":false,"start_time":"2021-02-05T18:42:22.502141","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# load our training dataset for EDA\ntraining_dataset = get_training_dataset()\ntraining_dataset = training_dataset.unbatch().batch(20)\ntraining_dataset = training_dataset.cache(\"/kaggle/temp/train_cache\")\ntrain_batch = iter(training_dataset)","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:25.017471Z","iopub.status.busy":"2021-02-05T18:42:25.016754Z","iopub.status.idle":"2021-02-05T18:42:25.409444Z","shell.execute_reply":"2021-02-05T18:42:25.408675Z"},"papermill":{"duration":2.867182,"end_time":"2021-02-05T18:42:25.409577","exception":false,"start_time":"2021-02-05T18:42:22.542395","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load our validation dataset for EDA\nvalidation_dataset = get_validation_dataset()\nvalidation_dataset = validation_dataset.unbatch().batch(20)\nvalid_batch = iter(validation_dataset)","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:25.455264Z","iopub.status.busy":"2021-02-05T18:42:25.454117Z","iopub.status.idle":"2021-02-05T18:42:25.534415Z","shell.execute_reply":"2021-02-05T18:42:25.533487Z"},"papermill":{"duration":0.104584,"end_time":"2021-02-05T18:42:25.534538","exception":false,"start_time":"2021-02-05T18:42:25.429954","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"testing_dataset = get_test_dataset()\ntesting_dataset = testing_dataset.unbatch().batch(20)\ntest_batch = iter(testing_dataset)","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:25.580675Z","iopub.status.busy":"2021-02-05T18:42:25.579497Z","iopub.status.idle":"2021-02-05T18:42:25.619631Z","shell.execute_reply":"2021-02-05T18:42:25.619121Z"},"papermill":{"duration":0.06466,"end_time":"2021-02-05T18:42:25.619788","exception":false,"start_time":"2021-02-05T18:42:25.555128","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow import keras\n\n# lr_scheduler = keras.optimizers.schedules.ExponentialDecay(\n#     initial_learning_rate=1e-5, \n#     decay_steps=10000, \n#     decay_rate=0.9)","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:25.665378Z","iopub.status.busy":"2021-02-05T18:42:25.664845Z","iopub.status.idle":"2021-02-05T18:42:25.66881Z","shell.execute_reply":"2021-02-05T18:42:25.668345Z"},"papermill":{"duration":0.028133,"end_time":"2021-02-05T18:42:25.668917","exception":false,"start_time":"2021-02-05T18:42:25.640784","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# def Model_fit(model, dir_log):\n#     with strategy.scope():      \n#         model = model()\n    \n#         #COMPILE MODEL\n#         model.compile(\n#             optimizer = OPTIMIZER,\n#             loss = LOSS,\n#             metrics = METRICS\n#         )\n    \n#         CHECKPOINT = ModelCheckpoint(str(dir_log)+\".h5\", monitor='val_loss', mode='min', save_best_only=True)\n#     # Tensorboard supervision\n#     #log_dir = \"logs/fit/\" + str(dir_log)+\"_\"+ datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n#     #tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)\n    \n#     # FITTING\n#         history = model.fit(\n#             train_dataset,\n#             validation_data = valid_dataset,\n#             epochs= EPOCHS,\n#             batch_size = BATCH_SIZE,\n#             #class_weight = class_weight,\n#             steps_per_epoch = STEPS_PER_EPOCH,\n#             validation_steps = VALID_STEPS,\n#             callbacks = [\n#                 ES,\n#                 CHECKPOINT, \n#                 reduce_lr],\n#                 #tensorboard_callback],\n#             verbose = 1)\n    \n#         model.save(str(dir_log)+'/'+'model_final.h5')  \n    \n#         return history","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:25.715505Z","iopub.status.busy":"2021-02-05T18:42:25.713745Z","iopub.status.idle":"2021-02-05T18:42:25.716243Z","shell.execute_reply":"2021-02-05T18:42:25.71666Z"},"papermill":{"duration":0.027456,"end_time":"2021-02-05T18:42:25.716803","exception":false,"start_time":"2021-02-05T18:42:25.689347","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"papermill":{"duration":0.020816,"end_time":"2021-02-05T18:42:25.758176","exception":false,"start_time":"2021-02-05T18:42:25.73736","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset = get_training_dataset()\nvalid_dataset = get_validation_dataset()","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:25.805961Z","iopub.status.busy":"2021-02-05T18:42:25.805113Z","iopub.status.idle":"2021-02-05T18:42:25.888151Z","shell.execute_reply":"2021-02-05T18:42:25.887689Z"},"papermill":{"duration":0.10938,"end_time":"2021-02-05T18:42:25.888274","exception":false,"start_time":"2021-02-05T18:42:25.778894","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs_within_each_step = 4\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nVALID_STEPS = NUM_VALIDATION_IMAGES // BATCH_SIZE\nSTEP_SIZE = STEPS_PER_EPOCH * epochs_within_each_step\n# CYCLE = np.floor(1+iterations/(2*step_size))\n# TRAINING_STEPS = CYCLE * 3","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:25.935273Z","iopub.status.busy":"2021-02-05T18:42:25.934562Z","iopub.status.idle":"2021-02-05T18:42:25.937408Z","shell.execute_reply":"2021-02-05T18:42:25.936917Z"},"papermill":{"duration":0.027456,"end_time":"2021-02-05T18:42:25.937509","exception":false,"start_time":"2021-02-05T18:42:25.910053","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def convPaper2_dp_l1l2():\n    model = Sequential()\n    # First Conv couche\n    model.add(Conv2D(32, (5, 5), activation=\"relu\", input_shape=(*IMAGE_SIZE, 3)))\n    \n    model.add(BatchNormalization())\n    model.add(MaxPooling2D(3,3))\n    \n    # Second conv \n    model.add(Conv2D(64, (3, 3), activation=\"relu\"))\n    model.add(Conv2D(128, (3, 3), activation=\"relu\"))\n    \n    model.add(BatchNormalization())\n    model.add(MaxPooling2D(3,3))\n    \n    # Third conv\n    \n    model.add(Conv2D(64, (3, 3), activation=\"relu\"))\n    model.add(Conv2D(128, (3, 3), activation=\"relu\"))\n    \n    model.add(BatchNormalization())\n    model.add(MaxPooling2D(3,3))\n  \n    # Fully connected\n    \n    model.add(Flatten())\n    model.add(Dense(units=512, activation=\"relu\", kernel_regularizer=regularizers.l1_l2(l1=1e-5, l2=1e-4)))\n    model.add(Dropout(0.3))\n    \n    model.add(Dense(units=1024, activation=\"relu\", kernel_regularizer=regularizers.l1_l2(l1=1e-5, l2=1e-4)))\n    model.add(Dropout(0.3))\n    model.add(Dense(units=1024, activation=\"relu\", kernel_regularizer=regularizers.l1_l2(l1=1e-5, l2=1e-4)))\n    model.add(Dropout(0.3))\n    \n    model.add(Dense(units=256, activation=\"relu\"))\n    model.add(Dropout(0.3))\n\n \n    model.add(Dense(units=5, activation=\"softmax\"))\n    return model","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:25.989551Z","iopub.status.busy":"2021-02-05T18:42:25.986988Z","iopub.status.idle":"2021-02-05T18:42:25.992308Z","shell.execute_reply":"2021-02-05T18:42:25.99182Z"},"papermill":{"duration":0.03381,"end_time":"2021-02-05T18:42:25.992408","exception":false,"start_time":"2021-02-05T18:42:25.958598","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow_addons.optimizers import CyclicalLearningRate, AdamW\n\ndef scale_fn(x):\n    return 1. ** x\n#         return 1 / (2.0 ** (x - 1))\n\nopt = CyclicalLearningRate(1e-3, 1e-7, step_size = STEP_SIZE, scale_fn=scale_fn)\nOPTIMIZER  = AdamW(weight_decay = 1e-6, learning_rate=opt)\nLOSS =  'sparse_categorical_crossentropy'\nMETRICS = 'sparse_categorical_accuracy'\n# opt = AdamW(weight_decay=1e-3)\n# model = convPaper2_dp_l1l2()\n\n# model.compile(\n#     optimizer = Adam(learning_rate=opt),\n#     loss = tf.keras.losses.sparse_categorical_crossentropy,\n#     metrics = tf.keras.metrics.categorical_accuracy\n# )","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:26.039424Z","iopub.status.busy":"2021-02-05T18:42:26.038715Z","iopub.status.idle":"2021-02-05T18:42:26.165912Z","shell.execute_reply":"2021-02-05T18:42:26.165403Z"},"papermill":{"duration":0.15281,"end_time":"2021-02-05T18:42:26.166032","exception":false,"start_time":"2021-02-05T18:42:26.013222","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"var_models = [convPaper2_dp_l1l2]\nnames = [\"convPaper2_dp_l1l2\"]\nNB_EXPERIENCE = 1\nseed = 0\nnp.random.seed = seed\ntf.random.set_seed(seed)","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:26.213009Z","iopub.status.busy":"2021-02-05T18:42:26.212348Z","iopub.status.idle":"2021-02-05T18:42:26.215266Z","shell.execute_reply":"2021-02-05T18:42:26.214844Z"},"papermill":{"duration":0.027959,"end_time":"2021-02-05T18:42:26.21538","exception":false,"start_time":"2021-02-05T18:42:26.187421","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ES = EarlyStopping(monitor='val_loss', patience=20, mode='min', restore_best_weights=True, verbose = 1)\nreduce_lr = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.3, patience = 4, min_lr = 1e-7, mode = 'min', verbose = 1)","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:26.262273Z","iopub.status.busy":"2021-02-05T18:42:26.261489Z","iopub.status.idle":"2021-02-05T18:42:26.264347Z","shell.execute_reply":"2021-02-05T18:42:26.263854Z"},"papermill":{"duration":0.028107,"end_time":"2021-02-05T18:42:26.264446","exception":false,"start_time":"2021-02-05T18:42:26.236339","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# for index_models in range(len(var_models)): # on parcourt tous les modèles\n#     list_experience = []\n#     list_experience2 = []\n    \n        \n#     for current_experience in range(NB_EXPERIENCE): # on entraine notre modèle plusieur fois (nb_experience fois)\n#         seed += 1 # set de seed\n#         tf.random.set_seed(seed) # set de seed\n#         np.random.seed = seed # set de seed\n        \n#         # nom du model + current experience\n#         dir_log = \"/kaggle/working\"\n#         # entrainement du modèle\n#         list_experience2.append(Model_fit(var_models[index_models],dir_log))\n#         # historys\n#       #  list_experience2.append(var_models[index_models])\n#     list_experience.append(list_experience2)\n#     #list_model_trained.append(list_experience2)","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:26.311029Z","iopub.status.busy":"2021-02-05T18:42:26.310302Z","iopub.status.idle":"2021-02-05T18:42:26.312642Z","shell.execute_reply":"2021-02-05T18:42:26.313043Z"},"papermill":{"duration":0.027542,"end_time":"2021-02-05T18:42:26.313157","exception":false,"start_time":"2021-02-05T18:42:26.285615","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"list_experience = []\nlist_experience2 = []\n\nmodel = convPaper2_dp_l1l2()\nmodel.compile(\n    optimizer = OPTIMIZER,\n    loss = LOSS,\n    metrics = METRICS\n)\n\nCHECKPOINT = ModelCheckpoint(\"ckpt_model.h5\", monitor='val_loss', mode='min', save_best_only=True)\n\nseed += 1 # set de seed\ntf.random.set_seed(seed) # set de seed\nnp.random.seed = seed # set de seed\n\nwith strategy.scope():\n    model = convPaper2_dp_l1l2()\n\n    model.compile(\n        optimizer = OPTIMIZER,\n        loss = LOSS,\n        metrics = METRICS\n    )\n    \nimport timeit\n\nstartTime = timeit.default_timer()\nhistory = model.fit(\n    train_dataset,\n    validation_data = valid_dataset,\n    epochs= EPOCHS,\n    batch_size = BATCH_SIZE,\n    #class_weight = class_weight,\n    steps_per_epoch = STEPS_PER_EPOCH,\n    validation_steps = VALID_STEPS,\n    callbacks = [\n        ES,\n        CHECKPOINT],\n        # reduce_lr],\n        #tensorboard_callback],\n        verbose = 1)\nelapsedTime = timeit.default_timer() - startTime\nprint(\"Time taken : \", elapsedTime)\nhist_df = pd.DataFrame(history.history)\nhist = 'history.csv'\nwith open(hist, mode='w') as f:\n    hist_df.to_csv(f)\n\nlist_experience2.append(history)\nlist_experience.append(list_experience2)\n    \nmodel.save('/kaggle/working/model_final.h5')","metadata":{"execution":{"iopub.execute_input":"2021-02-05T18:42:26.363786Z","iopub.status.busy":"2021-02-05T18:42:26.363232Z","iopub.status.idle":"2021-02-05T20:51:45.110879Z","shell.execute_reply":"2021-02-05T20:51:45.109884Z"},"papermill":{"duration":7758.776339,"end_time":"2021-02-05T20:51:45.111022","exception":false,"start_time":"2021-02-05T18:42:26.334683","status":"completed"},"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_name2(all_logs, exp, name=\"loss\", ax = None):\n    for k in range(len(all_logs)):\n        length = max(len(all_logs[k][i].history[name]) for i in range(len(all_logs[k])))\n        res = [[] for _ in range(len(all_logs[k]))]\n        for i in range(len(all_logs[k])):\n            if len(all_logs[k][i].history[name]) < length: \n                res[i] = np.append(all_logs[k][i].history[name], np.repeat(np.nan, length - len(all_logs[k][i].history[name])))\n            else :\n                res[i] = all_logs[k][i].history[name]\n\n        mean = np.mean(res, axis = 0)\n        std = np.std(res, axis = 0)  \n        if ax is None:\n            ax = plt.gca()\n        ax.plot(list(range(len(mean))), mean, label = exp[k])\n\n        ax.fill_between(list(range(len(mean))), np.array(mean) - np.array(std), np.array(mean) + np.array(std), alpha = 0.2 )\n    ax.set_title(\"mean \" + name)\n    ax.set_xlabel(\"epoch\")\n    return ax\n\ndef plot_logs2(all_logs, exp):\n    f, ((ax1, ax2),(ax3,ax4)) = plt.subplots(2, 2, sharey='row', figsize=(10,10))\n    p1 = plot_name2(all_logs, name = 'loss' , exp = exp, ax = ax1)\n    p2 = plot_name2(all_logs, name = 'val_loss' , exp = exp, ax = ax2)\n    p3 = plot_name2(all_logs, name = \"sparse_categorical_accuracy\" , exp = exp, ax = ax3)\n    p4 = plot_name2(all_logs, name = 'val_sparse_categorical_accuracy' , exp = exp, ax = ax4)\n    p2.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n    p4.legend(loc='center left', bbox_to_anchor=(1, 0.5))","metadata":{"execution":{"iopub.execute_input":"2021-02-05T20:52:21.945011Z","iopub.status.busy":"2021-02-05T20:52:21.944096Z","iopub.status.idle":"2021-02-05T20:52:21.964148Z","shell.execute_reply":"2021-02-05T20:52:21.963175Z"},"papermill":{"duration":18.187629,"end_time":"2021-02-05T20:52:21.964338","exception":false,"start_time":"2021-02-05T20:52:03.776709","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_logs2(list_experience[:][:], names[:])","metadata":{"execution":{"iopub.execute_input":"2021-02-05T20:52:58.492468Z","iopub.status.busy":"2021-02-05T20:52:58.491938Z","iopub.status.idle":"2021-02-05T20:52:58.943976Z","shell.execute_reply":"2021-02-05T20:52:58.944388Z"},"papermill":{"duration":18.710381,"end_time":"2021-02-05T20:52:58.944536","exception":false,"start_time":"2021-02-05T20:52:40.234155","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def to_float32(image, label):\n    return tf.cast(image, tf.float32), label","metadata":{"execution":{"iopub.execute_input":"2021-02-05T20:53:35.23275Z","iopub.status.busy":"2021-02-05T20:53:35.231839Z","iopub.status.idle":"2021-02-05T20:53:35.233699Z","shell.execute_reply":"2021-02-05T20:53:35.234102Z"},"papermill":{"duration":17.807804,"end_time":"2021-02-05T20:53:35.234264","exception":false,"start_time":"2021-02-05T20:53:17.42646","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"papermill":{"duration":18.014101,"end_time":"2021-02-05T20:54:11.770712","exception":false,"start_time":"2021-02-05T20:53:53.756611","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True) \ntest_ds = test_ds.map(to_float32)\n\nprint('Computing predictions...')\ntest_images_ds = testing_dataset\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","metadata":{"execution":{"iopub.execute_input":"2021-02-05T20:54:48.42751Z","iopub.status.busy":"2021-02-05T20:54:48.426775Z","iopub.status.idle":"2021-02-05T20:54:48.762539Z","shell.execute_reply":"2021-02-05T20:54:48.762092Z"},"papermill":{"duration":18.477531,"end_time":"2021-02-05T20:54:48.762705","exception":false,"start_time":"2021-02-05T20:54:30.285174","status":"completed"},"scrolled":true,"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"papermill":{"duration":18.246391,"end_time":"2021-02-05T20:55:25.071286","exception":false,"start_time":"2021-02-05T20:55:06.824895","status":"completed"},"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='image_id,label', comments='')\n!head submission.csv","metadata":{"execution":{"iopub.execute_input":"2021-02-05T20:56:01.658325Z","iopub.status.busy":"2021-02-05T20:56:01.657185Z","iopub.status.idle":"2021-02-05T20:56:02.434315Z","shell.execute_reply":"2021-02-05T20:56:02.433842Z"},"papermill":{"duration":18.710022,"end_time":"2021-02-05T20:56:02.434438","exception":false,"start_time":"2021-02-05T20:55:43.724416","status":"completed"},"tags":[],"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}