{"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\nimport 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","execution":{"iopub.status.busy":"2021-06-02T11:43:36.167967Z","iopub.execute_input":"2021-06-02T11:43:36.168422Z","iopub.status.idle":"2021-06-02T11:43:36.17482Z","shell.execute_reply.started":"2021-06-02T11:43:36.168388Z","shell.execute_reply":"2021-06-02T11:43:36.17408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_csv('/kaggle/input/cassava-leaf-disease-classification/train.csv',header=0)\ndf.head()\n'''label_map = pd.read_json(f'/kaggle/input/cassava-leaf-disease-classification/label_num_to_disease_map.json', \n                         orient='index')'''\ndict_label={\n  0: \"Cassava Bacterial Blight (CBB)\",\n  1: \"Cassava Brown Streak Disease (CBSD)\",\n  2: \"Cassava Green Mottle (CGM)\",\n  3: \"Cassava Mosaic Disease (CMD)\",\n  4: \"Healthy\"\n}","metadata":{"execution":{"iopub.status.busy":"2021-06-02T11:43:36.176216Z","iopub.execute_input":"2021-06-02T11:43:36.176704Z","iopub.status.idle":"2021-06-02T11:43:36.209898Z","shell.execute_reply.started":"2021-06-02T11:43:36.176666Z","shell.execute_reply":"2021-06-02T11:43:36.209194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['label'].replace(dict_label, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2021-06-02T11:43:36.211655Z","iopub.execute_input":"2021-06-02T11:43:36.21226Z","iopub.status.idle":"2021-06-02T11:43:36.219037Z","shell.execute_reply.started":"2021-06-02T11:43:36.212217Z","shell.execute_reply":"2021-06-02T11:43:36.218419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2021-06-02T11:43:36.220213Z","iopub.execute_input":"2021-06-02T11:43:36.220664Z","iopub.status.idle":"2021-06-02T11:43:36.236637Z","shell.execute_reply.started":"2021-06-02T11:43:36.220635Z","shell.execute_reply":"2021-06-02T11:43:36.235902Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.groupby('label').count()","metadata":{"execution":{"iopub.status.busy":"2021-06-02T11:43:36.237874Z","iopub.execute_input":"2021-06-02T11:43:36.238467Z","iopub.status.idle":"2021-06-02T11:43:36.258084Z","shell.execute_reply.started":"2021-06-02T11:43:36.238425Z","shell.execute_reply":"2021-06-02T11:43:36.257386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain, test = train_test_split(df, test_size=0.3, stratify=df.label)","metadata":{"execution":{"iopub.status.busy":"2021-06-02T11:43:36.259371Z","iopub.execute_input":"2021-06-02T11:43:36.259795Z","iopub.status.idle":"2021-06-02T11:43:36.297714Z","shell.execute_reply.started":"2021-06-02T11:43:36.259766Z","shell.execute_reply":"2021-06-02T11:43:36.296722Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.groupby('label').count()","metadata":{"execution":{"iopub.status.busy":"2021-06-02T11:43:36.298837Z","iopub.execute_input":"2021-06-02T11:43:36.299104Z","iopub.status.idle":"2021-06-02T11:43:36.314028Z","shell.execute_reply.started":"2021-06-02T11:43:36.299079Z","shell.execute_reply":"2021-06-02T11:43:36.312969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.groupby('label').count()","metadata":{"execution":{"iopub.status.busy":"2021-06-02T11:43:36.315947Z","iopub.execute_input":"2021-06-02T11:43:36.316247Z","iopub.status.idle":"2021-06-02T11:43:36.328493Z","shell.execute_reply.started":"2021-06-02T11:43:36.316219Z","shell.execute_reply":"2021-06-02T11:43:36.327655Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''#applying categorical encoding for labels\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OneHotEncoder\nct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [1])], remainder='passthrough')\ntrain_arr = ct.fit_transform(train)\ntest_arr = ct.transform(test)\nconvert_type = {'label1':int,'label2':int,'label3':int,'label4':int,'label5':int,'image_id':object}\ntrain=pd.DataFrame(train_arr, columns=['label1','label2','label3','label4','label5','image_id']).astype(convert_type)\ntest=pd.DataFrame(test_arr, columns=['label1','label2','label3','label4','label5','image_id']).astype(convert_type)'''","metadata":{"execution":{"iopub.status.busy":"2021-06-02T11:43:36.329815Z","iopub.execute_input":"2021-06-02T11:43:36.33033Z","iopub.status.idle":"2021-06-02T11:43:36.336887Z","shell.execute_reply.started":"2021-06-02T11:43:36.330297Z","shell.execute_reply":"2021-06-02T11:43:36.335772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(rescale = 1./255,\n                                   shear_range = 0.2,\n                                   zoom_range = 0.2,\n                                   horizontal_flip = True)\nfrom keras.utils import to_categorical\n\ntraining_set = train_datagen.flow_from_dataframe(train,directory='/kaggle/input/cassava-leaf-disease-classification/train_images',\n                                                 x_col=\"image_id\", y_col=\"label\",\n                                                 target_size = (64, 64),\n                                                 batch_size = 32,\n                                                 class_mode = 'categorical')\n\n# Preprocessing the Test set\ntest_datagen = ImageDataGenerator(rescale = 1./255)\ntest_set = test_datagen.flow_from_dataframe(test,directory='/kaggle/input/cassava-leaf-disease-classification/train_images',\n                                            x_col=\"image_id\", y_col=\"label\",\n                                            target_size = (64, 64),\n                                            batch_size = 32,\n                                            class_mode = 'categorical')","metadata":{"execution":{"iopub.status.busy":"2021-06-02T11:43:36.337846Z","iopub.execute_input":"2021-06-02T11:43:36.338101Z","iopub.status.idle":"2021-06-02T11:43:42.030788Z","shell.execute_reply.started":"2021-06-02T11:43:36.338076Z","shell.execute_reply":"2021-06-02T11:43:42.030098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Building the CNN\nfrom keras.models import Model,Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Dense,Flatten\n# Initialising the CNN\ncnn = tf.keras.models.Sequential()\n\n# Step 1 - Convolution\ncnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu', input_shape=[64, 64, 3]))\n# Step 2 - Pooling\ncnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))\n# Adding a second convolutional layer\ncnn.add(tf.keras.layers.Conv2D(filters=256, kernel_size=3, activation='relu'))\ncnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))\ncnn.add(tf.keras.layers.Flatten())\ncnn.add(tf.keras.layers.Dense(units=256, activation='relu'))\ncnn.add(tf.keras.layers.Dense(units=512, activation='relu'))\ncnn.add(tf.keras.layers.Dense(units=128, activation='relu'))\ncnn.add(Dropout(0.2))\ncnn.add(tf.keras.layers.Dense(units=64, activation='relu'))\ncnn.add(tf.keras.layers.Dense(units=5, activation='sigmoid'))\n\ncnn.summary()\n\n# Compiling the CNN\ncnn.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\nes = tf.keras.callbacks.EarlyStopping(\n    monitor=\"val_loss\",\n    patience=3\n)\n# Training the CNN on the Training set and evaluating it on the Test set\nhistory = cnn.fit(x = training_set, validation_data = test_set, epochs = 25, callbacks=[es])\nhistory.history['val_loss']","metadata":{"execution":{"iopub.status.busy":"2021-06-02T13:36:57.604998Z","iopub.execute_input":"2021-06-02T13:36:57.605636Z","iopub.status.idle":"2021-06-02T13:55:05.092675Z","shell.execute_reply.started":"2021-06-02T13:36:57.605599Z","shell.execute_reply":"2021-06-02T13:55:05.091624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing import image\ntest_image = image.load_img('/kaggle/input/cassava-leaf-disease-classification/test_images/2216849948.jpg', \n                            target_size = (64, 64))\ntest_image = image.img_to_array(test_image)\ntest_image = np.expand_dims(test_image, axis = 0)\nresult = cnn.predict(test_image)\nprint(training_set.class_indices)\nprint(result)","metadata":{"execution":{"iopub.status.busy":"2021-06-02T14:00:17.62776Z","iopub.execute_input":"2021-06-02T14:00:17.628208Z","iopub.status.idle":"2021-06-02T14:00:17.781408Z","shell.execute_reply.started":"2021-06-02T14:00:17.62817Z","shell.execute_reply":"2021-06-02T14:00:17.779576Z"},"trusted":true},"execution_count":null,"outputs":[]}]}