{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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)\nimport matplotlib.pyplot as plt\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\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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"dataset=pd.read_csv(\"../input/cassava-leaf-disease-classification/train.csv\")\ndataset=pd.DataFrame(dataset)\ndataset.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Activation,GlobalAveragePooling2D\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DATA_DIR=\"../input/cassava-leaf-disease-classification\"\nTEST_DATA=\"../input/cassava-leaf-disease-classification/test_images\"\nTRAIN_DATA=\"../input/cassava-leaf-disease-classification/train_images\"\ncsv_file=\"../input/cassava-leaf-disease-classification/train.csv\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels=dataset.label.unique()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def one_hot_encoding(data):\n    output=data.label\n    data[str(output)]=1\n    \n    return data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in labels:\n    dataset[str(i)]=0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset=dataset.apply(one_hot_encoding,axis=1)\ndataset.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Target_Size=(224,224)\nfrom tensorflow.keras.preprocessing import image\ndef show_image(image_path):\n    imag=image.load_img(image_path,target_size=Target_Size)\n    x=image.img_to_array(imag)\n    x=x/255\n    plt.imshow(x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_image(\"../input/cassava-leaf-disease-classification/train_images/1000015157.jpg\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y=list(dataset.columns[2:])\nY","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Train_Data=ImageDataGenerator(rescale=1/255.,\n                             validation_split=0.2,\n                            rotation_range=90,\n                              width_shift_range=0.2,\n                              height_shift_range=0.2,\n                              horizontal_flip=True,\n                              vertical_flip=True,\n                             )\nTrain=Train_Data.flow_from_dataframe(\n        dataframe=dataset,\n        directory=TRAIN_DATA,\n        x_col=\"image_id\",\n        y_col=Y,\n        shuffle=True,\n        batch_size=32,\n        subset=\"training\",\n        class_mode=\"raw\",\n        target_size=Target_Size,\n        seed=42\n    )\n\nValidation=Train_Data.flow_from_dataframe(\n        dataframe=dataset,\n        directory=TRAIN_DATA,\n        x_col=\"image_id\",\n        y_col=Y,\n        shuffle=True,\n        batch_size=32,\n        subset=\"validation\",\n        class_mode=\"raw\",\n        target_size=Target_Size,\n        seed=42\n    )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# !mkdir ~/.keras\n# !mkdir ~/.keras/models\n# !cp ../input/keras-pretrained-models/*notop* ~/.keras/models/\n# !cp ../input/keras-pretrained-models/imagenet_class_index.json ~/.keras/models/","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"D=tf.keras.applications.Xception(\n    include_top=False, weights='../input/keras-pretrained-models/xception_weights_tf_dim_ordering_tf_kernels_notop.h5', input_shape=(224,224,3))\n\ninp = keras.layers.Input([224, 224, 3])\nx = tf.keras.applications.xception.preprocess_input(inp)\nx=D(x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras import Model\nx=GlobalAveragePooling2D()(x)\nx=Dropout(0.4)(x)\nout=Dense(5,activation=\"softmax\")(x)\nmodel=Model(inp,out)\nmodel.summary()\nmodel.compile(optimizer=Adam(lr=(0.001)),loss=\"categorical_crossentropy\", metrics='accuracy')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ee=EarlyStopping(monitor='val_loss', patience=10, verbose=1)\nhistory=model.fit(\nTrain,\nepochs=5,\nsteps_per_epoch=17118//5,\nvalidation_data=Validation,\nvalidation_steps=4279//5,\ncallbacks=[EarlyStopping(monitor = 'val_accuracy', min_delta = 1e-4, patience = 20, mode = 'max', \n                    restore_best_weights = True, verbose = 0),ModelCheckpoint('model.h5',monitor = 'val_accuracy',\n                      verbose = 0, save_best_only = True, mode = 'max')]\n)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_image(\"../input/cassava-leaf-disease-classification/test_images/2216849948.jpg\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from PIL import Image\ndef predict_(path):\n    img=Image.open(path)\n    img=img.resize((224,224))\n    img=np.expand_dims(img,axis=0)\n    y_pred=model.predict(img)\n    return y_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred=predict_(\"../input/cassava-leaf-disease-classification/test_images/2216849948.jpg\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(np.argmax(y_pred))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"counter=[]\nfor k,i in enumerate(os.listdir(TEST_DATA)):\n    df={'image_id':i,'label':labels[np.argmax(predict_(TEST_DATA+'/'+i))]}\n    counter.append(k)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df=pd.DataFrame(df,index=counter)\ndf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.to_csv('submission.csv',index=False)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}