{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os, shutil\nfrom keras import layers, models, optimizers\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array, smart_resize\nfrom keras.callbacks import EarlyStopping, LearningRateScheduler, ReduceLROnPlateau, ModelCheckpoint\nfrom keras.applications import VGG16\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tf.test.is_gpu_available(\n    cuda_only=False, min_cuda_compute_capability=None\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = pd.read_csv(\"../input/cassava-leaf-disease-classification/train.csv\")\nlabels.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels['label']=labels['label'].astype(str)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dir = '../input/cassava-leaf-disease-classification/train_images'\ntest_dir = '../input/cassava-leaf-disease-classification/test_images'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale=1./225,\n                                   rotation_range=40,\n                                   width_shift_range=0.2,\n                                   height_shift_range=0.2,\n                                   shear_range=0.2,\n                                   zoom_range=0.2,\n                                   validation_split=0.3,\n                                   horizontal_flip=True,)\n\n\ntest_datagen = ImageDataGenerator(rescale=1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = train_datagen.flow_from_dataframe(dataframe=labels,\n                                                    directory=train_dir,\n                                                    subset='training',\n                                                    x_col=\"image_id\",\n                                                    y_col=\"label\",\n                                                    shuffle=True,\n                                                    target_size=(150,150),\n                                                    batch_size=32,\n                                                    class_mode='categorical')\n\nvalid_generator = train_datagen.flow_from_dataframe(dataframe=labels,\n                                                    directory=train_dir,\n                                                    subset='validation',\n                                                    x_col=\"image_id\",\n                                                    y_col=\"label\",\n                                                    shuffle=True,\n                                                    target_size=(150,150),\n                                                    batch_size=32,\n                                                    class_mode='categorical')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# conv_base = VGG16(weights='imagenet', include_top=False, input_shape=(150,150,3))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = models.Sequential()\n# model.add(conv_base)\nmodel.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=(150,150,3)))\nmodel.add(layers.MaxPooling2D(2,2))\nmodel.add(layers.Conv2D(64, (3,3), activation='relu'))\nmodel.add(layers.MaxPooling2D(2,2))\nmodel.add(layers.Conv2D(128, (3,3), activation='relu'))\nmodel.add(layers.MaxPooling2D(2,2))\nmodel.add(layers.Conv2D(128, (3,3), activation='relu'))\nmodel.add(layers.MaxPooling2D(2,2))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(512, activation='relu'))\nmodel.add(layers.Dense(5, activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy',\n             optimizer=optimizers.Adam(),\n             metrics=['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"callback_list = [\n    EarlyStopping(monitor='val_acc',patience=2),\n    ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=1),\n    ModelCheckpoint(filepath='{epoch:02d}-{val_acc:.4f}.hdf5', monitor='val_loss',save_best_only=True),\n]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(train_generator,steps_per_epoch=30,\n                    validation_data=valid_generator,validation_steps=30,\n                    callbacks=callback_list, epochs=100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"acc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(acc)+1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure()\n\nplt.plot(epochs, acc, 'bo', label='Train Acc')\nplt.plot(epochs, val_acc, 'b', label='Validation Acc')\nplt.title('Training and validation Acc')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'bo', label='Train Loss')\nplt.plot(epochs, val_loss, 'b', label='Validation Loss')\nplt.title('Training and validation Loss')\nplt.legend()\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.read_csv(\"../input/cassava-leaf-disease-classification/sample_submission.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = load_img(\"../input/cassava-leaf-disease-classification/test_images/2216849948.jpg\")\nimg = img_to_array(img)\nimg = smart_resize(img, (150,150))\nimg = tf.reshape(img, (-1, 150, 150, 3))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred = model.predict(img/255.)\npred = np.argmax(pred)\nsubmission_result = pd.DataFrame({'image_id' : submission.image_id, 'label' : pred})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_result.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Competetion Complete!!\")","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}