{"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":"import 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_path = \"../input/cassava-leaf-disease-classification/\"\ntrain_Data = data_path+\"train.csv\"\nlabel_json_data_path = data_path+\"label_num_to_disease_map.json\"\nimages_dir_data_path = data_path+\"train_images\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_csv = pd.read_csv(train_Data)\ntrain_csv['label'] = train_csv['label'].astype('string')\n\nlabel_class = pd.read_json(label_json_data_path, orient='index')\nlabel_class = label_class.values.flatten().tolist()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### We have 5 Labels for our data set"},{"metadata":{"trusted":true},"cell_type":"code","source":"label_class","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Train csv with image ID and label Number"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_csv.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Image Generator"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_gen = ImageDataGenerator(\n                                rotation_range=180,\n                                width_shift_range=0.1,\n                                height_shift_range=0.1,\n                                brightness_range=[0.1,0.9],\n                                shear_range=25,\n                                zoom_range=0.3,\n                                channel_shift_range=0.1,\n                                horizontal_flip=True,\n                                vertical_flip=True,\n                                rescale=1/255,\n                                validation_split=0.20\n                               )\n                                    \n    \nvalid_gen = ImageDataGenerator(rescale=1/255,\n                               validation_split = 0.20\n                              )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"shape = (180, 180)\nbatch_size = 18","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_ds = train_gen.flow_from_dataframe(\n                            dataframe=train_csv,\n                            directory = images_dir_data_path,\n                            x_col = \"image_id\",\n                            y_col = \"label\",\n                            target_size = shape,\n                            class_mode = \"categorical\",\n                            batch_size = batch_size,\n                            shuffle = True,\n                            subset = \"training\",\n\n)\n\nvalid_ds = valid_gen.flow_from_dataframe(\n                            dataframe=train_csv,\n                            directory = images_dir_data_path,\n                            x_col = \"image_id\",\n                            y_col = \"label\",\n                            target_size = shape,\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":"code","source":"Image, Labels = next(train_ds)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(10, 10))\nfor i in range(9):\n    ax = plt.subplot(3, 3, i + 1)\n    plt.imshow(Image[i])\n    plt.title(label_class[np.argmax(Labels)])\n    plt.axis(\"off\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers, models\nimport tensorflow.keras.optimizers as Optimizer\n\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(200,kernel_size=(3,3),activation='relu',input_shape=(180, 180, 3)))\nmodel.add(layers.Conv2D(180,kernel_size=(3,3),activation='relu'))\nmodel.add(layers.Conv2D(180,kernel_size=(3,3),activation='relu'))\nmodel.add(layers.Conv2D(140,kernel_size=(3,3),activation='relu'))\nmodel.add(layers.MaxPool2D(5,5))\nmodel.add(layers.Conv2D(100,kernel_size=(3,3),activation='relu'))\nmodel.add(layers.Conv2D(50,kernel_size=(3,3),activation='relu'))\nmodel.add(layers.MaxPool2D(5,5))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(1080,activation='relu'))\nmodel.add(layers.Dense(520,activation='relu'))\nmodel.add(layers.Dense(260,activation='relu'))\nmodel.add(layers.Dense(180,activation='relu'))\nmodel.add(layers.Dense(100,activation='relu'))\nmodel.add(layers.Dense(50,activation='relu'))\nmodel.add(layers.Dropout(rate=0.5))\nmodel.add(layers.Dense(5,activation='softmax'))\n\nmodel.compile(optimizer=Optimizer.Adam(lr=0.0001),loss='categorical_crossentropy',metrics=['accuracy'])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Classifier = model.fit(train_ds, validation_data = valid_ds, epochs = 30)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#plt.plot(Classifier.history['accuracy'])\n#plt.plot(Classifier.history['val_accuracy'])\n#plt.title('Model accuracy')\n#plt.ylabel('Accuracy')\n#plt.xlabel('Epoch')\n#plt.legend(['Train', 'Test'], loc='upper left')\n#plt.show()\n                                        \n#plt.plot(Classifier.history['loss'])\n#plt.plot(Classifier.history['val_loss'])\n#plt.title('Model loss')\n#plt.ylabel('Loss')\n#plt.xlabel('Epoch')\n#plt.legend(['Train', 'Test'], loc='upper left')\n#plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#model.save('model.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.load_model(\"../input/model-folder/model.h5\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Predict Image"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_img_path = data_path+\"test_images/2216849948.jpg\"\n\nimg = cv2.imread(test_img_path)\nresized_img = cv2.resize(img, shape).reshape(-1, 180, 180, 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":"ss = pd.read_csv(data_path+'sample_submission.csv')\npreds = []\nfor image in ss.image_id:\n    img = tf.keras.preprocessing.image.load_img(data_path+'test_images/' + image)\n    img = tf.keras.preprocessing.image.img_to_array(img)\n    img = tf.keras.preprocessing.image.smart_resize(img, (180, 180))\n    img = tf.reshape(img, (-1, 180, 180, 3))\n    prediction = model.predict(img/255)\n    preds.append(np.argmax(prediction))\n\nsubmission = pd.DataFrame({'image_id': ss.image_id, 'label': preds})\nsubmission.to_csv('submission.csv', index=False) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.head()","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}