{"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        k=1\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":"import pandas  as pd\nimport numpy as np\nimport matplotlib.pyplot  as plt\nfrom sklearn.utils import shuffle\nimport cv2\n\nimport tensorflow as tf \nfrom tensorflow.keras import applications\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Dense, Dropout, BatchNormalization, GlobalAveragePooling2D, Flatten","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":"print(images_dir_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_csv = pd.read_csv(train_csv_path)\ntrain_csv['label'] = train_csv['label'].astype('string')\n\nlabel_class = pd.read_json(label_json_path, orient='index')\nlabel_class = label_class.values.flatten().tolist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train_csv)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# label 3 data has 13158 images data\n#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[:3000]\n\n#train_data_label_not_3 = train_csv[train_csv[\"label\"]!='3']\n\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":"print(train_csv)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Label names :\")\nfor i, label in enumerate(label_class):\n    print(f\" {i}. {label}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMG_SIZE = 480","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Data agumentation and pre-processing using tensorflow\ntrain_gen = ImageDataGenerator(\n                                rotation_range=50,\n                                width_shift_range=0.3,\n                                height_shift_range=0.3,\n                                shear_range=0.3,\n                                zoom_range=0.3,\n                                horizontal_flip=True,\n                                fill_mode='nearest',\n                                rescale=1/255,\n                                validation_split=0.1\n                               )\n                                    \n    \nvalid_gen = ImageDataGenerator(\n                                rescale=1/255,\n                                validation_split = 0.1\n                              )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = train_gen.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 = int(np.sqrt(19258)),\n                            shuffle = False,\n                            subset = \"training\",\n\n)\n\nvalid_generator = valid_gen.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 = int(np.sqrt(2139)),\n                            shuffle = False,\n                            subset = \"validation\"\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch = next(train_generator)\nimages = batch[0]\nlabels = batch[1]\n\nplt.figure(figsize=(12,9))\nfor i, (img, label) in enumerate(zip(images, labels)):\n    plt.subplot(2,3, i%6 +1)\n    plt.axis('off')\n    plt.imshow(img)\n    plt.title(label_class[np.argmax(label)])\n    \n    if i==15:\n        break\n       ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), input_shape=(IMG_SIZE, IMG_SIZE, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(32, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(64, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(64, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(128, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(256, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Flatten())  # this converts our 3D feature maps to 1D feature vectors\nmodel.add(Dropout(0.6))\nmodel.add(Dense(5))\nmodel.add(Activation('softmax'))\n\nmodel.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# #Setting a callbacks for model during the training\ndef scheduler(epoch, lr):\n    if epoch >6 and epoch%2==0:\n        lr = lr/1.5\n        return lr\n    else:\n        return lr\n\n# A callback to save the model\ncallback0 = tf.keras.callbacks.ModelCheckpoint(\"./CasavaLeafDiseaseModel.h5\", \n                                               monitor='val_loss',save_best_only=True)\n\n# A callback to reduce the learning rate with increase in epoch\ncallback1 = tf.keras.callbacks.LearningRateScheduler(scheduler)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"his = model.fit(\n        train_generator,\n        epochs=18,\n        validation_data=valid_generator,\n        callbacks=[callback0, callback1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(model.predict(next(valid_generator)[0]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"stats = pd.DataFrame(his.history)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","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\nplt.figure(figsize=(8,4))\nplt.title(\"TEST IMAGE\")\nplt.imshow(resized_img[0])","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":"# Submission file ouput\nprint(\"Submission File: \\n---------------\\n\")\nprint(my_submission.head()) # Predicted Output","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}