{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":18199,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Import Library","metadata":{"_uuid":"fe76d1d1ded592430e7548feacfa38dc42f085d9"}},{"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)\n\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\n\nimport os\nprint(os.listdir(\"../input\"))\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Prepare Traning Data","metadata":{"_uuid":"7335a579cc0268fba5d34d6f7558f33c187eedb3"}},{"cell_type":"code","source":"filenames = os.listdir(\"../input/train/train\")\ncategories = []\nfor filename in filenames:\n    category = filename.split('.')[0]\n    if category == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n\ndf = pd.DataFrame({\n    'filename': filenames,\n    'category': categories\n})\ndf.head()","metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### See Total In count","metadata":{"_uuid":"a999484fc35b73373fafe2253ae9db7ff46fdb90"}},{"cell_type":"code","source":"df['category'].value_counts().plot.bar()","metadata":{"_uuid":"fa26f0bc7a6d835a24989790b20f3c6f32946f45","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# See sample image","metadata":{"_uuid":"400a293df3c8499059d9175f3915187074efd971"}},{"cell_type":"code","source":"sample = random.choice(filenames)\nimage = load_img(\"../input/train/train/\"+sample)\nplt.imshow(image)","metadata":{"_uuid":"602b40f7353871cb161c60b5237f0da0096b2f47","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Build Model","metadata":{"_uuid":"b244e6b7715a04fc6df92dd6dfa3d35c473ca600"}},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras import layers\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation,GlobalMaxPooling2D\nfrom keras import applications\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import optimizers\nfrom keras.applications import VGG16\nfrom keras.models import Model\n\nimage_size = 224\ninput_shape = (image_size, image_size, 3)\n\nepochs = 5\nbatch_size = 16\n\npre_trained_model = VGG16(input_shape=input_shape, include_top=False, weights=\"imagenet\")\n    \nfor layer in pre_trained_model.layers[:15]:\n    layer.trainable = False\n\nfor layer in pre_trained_model.layers[15:]:\n    layer.trainable = True\n    \nlast_layer = pre_trained_model.get_layer('block5_pool')\nlast_output = last_layer.output\n    \n# Flatten the output layer to 1 dimension\nx = GlobalMaxPooling2D()(last_output)\n# Add a fully connected layer with 512 hidden units and ReLU activation\nx = Dense(512, activation='relu')(x)\n# Add a dropout rate of 0.5\nx = Dropout(0.5)(x)\n# Add a final sigmoid layer for classification\nx = layers.Dense(1, activation='sigmoid')(x)\n\nmodel = Model(pre_trained_model.input, x)\n\nmodel.compile(loss='binary_crossentropy',\n              optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),\n              metrics=['accuracy'])\n\nmodel.summary()","metadata":{"_uuid":"8c9f833c1441b657c779844912d0b8028218d454","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Prepare Test and Train Data","metadata":{"_uuid":"a29ebfd697dd7183a1a1345ea41ec138874340b7"}},{"cell_type":"code","source":"train_df, validate_df = train_test_split(df, test_size=0.1)\ntrain_df = train_df.reset_index()\nvalidate_df = validate_df.reset_index()\n\n# validate_df = validate_df.sample(n=100).reset_index() # use for fast testing code purpose\n# train_df = train_df.sample(n=1800).reset_index() # use for fast testing code purpose\n\ntotal_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]","metadata":{"_uuid":"4eeb7af8dcf02c4ef5ca744c8305c51a2f5cedef","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Traning Generator","metadata":{"_uuid":"ff760be9104f7d9492467b8d9d3405011aa77d11"}},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rotation_range=15,\n    rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest',\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df, \n    \"../input/train/train/\", \n    x_col='filename',\n    y_col='category',\n    class_mode='binary',\n    target_size=(image_size, image_size),\n    batch_size=batch_size\n)","metadata":{"_uuid":"4d1c7818703a8a4bac5c036fdea45972aa9e5e9e","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Validation Generator","metadata":{"_uuid":"859c7b2857939c19fd2e3bb32839c9f7deb5aa3f"}},{"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale=1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    \"../input/train/train/\", \n    x_col='filename',\n    y_col='category',\n    class_mode='binary',\n    target_size=(image_size, image_size),\n    batch_size=batch_size\n)","metadata":{"_uuid":"7925e16bcacc89f4484fb6fe47e54d6420af732e","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# See sample generated images","metadata":{"_uuid":"6e17fc1f002fedd60febb78fee5e81770640b909"}},{"cell_type":"code","source":"example_df = train_df.sample(n=1).reset_index(drop=True)\nexample_generator = train_datagen.flow_from_dataframe(\n    example_df, \n    \"../input/train/train/\", \n    x_col='filename',\n    y_col='category',\n    class_mode='binary'\n)\nplt.figure(figsize=(12, 12))\nfor i in range(0, 9):\n    plt.subplot(3, 3, i+1)\n    for X_batch, Y_batch in example_generator:\n        image = X_batch[0]\n        plt.imshow(image)\n        break\nplt.tight_layout()\nplt.show()","metadata":{"_uuid":"23d923dba747f8b47dc75569244cecc6f70df321","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Fit Model","metadata":{"_uuid":"5cd8df64e794ed17de326b613a9819e7da977a0e"}},{"cell_type":"code","source":"# fine-tune the model\nhistory = model.fit_generator(\n    train_generator,\n    epochs=epochs,\n    validation_data=validation_generator,\n    validation_steps=total_validate//batch_size,\n    steps_per_epoch=total_train//batch_size)","metadata":{"_uuid":"0836a4cc8aa0abf603e0f96573c0c4ff383ad56b","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{"_uuid":"a624dbb9f5195e47f79c8f2a73d63d337b3cffa2"}},{"cell_type":"code","source":"loss, accuracy = model.evaluate_generator(validation_generator, total_validate//batch_size, workers=12)\nprint(\"Test: accuracy = %f  ;  loss = %f \" % (accuracy, loss))","metadata":{"_uuid":"e196e7807ffd55aa404481acdf2fc96e01c238aa","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def plot_model_history(model_history, acc='acc', val_acc='val_acc'):\n    fig, axs = plt.subplots(1,2,figsize=(15,5))\n    axs[0].plot(range(1,len(model_history.history[acc])+1),model_history.history[acc])\n    axs[0].plot(range(1,len(model_history.history[val_acc])+1),model_history.history[val_acc])\n    axs[0].set_title('Model Accuracy')\n    axs[0].set_ylabel('Accuracy')\n    axs[0].set_xlabel('Epoch')\n    axs[0].set_xticks(np.arange(1,len(model_history.history[acc])+1),len(model_history.history[acc])/10)\n    axs[0].legend(['train', 'val'], loc='best')\n    axs[1].plot(range(1,len(model_history.history['loss'])+1),model_history.history['loss'])\n    axs[1].plot(range(1,len(model_history.history['val_loss'])+1),model_history.history['val_loss'])\n    axs[1].set_title('Model Loss')\n    axs[1].set_ylabel('Loss')\n    axs[1].set_xlabel('Epoch')\n    axs[1].set_xticks(np.arange(1,len(model_history.history['loss'])+1),len(model_history.history['loss'])/10)\n    axs[1].legend(['train', 'val'], loc='best')\n    plt.show()\n    \nplot_model_history(history)","metadata":{"_uuid":"37e05b06e4131600f27d663f2098a2310750f13c","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Y_val = validate_df['category']\ny_pred =  model.predict_generator(validation_generator)","metadata":{"_uuid":"800b2cbabf53dd1725edfa1d82bcf31f05217222","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"threshold = 0.5\ny_final = np.where(y_pred > threshold, 1,0)","metadata":{"_uuid":"834bd766b3fa473bf85328d10625a38adbfb5cd9","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_final.size","metadata":{"_uuid":"7c427f212c00d161924fa5747c8dc23b19e9787a","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import seaborn as sns\nfrom sklearn.metrics import confusion_matrix\n# Predict the values from the validation dataset\n\n# compute the confusion matrix\nconfusion_mtx = confusion_matrix(Y_val, y_final) \n# plot the confusion matrix\nf,ax = plt.subplots(figsize=(8, 8))\nsns.heatmap(confusion_mtx, annot=True, linewidths=0.01,cmap=\"Greens\",linecolor=\"gray\", fmt= '.1f',ax=ax)\nplt.xlabel(\"Predicted Label\")\nplt.ylabel(\"True Label\")\nplt.title(\"Confusion Matrix\")\nplt.show()","metadata":{"_uuid":"875a42b6dee96997a8cbc4f4d7839aabd047cae0","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import classification_report\n\n# Generate a classification report\nreport = classification_report(Y_val, y_final, target_names=['0','1'])\n\nprint(report)","metadata":{"_uuid":"20e4ce1c5271a7f36364a69972ba3c3f1219ee6a","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Prepare Testing Data","metadata":{"_uuid":"764dc66e4b2bc558f3a0f90b80bb802f5b3d45a8"}},{"cell_type":"code","source":"test_filenames = os.listdir(\"../input/test1/test1\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]","metadata":{"_uuid":"c35e70d3e1e4834dbbf840fa0ea08c049bfcd915","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Create Testing Generator","metadata":{"_uuid":"291bc3996dce8d05e174b27d64f03996d3e8038e"}},{"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    \"../input/test1/test1/\", \n    x_col='filename',\n    y_col=None,\n    class_mode=None,\n    batch_size=batch_size,\n    target_size=(image_size, image_size),\n    shuffle=False\n)","metadata":{"_uuid":"52249ec1c35fb1be3adef386be245de3794e55aa","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Predict","metadata":{"_uuid":"2fa580afca2931ec5ce374e732d8c1789d03f2ed"}},{"cell_type":"code","source":"predict = model.predict_generator(test_generator, steps=np.ceil(nb_samples/batch_size))\nthreshold = 0.5\ntest_df['category'] = np.where(predict > threshold, 1,0)","metadata":{"_uuid":"4782eb23fa7d003f0e2415d995894017edb2d896","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# See predicted result","metadata":{"_uuid":"ce72a83f80d6e012b12b82c8ee3365d671a3b307"}},{"cell_type":"code","source":"sample_test = test_df.sample(n=9).reset_index()\nsample_test.head()\nplt.figure(figsize=(12, 12))\nfor index, row in sample_test.iterrows():\n    filename = row['filename']\n    category = row['category']\n    img = load_img(\"../input/test1/test1/\"+filename, target_size=(256, 256))\n    plt.subplot(3, 3, index+1)\n    plt.imshow(img)\n    plt.xlabel(filename + '(' + \"{}\".format(category) + ')')\nplt.tight_layout()\nplt.show()","metadata":{"_uuid":"98b41dc83075e6297137fb45bf703c313dd4ae28","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Submission","metadata":{"_uuid":"d1ca25943e73aa20a37f9fb8670ee430caeaaf1f"}},{"cell_type":"code","source":"submission_df = test_df.copy()\nsubmission_df['id'] = submission_df['filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['category']\nsubmission_df.drop(['filename', 'category'], axis=1, inplace=True)\nsubmission_df.to_csv('submission_13010030.csv', index=False)\n\nplt.figure(figsize=(10,5))\nsns.countplot(submission_df['label'])\nplt.title(\"(Test data)\")","metadata":{"_uuid":"cce9f3e2ffff0693d79d84590ed71fbbca7c3c7c","trusted":true},"outputs":[],"execution_count":null}]}