{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport os\nimport seaborn as sns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data=pd.read_csv(\"/kaggle/input/cassava-leaf-disease-classification/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.head()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data['label'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data['label'].hist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import json\nfile= open('/kaggle/input/cassava-leaf-disease-classification/label_num_to_disease_map.json')\nread_labels=json.load(file)\nread_labels={int(label):disease_name for label,disease_name in read_labels.items()}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data['disease_name']=data.label.map(read_labels)\ndata.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data['disease_name'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.drop('label',axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Dropout,Flatten\nfrom keras.layers import Conv2D,MaxPooling2D,Activation,AveragePooling2D,BatchNormalization\nfrom keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    validation_split = 0.2\n)\n\nvalid_datagen = ImageDataGenerator(\n    rescale=1/255,\n    validation_split = 0.2\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images_dir_path = \"/kaggle/input/cassava-leaf-disease-classification/train_images\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_width,img_height =256,256\ninput_shape=(img_width,img_height,3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size =32\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe=data,\n    directory = images_dir_path,\n    x_col = \"image_id\",\n    y_col = \"disease_name\",\n    target_size = (img_width,img_height),\n    class_mode = \"categorical\",\n    batch_size = batch_size\n)\n\nvalid_generator = valid_datagen.flow_from_dataframe(\n    dataframe = data,\n    directory = images_dir_path,\n    x_col = \"image_id\",\n    y_col = \"disease_name\",\n    target_size = (img_width,img_height),\n    class_mode = \"categorical\",\n    batch_size = batch_size\n)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(32, (5, 5),input_shape=input_shape,activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(3, 3)))\nmodel.add(Conv2D(32, (3, 3),activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(64, (3, 3),activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))   \nmodel.add(Flatten())\nmodel.add(Dense(512,activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Dense(128,activation='relu'))          \nmodel.add(Dense(5,activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\nopt=keras.optimizers.Adam(lr=0.001)\nmodel.compile(optimizer=opt,loss='categorical_crossentropy',metrics=['accuracy'])\ntrain=model.fit_generator(train_generator,\n                          epochs=15,\n                          steps_per_epoch=train_generator.samples // batch_size,\n                          validation_data=valid_generator)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Plottinf the accuracy\nacc = train.history['accuracy']\nval_acc = train.history['val_accuracy']\nloss = train.history['loss']\nval_loss = train.history['val_loss']\nepochs = range(1, len(acc) + 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Train and validation accuracy\nplt.plot(epochs, acc, 'b', label='Training accurarcy')\nplt.plot(epochs, val_acc, 'r', label='Validation accurarcy')\nplt.title('Training and Validation accurarcy')\nplt.legend()\nplt.figure()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Evaluating the model for unseen data\nscore,accuracy =model.evaluate(valid_generator,verbose=1)\nprint(\"Test score is {}\".format(score))\nprint(\"Test accuracy is {}\".format(accuracy))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Save entire model with optimizer, architecture, weights and training configuration.\nfrom keras.models import load_model\nmodel.save('model.h5')\n\n# Save model weights.\nfrom keras.models import load_model\nmodel.save_weights('model_weights.h5')","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}