{"cells":[{"cell_type":"code","execution_count":4,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":1786,"status":"ok","timestamp":1637112679057,"user":{"displayName":"SHRI JAYAN R A","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GiHDHZ8h1niBSqGtGi49LURhXNivA8XCTY4YzqL=s64","userId":"07758452110844830688"},"user_tz":-330},"id":"D84zrbkuByKY","outputId":"00f507f9-2d1f-48d2-8c29-2c8b2a8d582c"},"outputs":[{"name":"stdout","output_type":"stream","text":["Done\n"]}],"source":["from zipfile import ZipFile\n","file_name = \"/content/data.zip\"\n","with ZipFile(file_name,'r')as zip:\n","  zip.extractall()\n","  print('Done')"]},{"cell_type":"code","execution_count":8,"metadata":{"executionInfo":{"elapsed":4386,"status":"ok","timestamp":1637113011658,"user":{"displayName":"SHRI JAYAN R A","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GiHDHZ8h1niBSqGtGi49LURhXNivA8XCTY4YzqL=s64","userId":"07758452110844830688"},"user_tz":-330},"id":"Ofd6re9q5CM9"},"outputs":[],"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","\n","import numpy as np # linear algebra\n","import 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 \u0026 Run All\" \n","# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session"]},{"cell_type":"code","execution_count":7,"metadata":{"executionInfo":{"elapsed":3823,"status":"ok","timestamp":1637112819561,"user":{"displayName":"SHRI JAYAN R A","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GiHDHZ8h1niBSqGtGi49LURhXNivA8XCTY4YzqL=s64","userId":"07758452110844830688"},"user_tz":-330},"id":"X99hA3KM4pHf"},"outputs":[],"source":["import numpy as np\n","import tensorflow as tf\n","from tensorflow import keras\n","import cv2\n","import matplotlib.pyplot as plt\n","%matplotlib inline\n","from tensorflow.keras.preprocessing.image import ImageDataGenerator\n","from tensorflow.keras.models import Sequential\n","from tensorflow.keras.layers import Layer\n","import pickle\n","import os\n","from keras.preprocessing.image import img_to_array\n","from keras.applications.inception_resnet_v2 import InceptionResNetV2\n","from keras.layers import GlobalMaxPooling2D, Dense, GlobalAveragePooling2D\n","from keras.applications.inception_resnet_v2 import preprocess_input\n","from tensorflow.keras.models import Model\n","from sklearn.preprocessing import LabelBinarizer\n","from sklearn.model_selection import train_test_split\n","\n","default_image_size = tuple((229, 229))"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"7EVR68vt4nGb"},"outputs":[],"source":["def convert_image_to_array(image_dir):\n","    try:\n","        image = cv2.imread(image_dir)\n","        if image is not None :\n","            image = cv2.resize(image, default_image_size)\n","            x = img_to_array(image)\n","            return x #np.expand_dims(x, axis=0)\n","        else :\n","            return np.array([])\n","    except Exception as e:\n","        print(f\"Error : {e}\")\n","        return None"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"background_save":true,"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":442,"status":"ok","timestamp":1637069195659,"user":{"displayName":"SHRI JAYAN R A","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GiHDHZ8h1niBSqGtGi49LURhXNivA8XCTY4YzqL=s64","userId":"07758452110844830688"},"user_tz":-330},"id":"5tSqYheh4jXT"},"outputs":[{"name":"stdout","output_type":"stream","text":["[INFO] Loading images ...\n","Error : [Errno 2] No such file or directory: '/content/testfinal'\n"]}],"source":["image_list,label_list = [],[]\n","directory_root = '/content/testfinal'\n","\n","\n","#default_image_size = (229,229)\n","try:\n","    print(\"[INFO] Loading images ...\")\n","    root_dir = os.listdir(directory_root)\n","    for directory in root_dir :\n","        # remove .DS_Store from list\n","        if directory == \".DS_Store\" :\n","            root_dir.remove(directory)\n","\n","    for plant_folder in root_dir :\n","        plant_disease_folder_list = os.listdir(f\"{directory_root}/{plant_folder}\")\n","        \n","        for disease_folder in plant_disease_folder_list :\n","            # remove .DS_Store from list\n","            if disease_folder == \".DS_Store\" :\n","                plant_disease_folder_list.remove(disease_folder)\n","\n","        for plant_disease_folder in plant_disease_folder_list:\n","            print(f\"[INFO] Processing {plant_disease_folder} ...\")\n","            plant_disease_image_list = os.listdir(f\"{directory_root}/{plant_folder}/{plant_disease_folder}/\")\n","                \n","            for single_plant_disease_image in plant_disease_image_list :\n","                if single_plant_disease_image == \".DS_Store\" :\n","                    plant_disease_image_list.remove(single_plant_disease_image)\n","\n","            for image in plant_disease_image_list[:200]:\n","                image_directory = f\"{directory_root}/{plant_folder}/{plant_disease_folder}/{image}\"\n","                if image_directory.endswith(\".jpg\") == True or image_directory.endswith(\".JPG\") == True:\n","                    image_list.append(convert_image_to_array(image_directory))\n","                    label_list.append(plant_disease_folder)\n","    print(\"[INFO] Image loading completed\")  \n","except Exception as e:\n","    print(f\"Error : {e}\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"i45GQxSV4hg2"},"outputs":[],"source":["#np_label = np.asarray(label_list)\n","np_image_list = np.array(image_list, dtype=np.float16)\n","#print(\"Total no. of y:{}\".format(np_label.shape))\n","#print(\"Total no. of images:{}\".format(image_list.shape))\n","\n","softmax_output = len(plant_disease_folder_list)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"cumGAKZ84fFI"},"outputs":[],"source":["label_binarizer = LabelBinarizer()\n","image_labels = label_binarizer.fit_transform(label_list)\n","pickle.dump(label_binarizer,open('label_transform.pkl', 'wb'))\n","n_classes = len(label_binarizer.classes_)\n","print(n_classes)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"mgLxgjmM4cXb"},"outputs":[],"source":["X_train,X_test,Y_train,Y_test = train_test_split(np_image_list,image_labels,test_size=0.2,random_state=42)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"ot5S-vDE4Zxv"},"outputs":[],"source":["model = InceptionResNetV2(include_top=False,\n","    weights=\"imagenet\")\n","\n","X = model.output\n","\n","X = GlobalMaxPooling2D()(X)\n","\n","predictions = Dense(softmax_output, activation='softmax')(X)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"ryxLsTsI4X2S"},"outputs":[],"source":["aug = ImageDataGenerator(\n","    rotation_range=25, width_shift_range=0.1,\n","    height_shift_range=0.1, shear_range=0.2, \n","    zoom_range=0.2,horizontal_flip=True, \n","    fill_mode=\"nearest\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"yu_2v0Pa4V8T"},"outputs":[],"source":["# Hyper parameters\n","\n","batch_size = 16\n","epochs = 40\n","INIT_LR = 1e-3\n","my_callbacks = [\n","    tf.keras.callbacks.TensorBoard(log_dir='./logs'),\n","]"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"WXRT3Lr74TpL"},"outputs":[],"source":["opt = tf.keras.optimizers.Adam(lr=INIT_LR, decay=INIT_LR / epochs)\n","\n","Inception_Resnet_model = Model(inputs=model.input, outputs=predictions)\n","\n","Inception_Resnet_model.compile(optimizer=opt, loss='categorical_crossentropy',metrics=[\"accuracy\"])"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"E8-1SjsP4NkX"},"outputs":[],"source":["#Complete model\n","Inception_Resnet_model.summary()"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"USCgAn5Y4JvX"},"outputs":[],"source":["Inception_Resnet_model.fit(\n","    aug.flow(X_train, Y_train, batch_size=16),\n","    batch_size=batch_size,\n","    epochs=epochs,\n","    callbacks=my_callbacks,\n","    validation_data=(X_test, Y_test),\n","    shuffle=True\n","    \n",")"]}],"metadata":{"colab":{"authorship_tag":"ABX9TyOLoWW6l9MKD8ebiowzBPfU","name":"Tea","version":""},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}