{"cells":[{"metadata":{},"cell_type":"markdown","source":"This is the notebook where the models are trained."},{"metadata":{"trusted":true},"cell_type":"code","source":"!/opt/conda/bin/python3.7 -m pip install --upgrade pip -q\n!pip install /kaggle/input/keras-applications/ -q\n!pip install /kaggle/input/efficientnet-git/ -q","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import json\nimport math, re, os\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport albumentations as A\n\nfrom functools import partial\nfrom kaggle_datasets import KaggleDatasets\n\nimport tensorflow as tf\nfrom tensorflow.keras.utils import plot_model\nfrom tensorflow.keras.layers import (\n    Concatenate, Dense, BatchNormalization, \n    GlobalAveragePooling2D, Flatten, Input, \n    Activation, Conv2D, Add, Dropout, GlobalMaxPool2D)\nfrom tensorflow.keras.initializers import TruncatedNormal\nfrom tensorflow.keras.regularizers import l1, l2, l1_l2\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau,LearningRateScheduler\nfrom tensorflow.keras.applications import ResNet50, Xception, InceptionV3\n\nfrom efficientnet.keras import *\n\nBASE_DIR = \"/kaggle/input/cassava-leaf-disease-classification/\"\nTRAIN_DIR = \"/kaggle/input/cassava-leaf-disease-classification/train_images/\"\nTEST_DIR = \"/kaggle/input/cassava-leaf-disease-classification/test_images/\"\nTRAIN_TF_DIR = \"/kaggle/input/cassava-leaf-disease-classification/train_tfrecords/\"\n\nsub = pd.read_csv(f'{BASE_DIR}sample_submission.csv')\ntrain = pd.read_csv(os.path.join(BASE_DIR, \"train.csv\"))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Utilities"},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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)\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.reshape(image, [*IMAGE_SIZE, 3])\n    \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\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 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 = transform1(image=image)\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_brightness(image, 0.2)\n    image = tf.image.adjust_contrast(image, 1.5)\n    image = tf.image.random_flip_up_down(image)\n    \n    return image, label\n\ndef get_training_dataset(file_names, augmenatate=False):\n    dataset = load_dataset(file_names, labeled=True)  \n    if augmenatate:\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    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(AUTOTUNE)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Global Setup"},{"metadata":{"trusted":true},"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)\n    \n    GCS_PATH = KaggleDatasets().get_gcs_path('cassava-leaf-disease-classification')\n    GCS_PATH_AUG = KaggleDatasets().get_gcs_path('cassavaaug')\n    \n    # Getting the File Names\n    TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train_tfrecords/ld_train*.tfrec')\n    TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test_tfrecords/ld_test*.tfrec')\n    AUG_FILENAMES = tf.io.gfile.glob(GCS_PATH_AUG + '/*.tfrec')\nexcept:\n    strategy = tf.distribute.get_strategy()\n    \nprint('Number of replicas:', strategy.num_replicas_in_sync)\n\n\nAUTOTUNE = tf.data.experimental.AUTOTUNE\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nIMAGE_SIZE = [512, 512]\nCLASSES = ['0', '1', '2', '3', '4']\nEPOCHS = 25","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# EDA"},{"metadata":{"trusted":true},"cell_type":"code","source":"with open(os.path.join(BASE_DIR, \"label_num_to_disease_map.json\")) as file:\n    map_classes = json.loads(file.read())\n    map_classes = {int(k) : v for k, v in map_classes.items()}\n    \ntrain[\"class_name\"] = train[\"label\"].map(map_classes)\n\nplt.figure(figsize=(8, 4))\nsns.countplot(y=\"class_name\", data=train);","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Modeling"},{"metadata":{"trusted":true},"cell_type":"code","source":"def efn():\n    inputs = Input(shape=(*IMAGE_SIZE, 3))\n    model = EfficientNetB0(include_top=False, input_tensor=inputs, weights='imagenet')\n\n    # Freeze the pretrained weights\n    model.trainable = False\n    \n    for layer in model.layers[-15:]:\n        if not isinstance(layer, BatchNormalization):\n            layer.trainable = True\n\n#     Rebuild top\n    x = GlobalAveragePooling2D(name=\"avg_pool\")(model.output)\n    x = BatchNormalization()(x)\n    \n    x = Dropout(0.5)(x)\n    preds = []\n    for i in range(12):\n        x = Dense(2 ** (i//3+6), kernel_initializer=TruncatedNormal(0, 1e-5, 10211))(x)\n        x = BatchNormalization()(x)\n        x = Dropout(0.1)(x)\n        pred = Dense(5, activation=\"sigmoid\", kernel_initializer=TruncatedNormal(0, 5/(i+1), 231))(x)\n        preds.append(pred)\n        \n    outputs = Concatenate()(preds)\n    \n    outputs = Dense(5, activation=\"softmax\", \n                    name=\"prediction\", \n                    kernel_initializer=TruncatedNormal(0, 1e-2, 121))(outputs)\n\n    # Compile\n    model = tf.keras.Model(inputs, outputs, name=\"EfficientNetB0-v4\")\n    \n    optimizer = Adam(learning_rate=9e-4)\n    \n    \n    model_metrics = [tf.keras.metrics.SparseCategoricalAccuracy(name=\"spa\")]\n    model_loss = tf.keras.losses.SparseCategoricalCrossentropy(name='scc')\n    model.compile(\n        optimizer=optimizer, loss=model_loss, metrics=model_metrics\n    )\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope(): \n    model = efn()\n        \n#     model = tf.keras.models.load_model('/kaggle/input/nncassava/efnet05-01.h5')\n#     tf.keras.backend.set_value(model.optimizer.learning_rate, 1e-4)  \n#     model.optimizer.learning_rate = 1e-4\n\n# model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Traininig"},{"metadata":{"trusted":true},"cell_type":"code","source":"hist = model.fit(\n            get_training_dataset(TRAINING_FILENAMES),\n            epochs=800,\n            verbose=1,\n            callbacks = [\n                EarlyStopping(monitor='spa', \n                              patience=100, \n                              restore_best_weights=True, \n                              min_delta=1e-3, \n                              verbose=True,\n                              mode='max'\n                             ),\n                ReduceLROnPlateau(monitor='spa',\n                                  factor=0.95, \n                                  patience=5, \n                                  verbose=0,\n                                  mode='max',\n                                  min_delta=1e-3, \n                                  cooldown=0,\n                                  min_lr=1e-8)\n            ]\n        )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Sanity Check"},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.DataFrame(hist.history).loc[:, ['spa']].plot(title=\"Accuracy\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('/kaggle/working/efnet01-05.h5')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"testing_dataset = get_test_dataset()\n\ndef to_float32(image, label):\n    return tf.cast(image, tf.float32), label\ntest_ds = get_test_dataset(ordered=True) \ntest_ds = test_ds.map(to_float32)\n\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)\n\nNUM_TEST_IMAGES = len(TEST_FILENAMES)\nprint('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='id,label', comments='')\n!head submission.csv","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}