{"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":"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\n# import os\n# for 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nfrom sklearn.preprocessing import LabelEncoder\nimport os\nimport cv2","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trainpath = '/kaggle/input/plant-pathology-2021-fgvc8/train.csv'\nlabelpath = 'label.csv' # not yet exists\nimgfolder = '/kaggle/input/plant-pathology-2021-fgvc8/train_images'\ndataset = pd.read_csv(trainpath)\nlen(dataset)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom keras.preprocessing.image import ImageDataGenerator\ntrain_df, val_df = train_test_split(dataset)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(train_df), len(val_df)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_img_Path = '../input/resized-plant2021/img_sz_256'\n# test_img_Path = '../input/plant-pathology-2021-fgvc8/test_images'\nCLASSES = train_df['labels'].unique().tolist()\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(os.listdir(train_img_Path))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n            rescale=1./255,\n            shear_range=0.2,\n            zoom_range=0.2,\n            horizontal_flip=True)\ntrain_data = train_datagen.flow_from_dataframe(\n            dataframe=train_df,\n            directory=train_img_Path,\n            x_col=\"image\",\n            y_col=\"labels\",\n            target_size=(150, 150),\n            batch_size=32,\n            class_mode='categorical')\nval_data = train_datagen.flow_from_dataframe(\n            dataframe=val_df,\n            directory=train_img_Path,\n            x_col=\"image\",\n            y_col=\"labels\",\n            target_size=(150, 150),\n            batch_size=32,\n            class_mode='categorical')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.applications import ResNet101V2, ResNet152V2, InceptionResNetV2, Xception\nfrom keras import Sequential\nfrom tensorflow.keras.layers import Conv2D, Dropout,MaxPooling2D,Flatten,Dense\nbase_ResNet152V2 = ResNet152V2(include_top = False, \n                         weights = '../input/keras-pretrained-models/ResNet152V2_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_ResNet2 = Sequential()\nmodel_ResNet2.add(base_ResNet152V2)\nmodel_ResNet2.add(Dense(12, activation=('softmax')))\n\nmodel_ResNet2.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\nmodel_ResNet2.summary()\n\n# Training the CNN on the Train data and evaluating it on the val data\nb = model_ResNet2.fit(train_data, validation_data = val_data, epochs = 10, batch_size=128)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_model():\n    from keras import models, layers, losses,optimizers\n    model = models.Sequential()\n    model.add(layers.Conv2D(120, (3, 3), activation='relu', input_shape=(150, 150, 3)))\n    model.add(layers.MaxPooling2D((2, 2)))\n    model.add(layers.Conv2D(90, (3, 3), activation='relu'))\n    model.add(layers.MaxPooling2D((2, 2)))\n    model.add(layers.Conv2D(72, (3, 3), activation='relu'))\n    model.add(layers.Flatten())\n    model.add(layers.Dense(60, activation='relu'))\n    model.add(layers.Dense(12))\n    model.compile(optimizer=optimizers.Adam(learning_rate=0.001), loss=losses.BinaryCrossentropy())\n    model.summary()\n    return model\n\nmodel = load_model()\nr = model.fit(train_data, validation_data =val_data, epochs = 10, batch_size=128)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}