{"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":{"trusted":true},"cell_type":"code","source":"pip install efficientnet","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nfrom tensorflow.keras.optimizers import RMSprop,Adam\nimport numpy as np\nimport os\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\nfrom keras.models import Sequential\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Model\nfrom keras import Model\nfrom os import getcwd\nfrom keras.layers import Dense, Activation, BatchNormalization\nimport tensorflow as tf\nimport pandas as pd \nimport numpy as np \nfrom sklearn.model_selection import StratifiedKFold\nimport tqdm\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.layers import Dense,Dropout,BatchNormalization,GlobalAveragePooling2D\nfrom tensorflow.keras.models import Sequential,load_model\nfrom tensorflow.keras.optimizers import Adam\nimport tensorflow_addons as tfa \nfrom tensorflow.keras.callbacks import ReduceLROnPlateau,ModelCheckpoint,EarlyStopping\nimport matplotlib.pyplot as plt\nimport tensorflow.keras.backend as K\nimport keras \nfrom keras.utils import to_categorical\nfrom sklearn.metrics import confusion_matrix\nimport efficientnet.tfkeras as efn","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tf.test.is_gpu_available(\n    cuda_only=False, min_cuda_compute_capability=None\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ModelCheckpoint,ReduceLROnPlateau\nearlyStopping = EarlyStopping(monitor='val_accuracy', patience = 15, verbose=0, mode='max')\nmcp_save_xc = ModelCheckpoint(filepath='mdl_wts.hdf5', save_best_only=True, monitor='val_accuracy', mode='max')\nmcp_save_ens = ModelCheckpoint(filepath='mdl_wts_en.h5', save_best_only=True, monitor='val_accuracy', mode='max')\nmcp_save_ens1 = ModelCheckpoint(filepath='mdl_wts_en1.h5', save_best_only=True, monitor='val_loss', mode='min')\nreduce_lr_loss = ReduceLROnPlateau(monitor='val_loss', patience=5, verbose=1, min_delta=1e-4, mode='min')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(\"../input/cassava-leaf-disease-classification/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['label']=train_df['label'].astype(str)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"SEED=42\nTRAIN_DIR='../input/cassava-leaf-disease-classification/train_images'\n# TEST_DIR='data/DATA/TEST'\nIMG_SIZE=(300,300)\nBATCHSIZE=16\nINPUT_SHAPE=(300,300,3)\nEPOCHS=70\nLR=1e-4","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen=ImageDataGenerator(rescale=1/255,\n    rotation_range=40,\n    width_shift_range=.2,\n    height_shift_range=.2,\n    shear_range=.2,\n    validation_split=0.05,\n    #zoom_range=.2,\n\n    horizontal_flip=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = train_datagen.flow_from_dataframe(dataframe=train_df,\n    directory = TRAIN_DIR,\n    x_col=\"image_id\",\n    y_col=\"label\",\n    batch_size = BATCHSIZE,\n    subset = 'training',\n    class_mode='categorical',\n    shuffle = True,\n    target_size=(300,300)\n)\n\n\nvalidation_generator = train_datagen.flow_from_dataframe(dataframe=train_df,\n    directory = TRAIN_DIR,\n    x_col=\"image_id\",\n    y_col=\"label\",\n    shuffle = True,\n    batch_size = BATCHSIZE,\n    subset = 'validation',\n    class_mode='categorical',\n    target_size=(300,300)\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"eff=efn.EfficientNetB3(weights='imagenet',include_top=False,input_shape=INPUT_SHAPE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def f1_metric(y_true, y_pred):\n    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n    possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n    precision = true_positives / (predicted_positives + K.epsilon())\n    recall = true_positives / (possible_positives + K.epsilon())\n    f1_val = 2*(precision*recall)/(precision+recall+K.epsilon())\n    return f1_val","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model=Sequential()\nmodel.add(eff)\nmodel.add(Dropout(0.5))\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dense(5,activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=Adam(lr=LR),loss='categorical_crossentropy',metrics=[f1_metric])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"redlr=ReduceLROnPlateau(monitor='val_loss',patience=3,verbose=1)\nchkpt=ModelCheckpoint('best.h5',verbose=1,monitor='val_loss',save_best_only=True)\nes=EarlyStopping(patience=8,verbose=1,restore_best_weights=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history=model.fit(train_generator,validation_data=validation_generator,epochs=15,callbacks=[redlr,chkpt,es],verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from PIL import Image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TEST_DIR = '../input/cassava-leaf-disease-classification/test_images/'\ntest_images = os.listdir(TEST_DIR)\npredictions = []\n\nfor image in test_images:\n    img = Image.open(TEST_DIR + image)\n    img = img.resize(IMG_SIZE)\n    img = np.expand_dims(img, axis=0)\n    predictions.extend(model.predict(img).argmax(axis = 1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = pd.DataFrame({'image_id': test_images, 'label': predictions})\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}