{"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\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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import RMSprop\nimport numpy as np\nimport os","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.read_csv('../input/cassava-leaf-disease-classification/train.csv')\ndata","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label_dict = {\n0:\"Cassava Bacterial Blight (CBB)\",\n1:\"Cassava Brown Streak Disease (CBSD)\",\n2:\"Cassava Green Mottle (CGM)\",\n3:\"Cassava Mosaic Disease (CMD)\",\n4:\"Healthy\"\n}\nlabel_dict","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data['label'].replace(label_dict, inplace=True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain, valid = train_test_split(data, test_size=0.3, stratify=data.label)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale = 1/255.0)\ntrain_data = train_datagen.flow_from_dataframe(train ,directory='../input/cassava-leaf-disease-classification/train_images',\n                                                    x_col=\"image_id\" , y_col=\"label\", target_size=(300, 300), color_mode=\"rgb\",\n                                                    class_mode=\"categorical\",batch_size=128)\nvalid_data = train_datagen.flow_from_dataframe(valid ,directory='../input/cassava-leaf-disease-classification/train_images',\n                                                    x_col=\"image_id\" , y_col=\"label\", target_size=(300, 300), color_mode=\"rgb\",\n                                                    class_mode=\"categorical\",batch_size=32)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(16, (3,3), activation = 'relu', input_shape = (300,300,3)),\n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Conv2D(32, (3,3), activation = 'relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Conv2D(64, (3,3), activation = 'relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Conv2D(64, (3,3), activation = 'relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Conv2D(64, (3,3), activation = 'relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(512,activation = 'relu'),\n    tf.keras.layers.Dense(5,activation = 'softmax')\n])\nmodel.compile(optimizer=RMSprop(learning_rate=0.001),\n              loss = 'categorical_crossentropy',\n              metrics = ['accuracy'])\ncallback = tf.keras.callbacks.EarlyStopping(\n    monitor=\"val_loss\",\n    patience=3,\n    restore_best_weights=True\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(train_data,\n          epochs = 20,\n          validation_data = valid_data,\n          callbacks = [callback],verbose = 1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('cassava-model.h5')","metadata":{"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 = (300, 300))\ntest_image = image.img_to_array(test_image)\ntest_image = np.expand_dims(test_image, axis = 0)\nresult = model.predict(test_image)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_data = pd.DataFrame(columns = ['image_id','label'])\nsubmission_data['image_id'] = os.listdir('../input/cassava-leaf-disease-classification/test_images')\nsubmission_data['label'] = np.argmax(result)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_data.to_csv('submission.csv',index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}