{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-output":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":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\n%matplotlib inline\n\ntf.random.set_seed(34)\nnp.random.seed(34)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv(r\"../input/cassava-leaf-disease-classification/train.csv\", dtype=str)\n\ntrain, test = train_test_split(df, test_size = 0.1, random_state = 22, stratify = df['label'])\n\ns = 256\nt_datagen=ImageDataGenerator(preprocessing_function = tf.keras.applications.efficientnet.preprocess_input,\n                          rotation_range=180,\n                          width_shift_range=0.4,\n                          height_shift_range=0.2,\n                          zoom_range=0.4,\n                          fill_mode='nearest',\n                          horizontal_flip=True,\n                          vertical_flip=True)\n\ntrain_generator=t_datagen.flow_from_dataframe(\n    dataframe=train,\n    directory=\"../input/cassava-leaf-disease-classification/train_images\",\n    x_col=\"image_id\",\n    y_col=\"label\",\n    batch_size=32,\n    shuffle=True,\n    class_mode=\"categorical\",\n    target_size=(s,s))\n\nv_datagen=ImageDataGenerator(preprocessing_function = tf.keras.applications.efficientnet.preprocess_input)\n\nval_generator=v_datagen.flow_from_dataframe(\n    dataframe=test,\n    directory=\"../input/cassava-leaf-disease-classification/train_images\",\n    x_col=\"image_id\",\n    y_col=\"label\",\n    batch_size=32,\n    shuffle=True,\n    class_mode=\"categorical\",\n    target_size=(s,s))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.layers import Activation\nfrom keras.utils.generic_utils import get_custom_objects\nfrom keras import backend as k\n\ndef swish(x):\n  return (k.sigmoid(x)*x)\n\nget_custom_objects().update({'swish': Activation(swish)})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"weights = '../input/keras-pretrained-models/EfficientNetB7_NoTop_ImageNet.h5'\nbase = tf.keras.applications.EfficientNetB7(weights=weights,\n                                            include_top=False,\n                                            input_shape=(256,256,3),\n                                            pooling='avg')\n\n\nfor layer in base.layers:\n    layer.trainable=False\n\nbase.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"x = tf.keras.layers.Dense(256, activation='swish')(base.output)\nx = tf.keras.layers.Dropout(.2)(x)\nx = tf.keras.layers.BatchNormalization()(x)\nout = tf.keras.layers.Dense(5, activation='softmax')(x)\n\neff7model = tf.keras.models.Model(base.input, out)\neff7model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"eff7model.compile(optimizer=tf.keras.optimizers.Adam(1e-3),\n            loss='categorical_crossentropy', \n            metrics=['accuracy'])\n\nreduce_lr = tf.keras.callbacks.ReduceLROnPlateau(\n            monitor='val_loss',\n            factor=.2,\n            mode='min',\n            verbose=1,\n            patience=2,\n            min_delta=0.01)\n            \nES = tf.keras.callbacks.EarlyStopping(\n            monitor='val_loss',\n            mode='min',\n            verbose=1,\n            patience=5,\n            restore_best_weights=True,\n            min_delta=0.01)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"history = eff7model.fit(train_generator,\n                     steps_per_epoch=train_generator.n//train_generator.batch_size,\n                     validation_data=val_generator,\n                     validation_steps=val_generator.n//val_generator.batch_size,\n                     epochs=30,\n                     callbacks=[reduce_lr, ES])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\n\nTEST_DIR = '../input/cassava-leaf-disease-classification/test_images/'\ntest_images = os.listdir(TEST_DIR)\npredictions = []\n\nfor image in test_images:\n    img = tf.keras.preprocessing.image.load_img(TEST_DIR + image, target_size=(256,256))\n    img = tf.keras.preprocessing.image.img_to_array(img)\n    img = np.expand_dims(img, axis=0)\n    img = tf.keras.applications.efficientnet.preprocess_input(img)\n    pred = eff7model.predict(img).argmax(axis = 1)\n    predictions.extend(pred)\n\nlabels = (train_generator.class_indices)\nlabels = dict((v,k) for k,v in labels.items())\nprediction = [labels[k] for k in predictions]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = pd.DataFrame({'image_id': test_images, 'label': prediction})\ndisplay(sub)\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}