{"cells":[{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nfrom pathlib import Path\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import class_weight\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, Dense, Dropout, Flatten\nfrom keras.optimizers import Adam\nfrom keras.losses import binary_crossentropy\nfrom keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint\nfrom keras.metrics import *\nfrom keras import backend as K\nfrom tensorflow.keras.applications import EfficientNetB4","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path = Path('../input/cassava-leaf-disease-classification/')\nos.listdir(path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/cassava-leaf-disease-classification/train.csv\")\ntrain[\"label\"] = train[\"label\"].astype(\"str\")\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df, valid_df = train_test_split(train, test_size = 0.1, random_state = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.shape, valid_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_bs = 16\nvalid_bs = 16\nimg_size = 224\ntarget_size = (img_size, img_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale = 1./255,\n    rotation_range = 40,\n    height_shift_range = 0.2,\n    width_shift_range = 0.2,\n    zoom_range = 0.2,\n    shear_range = 0.2,\n    horizontal_flip = True,\n    fill_mode = 'nearest'\n)\n\nvalid_datagen = ImageDataGenerator(\n    rescale = 1./255\n)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe = train_df,\n    x_col = 'image_id',\n    y_col = 'label',\n    directory = path/'train_images',\n    target_size = target_size,\n    batch_size = train_bs,\n    shuffle = True,\n    class_mode = 'categorical'\n)\n\nvalidation_generator = valid_datagen.flow_from_dataframe(\n    dataframe = valid_df,\n    x_col = 'image_id',\n    y_col = 'label',\n    directory = path/'train_images',\n    target_size = target_size,\n    batch_size = valid_bs,\n    shuffle = False,\n    class_mode = 'categorical'\n)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"METRICS = [\n      TruePositives(name='tp'),\n      FalsePositives(name='fp'),\n      TrueNegatives(name='tn'),\n      FalseNegatives(name='fn'), \n      BinaryAccuracy(name='accuracy'),\n      Precision(name='precision'),\n      Recall(name='recall'),\n      AUC(name='auc'),\n]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#model\ninput_shape = (224,224,3)\nefficient_net_model = EfficientNetB4(weights = None, include_top = False, input_shape = input_shape )\nefficient_net_model.load_weights('../input/tfkerasefficientnetimagenetnotop/efficientnetb4_notop.h5')\n\n\nfor layer in efficient_net_model.layers:\n    layer.trainable = True\n    \nmodel = Sequential()\nmodel.add(efficient_net_model)\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dense(256, activation = 'relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(5, activation = 'softmax'))\n\nmodel.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = METRICS)\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"callbacks = [ReduceLROnPlateau(monitor = 'val_loss', patience = 2, factor = 0.5), \n            EarlyStopping(monitor = 'val_loss', patience = 2),\n             ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True)\n            ]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(train_generator,\n          epochs = 10, \n          validation_data=validation_generator,\n          callbacks=callbacks, 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_images = os.listdir('/kaggle/input/cassava-leaf-disease-classification/test_images/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict = []\n\nfor i in test_images:\n    image = Image.open(f'/kaggle/input/cassava-leaf-disease-classification/test_images/{i}')\n    image = image.resize((224, 224))\n    \n    image = np.asarray(image)\n    image = np.expand_dims(image, axis=0)\n    \n    predict.append(np.argmax(model.predict(image)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame({'image_id': test_images, 'label': predict})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv('submission.csv', index=None)","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}