{"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)\nimport pathlib\nimport imageio\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":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt \nimport plotly.express as px\nimport os\nimport cv2\nfrom PIL import Image\nimport keras\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport tensorflow as tf\nfrom tensorflow.keras import models, layers\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras.applications import Xception\nfrom tensorflow.keras.optimizers import Adam","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"input_dir = \"../input/cassava-leaf-disease-classification\"\n\ntrain_images_path = os.path.join(input_dir,\"train_images\")\ntest_images_path = os.path.join(input_dir,'test_images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/cassava-leaf-disease-classification/train.csv')\ntrain.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Total Number of Images in Training Data : \",train.shape[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_list = train['image_id'].to_list()\nlabel_list = train['label'].to_list()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import json\n\nwith open(\"../input/cassava-leaf-disease-classification/label_num_to_disease_map.json\") as f:\n    class_mapping = json.load(f)\n\nclass_mapping2 ={int(k):v for k,v in class_mapping.items()}\n\nclass_mapping2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"BATCH_SIZE = 8 #Mini-Batch Gradient Descent\nSTEPS_PER_EPOCH = len(train)*0.8 / BATCH_SIZE\nVALIDATION_STEPS = len(train)*0.2 / BATCH_SIZE\nEPOCHS = 20\nTARGET_SIZE = 512","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.label = train.label.astype('str')\n\ntrain_datagen = ImageDataGenerator(validation_split = 0.2,\n                                     rotation_range = 45,\n                                     zoom_range = 0.3,\n                                     horizontal_flip = True,\n                                     vertical_flip = True,\n                                     fill_mode = 'nearest',\n                                     shear_range = 0.1,\n                                     height_shift_range = 0.1,\n                                     width_shift_range = 0.1,\n                                     featurewise_center = True,\n                                     featurewise_std_normalization = True)\n\ntrain_generator = train_datagen.flow_from_dataframe(train,\n                         directory = os.path.join('../input/cassava-leaf-disease-classification/train_images'),\n                         subset = \"training\",\n                         x_col = \"image_id\",\n                         y_col = \"label\",\n                         target_size = (TARGET_SIZE, TARGET_SIZE),\n                         batch_size = BATCH_SIZE,\n                         class_mode = \"sparse\",\n                         shuffle= True)\n\n\nvalidation_datagen = ImageDataGenerator(validation_split = 0.2)\n\nvalidation_generator = validation_datagen.flow_from_dataframe(train,\n                         directory = os.path.join('../input/cassava-leaf-disease-classification/train_images'),\n                         subset = \"validation\",\n                         x_col = \"image_id\",\n                         y_col = \"label\",\n                         target_size = (TARGET_SIZE, TARGET_SIZE),\n                         batch_size = BATCH_SIZE,\n                         class_mode = \"sparse\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_path = os.path.join('../input/cassava-leaf-disease-classification/train_images/1003442061.jpg')\nimg = image.load_img(img_path, target_size = (TARGET_SIZE, TARGET_SIZE))\nimg_tensor = image.img_to_array(img)\nimg_tensor = np.expand_dims(img_tensor, axis = 0)\nimg_tensor /= 255.\n\nplt.imshow(img_tensor[0])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"generator = train_datagen.flow_from_dataframe(train.iloc[17:18],\n                         directory = os.path.join('../input/cassava-leaf-disease-classification/train_images'),\n                         x_col = \"image_id\",\n                         y_col = \"label\",\n                         target_size = (TARGET_SIZE, TARGET_SIZE),\n                         batch_size = BATCH_SIZE,\n                         class_mode = \"sparse\")\n\naug_images = [generator[0][0][0]/255 for i in range(10)]\nfig, axes = plt.subplots(2, 5, figsize = (20, 10))\naxes = axes.flatten()\nfor img, ax in zip(aug_images, axes):\n    ax.imshow(img)\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_model():\n    conv_base = Xception(include_top=False, input_tensor=None,\n    pooling=None, input_shape=(TARGET_SIZE, TARGET_SIZE, 3), classifier_activation='softmax')\n                               \n    model = conv_base.output\n    model = layers.GlobalAveragePooling2D()(model)\n    model = layers.Dense(5, activation = \"softmax\")(model)\n    model = models.Model(conv_base.input, model)\n\n    model.compile(optimizer = Adam(lr = 0.001),\n                  loss = \"sparse_categorical_crossentropy\",\n                  metrics = [\"acc\"])\n    return model ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = create_model()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":" model_save = ModelCheckpoint('./Xception_best_weights_more_data.h5', \n                              save_best_only = True, \n                              save_weights_only = True,\n                              monitor = 'val_loss', \n                              mode = 'min', verbose = 1)\n early_stop = EarlyStopping(monitor = 'val_loss', min_delta = 0.001, \n                            patience = 5, mode = 'min', verbose = 1,\n                            restore_best_weights = True)\n reduce_lr = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.3, \n                               patience = 2, min_delta = 0.001, \n                               mode = 'min', verbose = 1) #reduced learning rate\n\n\n history = model.fit(\n     train_generator,\n     steps_per_epoch = STEPS_PER_EPOCH,\n     epochs = EPOCHS,\n     validation_data = validation_generator,\n     validation_steps = VALIDATION_STEPS,\n     callbacks = [model_save, early_stop, reduce_lr])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":" model.save('./Xception_more_data.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}