{"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":"from tensorflow.keras.layers import Dense, Input, Lambda, Flatten, Conv2D, MaxPool2D,BatchNormalization,Dropout\nfrom tensorflow.keras.models import Sequential, Model\nfrom keras.utils import to_categorical, Sequence\nimport numpy as np\nnp.random.seed(42)\nimport cv2\nfrom glob import glob\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path = '/kaggle/input/cassava-leaf-disease-classification/'\nos.listdir(path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#load Data\n\ntrain_data = pd.read_csv(path+'train.csv')\nsub = pd.read_csv(path+'sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('number of train images:', len(os.listdir(path+'train_images/')))\nprint('number of test images:', len(os.listdir(path+'test_images/')))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = cv2.imread('../input/cassava-leaf-disease-classification/train_images/1000723321.jpg')\nplt.imshow(img)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nVALIDATION_SPLIT = 0.2\nBATCH_SIZE = 32\nTARGET_SIZE = (224, 224)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom keras.preprocessing.image import ImageDataGenerator\n\n\n\ndatagen = ImageDataGenerator(\n            rescale=1./255,\n            shear_range = 0.2,  zoom_range = 0.2, horizontal_flip = True,\n            validation_split = VALIDATION_SPLIT\n)\n\nclass TrainIDG(object):\n    def __init__(self):\n        train_generator = datagen.flow_from_dataframe(\n            train_data,\n            \"../input/cassava-leaf-disease-classification/train_images\",\n            x_col = \"image_id\",\n            y_col = \"label\",\n            target_size=TARGET_SIZE,\n            batch_size=BATCH_SIZE,\n            class_mode='raw',\n            subset=\"training\"\n        )\n\n        self.gene = train_generator\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        X, Y = self.gene.next()\n        return X, Y\n\nclass ValidIDG(object):\n    def __init__(self):\n        validation_generator = datagen.flow_from_dataframe(\n            train_data,\n            \"../input/cassava-leaf-disease-classification/train_images\",\n            x_col = \"image_id\",\n            y_col = \"label\",\n            target_size=TARGET_SIZE,\n            batch_size=BATCH_SIZE,\n            class_mode='raw',\n            subset=\"validation\"\n        )\n\n        self.gene = validation_generator\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        X, Y = self.gene.next()\n        return X, Y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_datagen = ImageDataGenerator(\n            rescale=1./255\n)\n\nclass TestIDG(object):\n    def __init__(self):\n        test_generator = test_datagen.flow_from_dataframe(\n            sub,\n            \"../input/cassava-leaf-disease-classification/test_images\",\n            x_col = \"image_id\",\n            y_col = \"label\",\n            target_size=TARGET_SIZE,\n            batch_size=BATCH_SIZE,\n            class_mode=None\n        )\n\n        self.gene = test_generator\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        X = self.gene.next()\n        return X","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = TrainIDG()\nvalidation_generator = ValidIDG()\ntest_generator = TestIDG()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"INPUT_SHAPE = (224,224,3)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inputs = Input(shape=INPUT_SHAPE)\nconv1 = Conv2D(64, (3,3), activation='relu', padding='same')(inputs)\npool1 = MaxPool2D(pool_size=(2,2))(conv1)\nnorm1 = BatchNormalization(axis=-1)(pool1)\ndrop1 = Dropout(rate=0.2)(norm1)\n\nconv2 = Conv2D(64, (3,3), activation='relu', padding='same')(drop1)\npool2 = MaxPool2D(pool_size=(2,2))(conv2)\nnorm2 = BatchNormalization(axis=-1)(pool2)\ndrop2 = Dropout(rate=0.2)(norm2)\n\nflat = Flatten()(drop2)\n\nhidden1 = Dense(512, kernel_initializer='he_uniform', activation='relu')(flat)\nnorm3 = BatchNormalization(axis=-1)(hidden1)\ndrop3 =  Dropout(rate=0.2)(norm3)\n\nhidden2 = Dense(256, kernel_initializer='he_uniform', activation='relu')(drop3)\nnorm4 = BatchNormalization(axis=-1)(hidden2)\ndrop4 =  Dropout(rate=0.2)(norm4)\n\nhidden3 = Dense(128, kernel_initializer='he_uniform', activation='relu')(drop4)\nnorm5 = BatchNormalization(axis=-1)(hidden3)\ndrop5 =  Dropout(rate=0.2)(norm5)\n\n\noutput = Dense(5, activation='softmax')(drop5)\n\n\nmodel = Model(inputs = inputs, outputs = output)\n\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\n\n\n\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":"from keras.callbacks import EarlyStopping\nes_callback = EarlyStopping(monitor='val_loss', \\\n                            mode='min', patience=4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history=model.fit(\n    train_generator, \n    validation_data=validation_generator,\n    epochs = 20,\n    callbacks = [es_callback],\n    steps_per_epoch = len(train_data) * (1-VALIDATION_SPLIT) // BATCH_SIZE,\n    validation_steps = len(train_data) * VALIDATION_SPLIT // BATCH_SIZE\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot the loss\nplt.plot(history.history['loss'], label='train loss')\nplt.plot(history.history['val_loss'], label='val loss')\nplt.legend()\nplt.show()\n\n\n# plot the accuracy\nplt.plot(history.history['accuracy'], label='train acc')\nplt.plot(history.history['val_accuracy'], label='val acc')\nplt.legend()\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\n\npredictions = model.predict(test_generator, steps = len(sub))\npredictions = np.argmax(predictions)\npredictions","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub[\"label\"] = predictions\nsub.to_csv(\"submission.csv\", index=False)","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}