{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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\nimport os\nfor 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nimport numpy as np \nimport pandas as pd \nimport torch\nimport math\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n\nimport os\nimport seaborn as sn\nimport json\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential, Model \nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers import Conv2D, GlobalAveragePooling2D, Dense, Flatten, Dropout, BatchNormalization\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\n\n%matplotlib inline\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#tf.keras.models.load_model(\"../input/casavaleafdiseasemodel-tf/CasavaLeafDiseaseModel_epoch_12_acc_85.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import math, re, os\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\n\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom tensorflow import keras\nfrom functools import partial\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.utils import shuffle\nimport cv2\nfrom tensorflow.keras import applications\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Dense, Dropout, BatchNormalization, GlobalAveragePooling2D\ntrain_csv_path = \"../input/cassava-leaf-disease-classification/train.csv\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_csv_path = \"../input/cassava-leaf-disease-classification/train.csv\"\nlabel_json_path = \"../input/cassava-leaf-disease-classification/label_num_to_disease_map.json\"\nimages_dir_path = \"../input/cassava-leaf-disease-classification/train_images\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_csv = pd.read_csv(train_csv_path)\n\ntrain_csv['label'] = train_csv['label'].astype('string')\n\nlabel_class = pd.read_json(label_json_path, orient = 'index')\n\nlabel_class = label_class.values.flatten().tolist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_csv","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data_label_3 = train_csv[train_csv[\"label\"]=='3']\ntrain_data_label_2 = train_csv[train_csv[\"label\"]=='2']\ntrain_data_label_1 = train_csv[train_csv[\"label\"]=='1']\ntrain_data_label_0 = train_csv[train_csv[\"label\"]=='0']\ntrain_data_label_4 = train_csv[train_csv[\"label\"]=='4']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(train_data_label_3))\nprint(len(train_data_label_2)) \nprint(train_data_label_1) \nprint(train_data_label_0 )\nprint(train_data_label_4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"BATCH_SIZE = 24\nIMG_SIZE = 300","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data_label_0 = train_csv[train_csv[\"label\"]=='0']\ntrain_data_label_0 = shuffle(train_data_label_0)\ntrain_data_label_1 = train_csv[train_csv[\"label\"]=='1']\ntrain_data_label_1 = shuffle(train_data_label_1)\ntrain_csv1 = pd.concat([train_data_label_1, train_data_label_0], ignore_index=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#train_data_label_3 = train_csv[train_csv[\"label\"]=='3']\n#train_data_label_3 = shuffle(train_data_label_3)\n#train_data_label_3= train_data_label_3[:4000]\n#train_data_label_not_3 = train_csv[train_csv[\"label\"]!='3']\n#train_csv = pd.concat([train_data_label_3, train_data_label_not_3], ignore_index=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_csv","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_csv = train_csv.append(train_csv1, ignore_index = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_csv","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# ****Data Agumentation and Pre-Processing****"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_ex = ImageDataGenerator(rotation_range=270,\n                                width_shift_range=0.2,\n                                height_shift_range=0.2,\n                                brightness_range=[0.1,0.9],shear_range=25,\n                                zoom_range=0.3,\n                                channel_shift_range=0.1,\n                                horizontal_flip=True,\n                                zca_whitening=True,\n                                vertical_flip=True,\n                                rescale=1/255,\n                                validation_split=0.2\n                               )\nvalid_ex = ImageDataGenerator(rescale=1/255,\n                               validation_split = 0.2\n                              )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = train_ex.flow_from_dataframe(\n                            dataframe=train_csv,\n                            directory = images_dir_path,\n                            x_col = \"image_id\",\n                            y_col = \"label\",\n                            target_size = (IMG_SIZE, IMG_SIZE),\n                            class_mode = \"categorical\",\n                            batch_size = BATCH_SIZE,\n                            shuffle = True,\n                            subset = \"training\"\n\n)\n\nvalid_generator = valid_ex.flow_from_dataframe(\n                            dataframe=train_csv,\n                            directory = images_dir_path,\n                            x_col = \"image_id\",\n                            y_col = \"label\",\n                            target_size = (IMG_SIZE, IMG_SIZE),\n                            class_mode = \"categorical\",\n                            batch_size = BATCH_SIZE,\n                            shuffle = False,\n                            subset = \"validation\"\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"batch = next(train_generator)\nimages = batch[0]\nlabels = batch[1]\n\nplt.figure(figsize=(15,9))\nfor i, (img, label) in enumerate(zip(images, labels)):\n    plt.subplot(5,3, i%15 +1)\n    plt.axis('off')\n    plt.imshow(img)\n    plt.title(label_class[np.argmax(label)])\n    \n    if i==15:\n        break"},{"metadata":{"trusted":true},"cell_type":"code","source":"def customModel(weights = None):\n    \n    base_model = keras.applications.InceptionResNetV2(include_top = False,weights = weights, input_shape = [IMG_SIZE,IMG_SIZE,3])\n    model = Sequential()\n    model.add(base_model)\n    model.add(BatchNormalization(axis=-1))\n    model.add(GlobalAveragePooling2D())\n    model.add(Dropout(0.5))\n    model.add(Dense(256,activation = \"relu\"))\n    model.add(Dense(5, activation = \"softmax\"))\n    \n    model.compile(loss = \"categorical_crossentropy\", optimizer = Adam(lr = 0.001), metrics = [\"acc\"])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = customModel(weights = \"imagenet\")\n#model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#LEARNING RATE SCHEDULER\ndef lr_scheduler(epoch,lr):\n    if epoch > 3:\n        return lr/1.125\n    return lr\n\nearly_stopping = EarlyStopping(monitor = \"acc\", mode = \"max\",patience = 7)\nlr_scheduler = tf.keras.callbacks.LearningRateScheduler(lr_scheduler)\ncheck_point = tf.keras.callbacks.ModelCheckpoint(\"./CasavaLeafDiseaseDetectModel.h5\", \n                                               monitor='val_loss',save_best_only=True)\nhistory = model.fit(train_generator,\n                    validation_data = valid_generator,\n                    epochs = 25,\n                    callbacks = [early_stopping, lr_scheduler, check_point]\n                   )\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"acc = history.history[\"acc\"]\nv_acc = history.history[\"val_acc\"]\n\nloss = history.history[\"loss\"]\nv_loss = history.history[\"loss\"]\n\nepochs = range(25)\n\nplt.figure(figsize = (8, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs, acc, label = \"Training Set Accuracy\")\nplt.plot(epochs, v_acc, label = \"Validation Set Accuracy\")\nplt.legend(loc = \"lower right\")\nplt.title(\"Training and Validation Accuracy\")\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs, loss, label = \"Training Loss\")\nplt.plot(epochs, v_loss, label = \"Validation Loss\")\nplt.legend(loc = \"lower right\")\nplt.title(\"Training and Validation Loss\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = model = tf.keras.models.load_model(\"../input/casavaleafdiseasemodel-tf/CasavaLeafDiseaseModel_epoch_12_acc_85.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = []\nss = pd.read_csv('../input/cassava-leaf-disease-classification/sample_submission.csv')\n\nfor image in ss.image_id:\n    img = tf.keras.preprocessing.image.load_img('../input/cassava-leaf-disease-classification/test_images/' + image)\n    img = tf.keras.preprocessing.image.img_to_array(img)\n    img = tf.keras.preprocessing.image.smart_resize(img, (IMG_SIZE, IMG_SIZE))\n    img = tf.reshape(img, (-1, IMG_SIZE, IMG_SIZE, 3))\n    prediction = model.predict(img/255)\n    preds.append(np.argmax(prediction))\n\nmy_submission = pd.DataFrame({'image_id': ss.image_id, 'label': preds})\nmy_submission.to_csv('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":{"trusted":true},"cell_type":"code","source":"","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":{"trusted":true},"cell_type":"markdown","source":"def lr_scheduler(epoch,lr):\n    if epoch > 3:\n        return lr/1.125\n    return lr\n\nearly_stopping = EarlyStopping(monitor = \"acc\", mode = \"max\",patience = 7)\nlr_scheduler = tf.keras.callbacks.LearningRateScheduler(lr_scheduler)\ncheck_point = tf.keras.callbacks.ModelCheckpoint(\"./CasavaLeafDiseaseModel.h5\",  \n                                               monitor='val_loss',save_best_only=True)\n\nmodel  = tf.keras.models.load_model(\"../input/cassava-leaf-disease-models/EfNetB0_300_16.h5\")"},{"metadata":{"trusted":true},"cell_type":"markdown","source":"\nmodel.compile(loss=tf.keras.losses.CategoricalCrossentropy(), optimizer=tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.9), metrics=['acc', tf.keras.metrics.TruePositives(name='tp')])\nmodel.summary()"},{"metadata":{"trusted":true},"cell_type":"markdown","source":"try:\n    model = tf.keras.models.load_model(\"../input/casavaleafdiseasemodel-tf/CasavaLeafDiseaseModel_epoch_12_acc_85.h5\")\nexcept:\n    print(\"No saved model. So Train the model !\")\n    \nhistory = model.fit(train_generator, validation_data=valid_generator, epochs=8, callbacks=[check_point, lr_scheduler])"},{"metadata":{"trusted":true},"cell_type":"markdown","source":"test_img_path = \"../input/cassava-leaf-disease-classification/test_images/2216849948.jpg\"\n\nimg = cv2.imread(test_img_path)\nresized_img = cv2.resize(img, (IMG_SIZE, IMG_SIZE)).reshape(-1, IMG_SIZE, IMG_SIZE, 3)/255\n\n"},{"metadata":{"trusted":true},"cell_type":"markdown","source":"p = model.predict()"},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"model = tf.keras.Sequential()\nmodel.add(base)\nmodel.add(BatchNormalization(axis=-1))\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(5, activation='softmax'))\n\nmodel.compile(loss=tf.keras.losses.CategoricalCrossentropy(), optimizer=tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.9), metrics=['acc', tf.keras.metrics.TruePositives(name='tp')])"},{"metadata":{"trusted":true},"cell_type":"markdown","source":"# Loading the ResNet152V2 architecture with imagenet weights as base\nbase = tf.keras.applications.ResNet152V2(include_top=False, weights='imagenet',input_shape=[IMG_SIZE,IMG_SIZE,3])"},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":{"trusted":true},"cell_type":"code","source":"","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":{"trusted":true},"cell_type":"code","source":"","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}