{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"#### Importing libraries","metadata":{}},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd\nfrom pathlib import Path\nimport os.path\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nimport os\nimport cv2","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from cycler import cycler\nimport matplotlib as mpl\n\nraw_light_palette = [\n    (0, 122, 255), # Blue\n    (255, 149, 0), # Orange\n    (52, 199, 89), # Green\n    (255, 59, 48), # Red\n    (175, 82, 222),# Purple\n    (255, 45, 85), # Pink\n    (88, 86, 214), # Indigo\n    (90, 200, 250),# Teal\n    (255, 204, 0)  # Yellow\n]\nraw_dark_palette = [\n    (10, 132, 255), # Blue\n    (255, 159, 10), # Orange\n    (48, 209, 88),  # Green\n    (255, 69, 58),  # Red\n    (191, 90, 242), # Purple\n    (94, 92, 230),  # Indigo\n    (255, 55, 95),  # Pink\n    (100, 210, 255),# Teal\n    (255, 214, 10)  # Yellow\n]\nraw_gray_light_palette = [\n    (142, 142, 147),# Gray\n    (174, 174, 178),# Gray (2)\n    (199, 199, 204),# Gray (3)\n    (209, 209, 214),# Gray (4)\n    (229, 229, 234),# Gray (5)\n    (242, 242, 247),# Gray (6)\n]\nraw_gray_dark_palette = [\n    (142, 142, 147),# Gray\n    (99, 99, 102),  # Gray (2)\n    (72, 72, 74),   # Gray (3)\n    (58, 58, 60),   # Gray (4)\n    (44, 44, 46),   # Gray (5)\n    (28, 28, 39),   # Gray (6)\n]\n\nlight_palette = np.array(raw_light_palette)/255\ndark_palette = np.array(raw_dark_palette)/255\ngray_light_palette = np.array(raw_gray_light_palette)/255\ngray_dark_palette = np.array(raw_gray_dark_palette)/255\n\nmpl.rcParams['axes.prop_cycle'] = cycler('color',dark_palette)\nmpl.rcParams['figure.facecolor']  = gray_dark_palette[-2]\nmpl.rcParams['figure.edgecolor']  = gray_dark_palette[-2]\nmpl.rcParams['axes.facecolor'] =  gray_dark_palette[-2]\n\nwhite_color = gray_light_palette[-2]\nmpl.rcParams['text.color'] = white_color\nmpl.rcParams['axes.labelcolor'] = white_color\nmpl.rcParams['axes.edgecolor'] = white_color\nmpl.rcParams['xtick.color'] = white_color\nmpl.rcParams['ytick.color'] = white_color\n\nmpl.rcParams['figure.dpi'] = 200\nmpl.rcParams['axes.spines.top'] = False\nmpl.rcParams['axes.spines.right'] = False","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a list with the filepaths for training and testing\ntrain_img_Path = '../input/plant-pathology-2021-fgvc8/train_images'\n\ntest_img_Path = '../input/plant-pathology-2021-fgvc8/test_images'\n\nimg_Path = '../input/resized-plant2021/img_sz_256'\n\ntrain = pd.read_csv(r'../input/plant-pathology-2021-fgvc8/train.csv')\n\nsample_submission = pd.read_csv(r'../input/plant-pathology-2021-fgvc8/sample_submission.csv')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f'Number of pictures in the training dataset: {train.shape[0]}\\n')\nprint(f'Number of different labels: {len(train.labels.unique())}\\n')\nprint(f'Labels: {train.labels.unique()}')","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train['labels'].value_counts()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CLASSES = train['labels'].unique().tolist()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n\n# Preprocessing the Training set\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n                                   shear_range = 0.1,\n                                   zoom_range = 0.1,\n                                   horizontal_flip = True,\n                                   validation_split=0.25)\n\ntrain_data = train_datagen.flow_from_dataframe(train,\n                                              directory=img_Path,\n                                              classes=CLASSES,\n                                              x_col=\"image\",\n                                              y_col=\"labels\",\n                                              target_size=(150, 150),\n                                              subset='training')\n\nval_data = train_datagen.flow_from_dataframe(train,\n                                            directory=img_Path,\n                                            classes=CLASSES,\n                                            x_col=\"image\",\n                                            y_col=\"labels\",\n                                            target_size=(150, 150),\n                                            subset='validation')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dict_classes = train_data.class_indices\ndict_classes","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\nfrom keras import Sequential\nfrom tensorflow.keras.layers import Conv2D, Dropout,MaxPooling2D,Flatten,Dense\nfrom tensorflow.keras.applications.resnet_v2 import ResNet50V2","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_resnet50V2 = ResNet50V2(include_top = False, \n                         weights = '../input/keras-pretrained-models/ResNet50V2_NoTop_ImageNet.h5', \n                         input_shape = train_data.image_shape, \n                         pooling='avg',\n                         classes = CLASSES)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Adding the final layers to the above base models where the actual classification is done in the dense layers\nmodel_ResNet = Sequential()\nmodel_ResNet.add(base_resnet50V2)\nmodel_ResNet.add(Dense(12, activation=('softmax')))\n\nmodel_ResNet.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\nmodel_ResNet.summary()\n\n# Training the CNN on the Train data and evaluating it on the val data\nr = model_ResNet.fit(train_data, validation_data = val_data, epochs = 15, batch_size=32)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_ResNet.save('res101ver1.h5')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# test_dir = '/kaggle/input/plant-pathology-2021-fgvc8/test_images/'\n# test_df = pd.DataFrame()\n# test_df['image'] = os.listdir(test_dir)\n\n# test_data = train_datagen.flow_from_dataframe(dataframe=test_df,\n#                                     directory=test_dir,\n#                                     x_col=\"image\",\n#                                     y_col=None,\n#                                     batch_size=32,\n#                                     seed=42,\n#                                     shuffle=False,\n#                                     class_mode=None,\n#                                     target_size=(150, 150))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# pred1 = tf.keras.models.load_model('../input/incepres/Iresnet50ver2.h5')\n# pred2 = tf.keras.models.load_model('../input/res101/res101ver1.h5')\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# pred1 = pred1.predict(test_data)\n# pred2 = pred2.predict(test_data)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# pred = (pred1+pred2).tolist()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# for i in range(len(pred)):\n#     pred[i] = np.argmax(pred[i])\n\n    \n# def get_key(val):\n#     for key, value in dict_classes.items():\n#         if val == value:\n#             return key\n        \n\n# for i in range(len(pred)):\n#     pred[i] = get_key(pred[i])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# print(pred)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# test_df['labels'] = pred\n# # test_df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# test_df.to_csv('submission.csv',index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}