{"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 \n\nimport glob\nimport gc\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D, BatchNormalization\nfrom keras.losses import categorical_crossentropy\n\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OneHotEncoder","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def crop_center(pil_img, crop_width, crop_height):\n    img_width, img_height = pil_img.size\n    return pil_img.crop(((img_width - crop_width) // 2,\n                         (img_height - crop_height) // 2,\n                         (img_width + crop_width) // 2,\n                         (img_height + crop_height) // 2))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#size=300,200\n\n\ndef prepare(data):\n    if data== 'train':\n        frag = glob.glob('../input/cassava-leaf-disease-classification/train_images/*')\n        train = pd.read_csv('../input/cassava-leaf-disease-classification/train.csv')\n        indexs = []\n        array=[]\n        y_=[]\n        y=[]\n\n        #pbar = ProgressBar()    \n        for i in range(0,len(frag)):\n            indexs =  np.append(indexs,frag[i].split('train_images/')[1])\n            y.append(train[train['image_id']==indexs[i]]['label'].values)\n            y_.append(y[i][0])\n            \n            image = Image.open(frag[i])\n            image = crop_center(image,200,200)\n            array.append(np.asarray(image))\n        \n        array = np.asarray(array)\n            \n        y_=np.asarray(y_)  #risparmio memoria usando 'sparse_categorical_crossentropy'\n       \n        #y_ = np.matrix(pd.get_dummies(y_)) #per usare 'categorical_crossentropy'\n\n        return(array,y_)\n    \n    if data=='test':\n        image = Image.open('../input/cassava-leaf-disease-classification/test_images/2216849948.jpg')\n        image = crop_Center(image,200,200)\n        image = np.array(image)\n        image = np.float32(image)\n        image = np.expand_dims(image,axis=0)\n    return(image)\n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nx,y = prepare('train')\n\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#preprocessing.scale(x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_val, y_train, y_val = train_test_split(x,y, random_state=1, test_size=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_features = 32\nnum_labels=5\nbatch_size = 64\n\nmodel =  Sequential()\n\n#model.add(BatchNormalization())     \nmodel.add(Conv2D(num_features, kernel_size=(3, 3), activation='relu', input_shape=(200,200,3)))  #300,200\n#model.add(Conv2D(2*num_features, kernel_size=(3, 3), activation='relu', padding='same'))\nmodel.add(BatchNormalization()) \nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(Dropout(0.3))\n\nmodel.add(Flatten())\n\n#model.add(Dense(2*num_features, activation='relu'))\n#model.add(Dropout(0.3))\nmodel.add(Dense(num_features, activation='relu'))\nmodel.add(Dropout(0.3))\n\nmodel.add(Dense(num_labels, activation='softmax'))\nmodel.compile(loss='sparse_categorical_crossentropy', \n              optimizer='adam',\n              metrics=['accuracy'])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time \nhistory = model.fit(X_train,y_train,epochs=25,verbose=1, validation_data= (X_val,y_val),batch_size = batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_frame = pd.DataFrame(history.history)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_frame.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(8,6))\nsns.lineplot(x = range(0,len(history_frame)) , y = history_frame['loss'],label = 'Training Loss')\nsns.lineplot(x = range(0,len(history_frame))  , y = history_frame['val_loss'],label='Validation Loss')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(8,6))\nsns.lineplot(x = range(0,len(history_frame)) , y = history_frame['accuracy'],label = 'Training accuracy')\nsns.lineplot(x = range(0,len(history_frame))  , y = history_frame['val_accuracy'],label='Validation accuracy')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = prepare('test')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valore = model.predict(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def sub(valore):\n    original = pd.DataFrame(valore).idxmax(axis=1)\n    value =  original[0]\n    submission = pd.read_csv('../input/cassava-leaf-disease-classification/sample_submission.csv')\n    submission['label'] = value \n    submission.to_csv('submission.csv', index=False)\n    print(submission)\n    print('  Finished!  ')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub(valore)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"frag = glob.glob('../input/cassava-leaf-disease-classification/train_images/*')","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}