{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import os\nimport cv2\nimport json\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom tensorflow import keras\nimport matplotlib.pyplot as plt\nfrom keras import applications\nimport tensorflow as tf\nfrom tensorflow.keras import models, layers\nfrom tensorflow.keras.applications import EfficientNetB3\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras.optimizers import Adam","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = pd.read_csv('../input/cassava-leaf-disease-classification/train.csv')\ndata['label'] = data['label'].astype('str')\ndata.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f'There are total {data.shape[0]} images in our train data.')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with open('../input/cassava-leaf-disease-classification/label_num_to_disease_map.json', 'r') as file:\n    labels = json.load(file)\n    \nlabels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_PATH = '../input/cassava-leaf-disease-classification/train_images'\nIMAGE_WIDTH = 224\nIMAGE_HEIGHT = 224\n\nplt.figure(figsize=(16, 15))\ndf_sample = data.sample(12).reset_index(drop=True)\nfor i in range(9):\n    plt.subplot(3, 3, i+1)\n    img = cv2.imread(os.path.join(TRAIN_PATH, df_sample.image_id[i]))\n    img = cv2.resize(img, (IMAGE_HEIGHT, IMAGE_WIDTH))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    plt.axis('off')\n    plt.imshow(img)\n    plt.title(labels.get(df_sample.label[i]))\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.countplot(data.label.values)\nplt.title('Bar distribution of class labels')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = keras.preprocessing.image.ImageDataGenerator(\n    horizontal_flip=True,\n    vertical_flip=True,\n    rotation_range=20,\n    shear_range=20,\n    zoom_range=0.2,\n    height_shift_range=0.1,\n    width_shift_range=0.1,\n    validation_split=0.2\n)\n\ntrain_imagegen = train_datagen.flow_from_dataframe(\n    data,\n    directory='../input/cassava-leaf-disease-classification/train_images',\n    x_col='image_id',\n    y_col='label',\n    subset='training',\n    target_size=(IMAGE_HEIGHT, IMAGE_WIDTH),\n    class_mode='categorical',\n    batch_size=32\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_datagen = keras.preprocessing.image.ImageDataGenerator(validation_split=0.3)\n\nvalid_imagegen = valid_datagen.flow_from_dataframe(\n    data,\n    directory='../input/cassava-leaf-disease-classification/train_images',\n    x_col='image_id',\n    y_col='label',\n    subset='validation',\n    target_size=(IMAGE_HEIGHT, IMAGE_WIDTH),\n    class_mode='categorical',\n    batch_size=32\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"conv_base = EfficientNetB3(include_top = False, weights = None,input_shape = (224, 224, 3))\nmodel = conv_base.output\nmodel = layers.GlobalAveragePooling2D()(model)\nmodel = layers.Dense(5, activation = \"softmax\")(model)\nmodel = models.Model(conv_base.input, model)\n\nmodel.compile(optimizer = Adam(lr = 0.001),loss = \"categorical_crossentropy\",metrics = [\"acc\"])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"early_stop = EarlyStopping(monitor = 'val_loss', min_delta = 0.001, \n                           patience = 5, mode = 'min', verbose = 1,\n                           restore_best_weights = True)\n\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":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator( train_imagegen,\n                               epochs =10,\n                               steps_per_epoch = (len(data)*0.8) // 32,\n                               validation_data = valid_imagegen,\n                               validation_steps = (len(data)*0.2) // 32,\n                               callbacks = [early_stop, reduce_lr])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(25,10))\nplt.subplot(1, 2, 1)\nplt.plot(history.history['acc'], 'b*-', label=\"train_acc\")\nplt.plot(history.history['val_acc'], 'r*-', label=\"val_acc\")\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], 'b*-', label=\"train_acc\")\nplt.plot(history.history['val_loss'], 'r*-', label=\"val_acc\")\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = pd.read_csv('../input/cassava-leaf-disease-classification/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict = []\nfor image in sample.image_id:\n    img = keras.preprocessing.image.load_img('../input/cassava-leaf-disease-classification/test_images/' + image)\n    img = keras.preprocessing.image.img_to_array(img)\n    img = keras.preprocessing.image.smart_resize(img, (224, 224))\n    img = np.expand_dims(img, 0)\n    prediction = model.predict(img)\n    predict.append(np.argmax(prediction))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame({'image_id': sample.image_id, 'label': predict})\nsubmission.head()","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}