{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Importing important libraries"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport keras\nfrom keras.preprocessing import image\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPool2D, Flatten, Dense, Dropout, BatchNormalization, Input, GlobalAveragePooling2D\nfrom keras.utils.vis_utils import plot_model\nfrom keras.callbacks import ModelCheckpoint,EarlyStopping,ReduceLROnPlateau\nfrom tensorflow.keras.layers.experimental import preprocessing\nfrom tensorflow.keras.applications import InceptionResNetV2\n\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/cassava-leaf-disease-classification/train.csv\")\ntrain['label'] = train['label'].astype('string')\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"diseases = pd.read_json(\"/kaggle/input/cassava-leaf-disease-classification/label_num_to_disease_map.json\", typ='series')\ndiseases","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['label'].value_counts(normalize=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMG_SIZE = 320","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Augmentation"},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = image.ImageDataGenerator(rotation_range=360, width_shift_range=0.1,\n                                   height_shift_range=0.1, brightness_range=[0.2,1.5],\n                                   shear_range=25, zoom_range=0.3,\n                                   channel_shift_range=0.1, horizontal_flip=True,\n                                   vertical_flip=True, rescale=1/255,\n                                   validation_split=0.15)\n\nval_datagen = image.ImageDataGenerator(rescale=1/255, validation_split = 0.15)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = datagen.flow_from_dataframe(\n    dataframe=train,\n    directory=\"/kaggle/input/cassava-leaf-disease-classification/train_images\",\n    x_col='image_id',\n    y_col='label',\n    target_size=(IMG_SIZE, IMG_SIZE),\n    batch_size=32,\n    subset='training',\n    shuffle = True,\n    class_mode='categorical'\n)\n\nval_generator = val_datagen.flow_from_dataframe(\n    dataframe=train,\n    directory=\"/kaggle/input/cassava-leaf-disease-classification/train_images\",\n    x_col='image_id',\n    y_col='label',\n    target_size=(IMG_SIZE, IMG_SIZE),\n    batch_size=32,\n    subset='validation',\n    class_mode = 'categorical',\n    shuffle = True\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_imgs, labels = next(train_generator)\nprint(train_imgs.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(20,10))\nfor i in range(25):\n    plt.subplot(5,5,i+1)\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(False)\n    plt.imshow(train_imgs[i])\n    label1 = np.argmax(labels[i])\n    plt.xlabel(diseases.get(label1))\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model"},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"model = tf.keras.Sequential()\nmodel.add(InceptionResNetV2(include_top=False,\n                            weights='../input/keras-pretrained-models/inception_resnet_v2_weights_tf_dim_ordering_tf_kernels_notop.h5',\n                            input_shape=[IMG_SIZE,IMG_SIZE,3]))\nmodel.add(BatchNormalization(axis=-1))\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dense(5, activation='softmax'))\n\nmodel.compile(loss=tf.keras.losses.CategoricalCrossentropy(),\n              optimizer=tf.keras.optimizers.Adamax(learning_rate=0.01),\n              metrics=['accuracy'])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_model(model, to_file='model.png', show_shapes=True, show_layer_names=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_save = ModelCheckpoint(\"Model\", \n                             save_best_only = True, \n                             save_weights_only = True,\n                             monitor = 'val_loss', \n                             mode = 'min', verbose = 1)\nearly_stop = EarlyStopping(monitor = 'val_loss', min_delta = 0.001, \n                           patience = 5, mode = 'min', verbose = 1,\n                           restore_best_weights = True)\nreduce_lr = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.3, \n                              patience = 2, min_delta = 0.001, \n                              mode = 'min', verbose = 1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training the Model"},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"history = model.fit_generator(train_generator, steps_per_epoch=17118//32,\n                              epochs=25, validation_data=val_generator,\n                              validation_steps = 4279//32, verbose = 1,\n                              callbacks = [model_save, early_stop, reduce_lr])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_history = history.history\nloss_accuracy_train = model.evaluate(train_generator)\nprint(\"Training Loss: {:.4f}\".format(loss_accuracy_train[0]))\nprint(\"Training Accuracy: {:.2%}\".format(loss_accuracy_train[1]))\nloss_accuracy = model.evaluate(val_generator)\nprint(\"Validation Loss: {:.4f}\".format(loss_accuracy[0]))\nprint(\"Validation Accuracy: {:.2%}\".format(loss_accuracy[1]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig , ax = plt.subplots(1,2)\ntrain_acc = history.history['accuracy']\ntrain_loss = history.history['loss']\nfig.set_size_inches(12,4)\n\nax[0].plot(history.history['accuracy'])\nax[0].plot(history.history['val_accuracy'])\nax[0].set_title('Training Accuracy vs Validation Accuracy')\nax[0].set_ylabel('Accuracy')\nax[0].set_xlabel('Epoch')\nax[0].legend(['Train', 'Validation'], loc='upper left')\n\nax[1].plot(history.history['loss'])\nax[1].plot(history.history['val_loss'])\nax[1].set_title('Training Loss vs Validation Loss')\nax[1].set_ylabel('Loss')\nax[1].set_xlabel('Epoch')\nax[1].legend(['Train', 'Validation'], loc='upper left')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Prediction"},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = []\nss = pd.read_csv('../input/cassava-leaf-disease-classification/sample_submission.csv')\n\nfor image in ss.image_id:\n    img = tf.keras.preprocessing.image.load_img('../input/cassava-leaf-disease-classification/test_images/' + image)\n    img = tf.keras.preprocessing.image.img_to_array(img)\n    img = tf.keras.preprocessing.image.smart_resize(img, (IMG_SIZE, IMG_SIZE))\n    img = tf.reshape(img, (-1, IMG_SIZE, IMG_SIZE, 3))\n    prediction = model.predict(img/255)\n    preds.append(np.argmax(prediction))\n\nsubmission = pd.DataFrame({'image_id': ss.image_id, 'label': preds})\nsubmission","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv('submission.csv', index = False)","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}