{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom tensorflow.keras.applications import EfficientNetB2\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom keras.models import load_model\nimport tensorflow as tf\nfrom PIL import Image\nimport os\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path = '../input/cassava-leaf-disease-classification/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_path = pd.read_csv(path + 'train.csv')\ntrain_path['label'] = train_path['label'].astype('string')\ntrain_path.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"disease_names = pd.read_json(path + 'label_num_to_disease_map.json', typ='series')\ndisease_names","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(16, 12))\nfor i in range(9):\n    plt.subplot(3, 3, i + 1)\n    image = Image.open(path + 'train_images/' + train_path.iloc[i]['image_id'])\n    array = np.array(image)\n    plt.imshow(array)\n    label=train_path.iloc[i]['label']\n    plt.title(f'{disease_names[int(label)]}')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sizes = []\nfor i in range(1, len(train_path), 200):\n    image = Image.open(path + 'train_images/' + train_path.iloc[i]['image_id'])\n    array = np.array(image)\n    sizes.append(array.shape)\nprint('Image size is:', set(sizes))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_width, image_height = 250, 250","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(validation_split=0.2,\n                             vertical_flip=True,\n                             horizontal_flip=True)\ntrain_datagen_flow = datagen.flow_from_dataframe(\n    dataframe=train_path,\n    directory=path + 'train_images',\n    x_col='image_id',\n    y_col='label',\n    target_size=(image_width, image_height),\n    batch_size=20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_datagen_flow = datagen.flow_from_dataframe(\n    dataframe=train_path,\n    directory=path + 'train_images',\n    x_col='image_id',\n    y_col='label',\n    target_size=(image_width, image_height),\n    batch_size=20,\n    subset='validation',\n    seed=12345)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"current_balance = train_path['label'].value_counts(normalize=True)\ncurrent_balance","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class_weight = {0: (1 - current_balance['0']) / (1 - current_balance.min()),\n                1: (1 - current_balance['1']) / (1 - current_balance.min()),\n                2: (1 - current_balance['2']) / (1 - current_balance.min()),\n                3: (1 - current_balance['3']) / (1 - current_balance.min()),\n                4: (1 - current_balance['4']) / (1 - current_balance.min())}\n\nclass_weight","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"early_stopping = EarlyStopping(monitor='val_accuracy', patience=4)\nmc = ModelCheckpoint('best_model.h5', monitor='val_loss', mode='min', save_best_only=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":" model = Sequential()\noptimizer = Adam(lr=0.001)\nbackbone = EfficientNetB2(include_top=False, \n                          weights=None, \n                          pooling='avg')\nmodel.add(backbone)\nmodel.add(Dense(5, activation='softmax'))\nmodel.compile(loss=\"categorical_crossentropy\", \n              optimizer=optimizer, \n              metrics=[\"accuracy\"])\nmodel.fit_generator(train_datagen_flow,\n                    validation_data=valid_datagen_flow, \n                    epochs=10,\n                    class_weight=class_weight,\n                    callbacks=[early_stopping, mc],\n                    verbose=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"saved_model = load_model('best_model.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame(columns=['image_id','label'])\nfor image_name in os.listdir(path + 'test_images'):\n    image_path = os.path.join(path + 'test_images', image_name)\n    image = tf.keras.preprocessing.image.load_img(image_path)\n    resized_image = image.resize((image_width, image_height))\n    numpied_image = np.expand_dims(resized_image, 0)\n    tensored_image = tf.cast(numpied_image, tf.float32)\n    submission = submission.append(pd.DataFrame({'image_id': image_name,\n                                                 'label': saved_model.predict_classes(tensored_image)}))\n\nsubmission","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv('/kaggle/working/submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}