{"cells":[{"metadata":{"_uuid":"90666736-074c-4f95-8769-523fdd1a68af","_cell_guid":"e15e56ec-91f8-4b7b-8c50-a94e74be4e13","trusted":true},"cell_type":"code","source":"import math, re, os\n!pip install -q efficientnet >> /dev/null\n\n#sys.path.append(os.path.abspath('../input/efficientnet/efficientnet-master/efficientnet-master/'))\n\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport efficientnet.tfkeras as efn\nimport albumentations as A\nfrom efficientnet.tfkeras import preprocess_input\nfrom kaggle_datasets import KaggleDatasets\nfrom tensorflow import keras\nfrom functools import partial\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.losses import categorical_crossentropy\nfrom keras.callbacks import ReduceLROnPlateau,EarlyStopping, LearningRateScheduler\nfrom keras import backend as K\nfrom tensorflow import image\nprint(\"Tensorflow version \" + tf.__version__)\n\ntry:\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)\n\nAUTOTUNE = tf.data.experimental.AUTOTUNE\nGCS_PATH = KaggleDatasets().get_gcs_path()\nGCS_PATH_ORI = KaggleDatasets().get_gcs_path('cassava-leaf-disease-classification')\n\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nIMAGE_SIZE = [512, 512]\nCLASSES = ['0', '1', '2', '3', '4']\nEPOCHS = 12\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    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\nTRAINING_FILENAMES, VALID_FILENAMES = train_test_split(\n    tf.io.gfile.glob(GCS_PATH + '/train_tfrecords/ld_train*.tfrec'),\n    test_size=0.35, random_state=10)\n\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test_tfrecords/ld_test*.tfrec')\n\ndef data_augment(image, label, seed = 415):\n    \n    image = tf.image.random_flip_left_right(image, seed=seed)\n    image = tf.image.random_crop(image, [*IMAGE_SIZE, 3])\n    image = tf.image.random_jpeg_quality(image, 80, 100,seed=seed)\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image, label\n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)  \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_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\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\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)\n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALID_FILENAMES)\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))\n\n\nprint(\"Training data shapes:\")\nfor image, label in get_training_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training data label examples:\", label.numpy())\nprint(\"Validation data shapes:\")\nfor image, label in get_validation_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Validation data label examples:\", label.numpy())\nprint(\"Test data shapes:\")\nfor image, idnum in get_test_dataset().take(3):\n    print(image.numpy().shape, idnum.numpy().shape)\nprint(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string\n\n# numpy and matplotlib defaults\nnp.set_printoptions(threshold=15, linewidth=80)\n\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    if numpy_labels.dtype == object: # binary string in this case, these are image ID strings\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    # If no labels, only image IDs, return None for labels (this is the case for test data)\n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    if correct_label is None:\n        return CLASSES[label], True\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_plant(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    if len(title) > 0:\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\n\ndef display_batch_of_images(databatch, predictions=None):\n    \"\"\"This will work with:\n    display_batch_of_images(images)\n    display_batch_of_images(images, predictions)\n    display_batch_of_images((images, labels))\n    display_batch_of_images((images, labels), predictions)\n    \"\"\"\n    # data\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n        \n    # auto-squaring: this will drop data that does not fit into square or square-ish rectangle\n    rows = int(math.sqrt(len(images)))\n    cols = len(images)//rows\n        \n    # size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot=(rows,cols,1)\n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))\n    else:\n        plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))\n    \n    # display\n    for i, (image, label) in enumerate(zip(images[:rows*cols], labels[:rows*cols])):\n        title = '' if label is None else CLASSES[label]\n        correct = True\n        if predictions is not None:\n            title, correct = title_from_label_and_target(predictions[i], label)\n        dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3 # magic formula tested to work from 1x1 to 10x10 images\n        subplot = display_one_plant(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n    \n    #layout\n    plt.tight_layout()\n    if label is None and predictions is None:\n        plt.subplots_adjust(wspace=0, hspace=0)\n    else:\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n    plt.show()\n\n# load our training dataset for EDA\ntraining_dataset = get_training_dataset()\ntraining_dataset = training_dataset.unbatch().batch(20)\ntrain_batch = iter(training_dataset)\n\n# run this cell again for another randomized set of training images\ndisplay_batch_of_images(next(train_batch))\n\n# load our validation dataset for EDA\nvalidation_dataset = get_validation_dataset()\nvalidation_dataset = validation_dataset.unbatch().batch(15)\nvalid_batch = iter(validation_dataset)\n\n# run this cell again for another randomized set of training images\ndisplay_batch_of_images(next(valid_batch))\n\n# load our test dataset for EDA\ntesting_dataset = get_test_dataset()\ntesting_dataset = testing_dataset.unbatch().batch(15)\ntest_batch = iter(testing_dataset)\n\n# we only have one test image\ndisplay_batch_of_images(next(test_batch))\n\n\ndef recall_m(y_true, y_pred):\n    y_true = tf.one_hot(tf.cast(y_true, tf.int32), 5)\n    y_true = tf.squeeze(y_true, axis=1)\n    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n    possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n    recall = true_positives / (possible_positives + K.epsilon())\n    return recall\n\ndef precision_m(y_true, y_pred):\n    y_true = tf.one_hot(tf.cast(y_true, tf.int32), 5)\n    y_true = tf.squeeze(y_true, axis=1)\n    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n    precision = true_positives / (predicted_positives + K.epsilon())\n    return precision\n\ndef f1_m(y_true, y_pred):\n    precision = precision_m(y_true, y_pred)\n    recall = recall_m(y_true, y_pred)\n    return 2*((precision*recall)/(precision+recall+K.epsilon()))\n\n\ndef categorical_focal_loss_with_label_smoothing(gamma,alpha,ls,classes):\n    \"\"\"\n    Implementation of Focal Loss from the paper in multiclass classification\n    Formula:\n        loss = -alpha*((1-p)^gamma)*log(p)\n        y_ls = (1 - α) * y_hot + α / classes\n    Parameters:\n        alpha -- the same as wighting factor in balanced cross entropy\n        gamma -- focusing parameter for modulating factor (1-p)\n        ls    -- label smoothing parameter(alpha)\n        classes     -- No. of classes\n    Default value:\n        gamma -- 2.0 as mentioned in the paper\n        alpha -- 0.25 as mentioned in the paper\n        ls    -- 0.1\n        classes     -- 4\n    \"\"\"\n    def focal_loss(y_true, y_pred):\n        epsilon = K.epsilon() # epsilon = 1.e-9\n        y_pred_ls = (1 - ls) * y_pred + ls / classes\n        y_pred_ls =  K.clip(y_pred_ls, epsilon,1.0 - epsilon)\n        y_true = tf.one_hot(tf.cast(y_true, tf.int32), classes)\n        y_true = tf.squeeze(y_true, axis=1)\n        cross_entropy = - y_true*K.log(y_pred_ls)\n        weight = alpha * y_true * K.pow((1-y_pred_ls), gamma)\n        loss = weight * cross_entropy\n        loss = K.sum(loss, axis=1)\n        return loss\n    \n    return focal_loss\n\n#This function from here and a modification from a Kaggler: https://stackoverflow.com/questions/60689185/label-smoothing-for-sparse-categorical-crossentropy\n\ndef scce_with_ls(y, y_hat):\n    y = tf.one_hot(tf.cast(y,tf.int32),5)\n    y = tf.squeeze(y, axis=1)\n    return categorical_crossentropy(y, y_hat,label_smoothing=0.001)\n\ninitial_learning_rate = 0.001 #0.0005 \nlr_scheduler = keras.optimizers.schedules.ExponentialDecay(\n    initial_learning_rate, \n    decay_steps = 400, \n    decay_rate = 0.90)\n\n# learning rate schedule\ndef step_decay(epoch):\n    initial_lrate = 0.001\n    drop = 0.5\n    epochs_drop = 2.0\n    lrate = initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop))\n    return lrate\n\nwith strategy.scope(): \n    #img_adjust_layer = tf.keras.layers.Lambda(efn.preprocess_input,input_shape=[*IMAGE_SIZE, 3])\n    base_model = efn.EfficientNetB6(include_top=False,input_shape=[*IMAGE_SIZE, 3],weights='imagenet')\n    #weights='noisy-student'\n    base_model.trainable = True\n    \n    model = tf.keras.Sequential([\n        #img_adjust_layer,\n        base_model,\n        tf.keras.layers.GlobalMaxPooling2D(),\n        #tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dropout(rate = 0.5),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')  \n    ])\n    \n    model.compile(\n        optimizer=tf.keras.optimizers.Adam(),\n        #optimizer=tf.keras.optimizers.Adam(learning_rate=lr_scheduler),\n        #optimizer=tf.keras.optimizers.Adadelta(lr=1.0, rho=0.95, epsilon=1e-08, decay=0.0),\n        #loss = scce_with_ls,\n        loss = tf.keras.losses.SparseCategoricalCrossentropy(),\n        #loss = categorical_focal_loss_with_label_smoothing(gamma=2.0, alpha = 0.75, ls = 0.1,classes=5.0),\n        metrics=['sparse_categorical_accuracy'])\n    \n# load data\ntrain_dataset = get_training_dataset()\nvalid_dataset = get_validation_dataset()\n\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nVALID_STEPS = NUM_VALIDATION_IMAGES // BATCH_SIZE\n\nlr_reducer = tf.keras.callbacks.ReduceLROnPlateau(monitor=\"val_acc\", patience=2, mode='max',\n                                                  factor = 0.1, min_lr=0.00001)\n\nearly_stop = tf.keras.callbacks.EarlyStopping(monitor='val_sparse_categorical_accuracy', mode='max',\n                                              patience=3, verbose=0) \n\ncheckpoint = tf.keras.callbacks.ModelCheckpoint('best_efn_model.h5', verbose=1,monitor='val_acc',\n                                                save_best_only=True, mode='auto')  \nlrate = LearningRateScheduler(step_decay)\n\nhistory = model.fit(train_dataset, \n                    steps_per_epoch=STEPS_PER_EPOCH, \n                    epochs=EPOCHS,\n                    validation_data=valid_dataset,\n                    validation_steps=VALID_STEPS,\n                    callbacks = [early_stop,checkpoint, lrate],\n                    verbose=1)\n\n# print out variables available to us\nprint(history.history.keys())\n\n# create learning curves to evaluate model performance\nhistory_frame = pd.DataFrame(history.history)\nhistory_frame.loc[:, ['loss', 'val_loss']].plot()\nhistory_frame.loc[:, ['sparse_categorical_accuracy', 'val_sparse_categorical_accuracy']].plot();\n\n# save model\nmodel.save('best_efn_model.h5')","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}