{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np \nimport pandas as pd\nimport gc\nimport random\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils import to_categorical\nfrom tqdm import tqdm\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import img_to_array, load_img, ImageDataGenerator\nimport cv2\nfrom random import shuffle\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization\n\n\ndata = pd.read_csv('../input/cassava-leaf-disease-classification/train.csv')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#data['label'] = data['label'].astype(str)\n\nframe  =[\n        data[data['label']==3].sample(n=900,replace=True),\n        data[data['label']==1].sample(n=900,replace=True),\n        data[data['label']==2].sample(n=900,replace=True),\n        data[data['label']==4].sample(n=900,replace=True),\n        data[data['label']==0].sample(n=900,replace=True)]\n\n\ndf = pd.concat(frame)\ndf = df.iloc[np.random.permutation(len(df))]\n\ndel data,frame \ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Preprocessing Training Images"},{"metadata":{"trusted":true},"cell_type":"code","source":"\nimages_train = []\nlabel_image = []\n\nfor (file,label) in tqdm(zip(df['image_id'],df['label'])):\n    img = cv2.imread('../input/cassava-leaf-disease-classification/train_images/'+file, cv2.IMREAD_COLOR)       \n    img = cv2.resize(img, (100, 100))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    imgs = img.reshape((1,) + img.shape)\n    img = img/255.0\n    data_generator = ImageDataGenerator(rotation_range=45, \n                                        width_shift_range=0.2,\n                                        horizontal_flip=True,\n                                        vertical_flip=True,\n                                        zoom_range=[.1, .3])\n    data_generator.fit(imgs)\n    image_iterator = data_generator.flow(imgs)\n    for x in range(3):\n        img_transformed=image_iterator.next()[0].astype('int')/255\n        images_train.append(img_transformed)\n        label_image.append(label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = np.array(images_train)\nxtrain, xtest, ytrain, ytest = train_test_split(train,label_image, test_size=0.1, random_state = 42 )\n\ndel images_train,df,train,label_image\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y = ytrain\nYtrain = to_categorical(Y)\n\nz = ytest\nYtest = to_categorical(z)\n\ndel ytrain\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Preprocessing Test images"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing import image\n\nimg = cv2.imread('../input/cassava-leaf-disease-classification/test_images/2216849948.jpg', cv2.IMREAD_COLOR)\nimg = cv2.resize(img, (100, 100))\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\nimg = image.img_to_array(img)\nimg = img/255.0\nTest = np.array(img)\nTest = Test.reshape(1,Test.shape[0],Test.shape[1],Test.shape[2])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Modeling"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='sigmoid', input_shape=(100, 100, 3)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(5, activation='softmax'))\n\n\nmodel.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(xtrain, Ytrain,epochs=50, batch_size = 100, validation_data=(xtest, Ytest))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred = model.predict(Test)\nlabel_predicted=np.argmax(pred, axis=-1)\n\nlabel_predicted","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame({'image_id':'2216849948.jpg' ,'label':label_predicted})\nsubmission.to_csv(\"submission.csv\", index = False, header = True)","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}