{"cells":[{"metadata":{"id":"XTHgTst3tn8Y","outputId":"3c9cfe9a-4222-48e1-c212-da7568419130","trusted":true},"cell_type":"code","source":"import cv2\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.applications import vgg16\nimport zipfile\n\nprint(tf.__version__)\nprint(tf.executing_eagerly())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip', 'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working/')\n    \nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip', 'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working/')","execution_count":null,"outputs":[]},{"metadata":{"id":"Wio9ag90tn8d","trusted":true},"cell_type":"code","source":"import os\nfrom random import shuffle\nfrom glob import glob\n\nIMG_SIZE = (224, 224)\n\ntrain_files = glob('train/*.jpg')\ntest_files = glob('test/*.jpg')","execution_count":null,"outputs":[]},{"metadata":{"id":"hNS-Rn79gmTP","trusted":true},"cell_type":"code","source":"def load_image(path, target_size=IMG_SIZE):\n    img = cv2.imread(path)[...,::-1]\n    img = cv2.resize(img, target_size)\n    return vgg16.preprocess_input(img)\n\ndef fit_generator(files, batch_size=64):\n    batch_size = min(batch_size, len(files))\n    while True:\n        shuffle(files)\n        for k in range(len(files) // batch_size):\n            i = k * batch_size\n            j = i + batch_size\n            if j > len(files):\n                j = - j % len(files)\n            x = np.array([load_image(path) for path in files[i:j]])\n            y = np.array([1. if os.path.basename(path).startswith('dog') else 0.\n                          for path in files[i:j]])\n            yield (x, y)\n\ndef predict_generator(files):\n    while True:\n        for path in files:\n            yield np.array([load_image(path)])","execution_count":null,"outputs":[]},{"metadata":{"id":"LLG89UXTtn8h","outputId":"b1acac6b-fe96-4ef3-d8ff-879673a47902","trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline\n\nfig = plt.figure(figsize=(16, 8))\nfor i, path in enumerate(train_files[:10], 1):\n    subplot = fig.add_subplot(2, 5, i)\n    subplot.set_title('%s' % path.split('/')[-1])\n    img = cv2.imread(path)[...,::-1]\n    img = cv2.resize(img, IMG_SIZE)\n    plt.imshow(img);","execution_count":null,"outputs":[]},{"metadata":{"id":"cnQjlvIRtn8k","outputId":"e2f20e3f-ef76-43aa-d357-a47d89a1e3d6","trusted":true},"cell_type":"code","source":"base_model = vgg16.VGG16(weights='imagenet',\n                         include_top=False,\n                         input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3))","execution_count":null,"outputs":[]},{"metadata":{"id":"pd92ejXVtn8q","trusted":true},"cell_type":"code","source":"for layer in base_model.layers:\n    layer.trainable = False","execution_count":null,"outputs":[]},{"metadata":{"id":"7oKgESjkd5Iu","trusted":true},"cell_type":"code","source":"x = base_model.layers[-5].output\nx = tf.keras.layers.Flatten()(x)\nx = tf.keras.layers.BatchNormalization()(x)\nx = tf.keras.layers.Dense(1, activation='sigmoid',\n                                kernel_regularizer=tf.keras.regularizers.l1(1e-4))(x)","execution_count":null,"outputs":[]},{"metadata":{"id":"miCR6hzqfA-K","trusted":true},"cell_type":"code","source":"model = tf.keras.Model(inputs=base_model.input, outputs=x, name='dogs_vs_cats')","execution_count":null,"outputs":[]},{"metadata":{"id":"wIeDdKNXtn8w","trusted":true},"cell_type":"code","source":"model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-5, epsilon=1e-8), \n              loss='binary_crossentropy',\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.utils import plot_model\nplot_model(model, show_shapes=True, show_layer_names=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"id":"371wY174fFhc","trusted":true},"cell_type":"code","source":"reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(\n                              monitor='val_loss',\n                              patience=5,\n                              min_delta=1e-7,\n                              verbose=2,\n                              factor=.5,\n                              min_lr=1e-10,\n                              mode='auto')\n\nearly_stopping = tf.keras.callbacks.EarlyStopping(\n                              monitor='val_loss',\n                              min_delta=1e-7,\n                              patience=5,\n                              verbose=2,\n                              mode='auto',\n                              restore_best_weights=False)\n\nmodel_checkpoint = tf.keras.callbacks.ModelCheckpoint(\n                              'model_VGG16_custom.h5',\n                              monitor='val_loss',\n                              verbose=1, \n                              save_best_only=True, \n                              save_weights_only=True,\n                              mode='min')","execution_count":null,"outputs":[]},{"metadata":{"id":"h0LRFFzyfE3p","trusted":true},"cell_type":"code","source":"shuffle(train_files)\nvalidation_data = next(fit_generator(train_files))\ntrain_data = fit_generator(train_files)","execution_count":null,"outputs":[]},{"metadata":{"scrolled":false,"id":"5yVzIocktn8z","outputId":"06d02cde-be79-4f84-fcb3-68b6d8803d76","trusted":true},"cell_type":"code","source":"hist = model.fit(train_data,\n                 batch_size=128,\n                 steps_per_epoch=100,\n                 epochs=100,\n                 validation_data=validation_data,\n                 callbacks=[model_checkpoint, reduce_lr, early_stopping])","execution_count":null,"outputs":[]},{"metadata":{"id":"GbcYKRBjjcUr","outputId":"45c31279-e2ac-42de-ac9c-f088396b2f27","trusted":true},"cell_type":"code","source":"plt.figure(figsize=(16,4))\nplt.subplot(121)\nplt.plot(hist.history['accuracy'])\nplt.plot(hist.history['val_accuracy'])\nplt.legend(['accuracy', 'val_accuracy'])\nplt.title(('accuracy = {}\\nval_accuracy = {}'.format(round(hist.history['accuracy'][-1],3), \n                                                   round(hist.history['val_accuracy'][-1],3))), fontsize=14)\nplt.grid(True)\nplt.subplot(122)\nplt.plot(hist.history['loss'])\nplt.plot(hist.history['val_loss'])\nplt.legend(['loss','val_loss'])\nplt.title(('loss = {}\\nval_loss = {}'.format(round(hist.history['loss'][-1],3), \n                                           round(hist.history['val_loss'][-1],3))), fontsize=14)\nplt.grid(True)\nplt.show();","execution_count":null,"outputs":[]},{"metadata":{"id":"4wzXSgGaZyew","trusted":true},"cell_type":"code","source":"model.load_weights('model_VGG16_custom.h5')","execution_count":null,"outputs":[]},{"metadata":{"id":"3OEEBce9tn85","trusted":true},"cell_type":"code","source":"test_pred = model.predict(predict_generator(test_files),\n                          steps=len(test_files))","execution_count":null,"outputs":[]},{"metadata":{"id":"iDADjuRKtn88","trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(16, 8))\nfor i, (path, score) in enumerate(zip(test_files[:10], test_pred[:10]), 1):\n    subplot = fig.add_subplot(2, 5, i)\n    subplot.set_title('%.2f %s' % (score, os.path.basename(path)))\n    img = cv2.imread(path)[...,::-1]\n    img = cv2.resize(img, IMG_SIZE)\n    subplot.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"id":"tmER55AHtn8_","outputId":"404886e6-4a3a-4e4f-8e63-0ed83947b772","trusted":true},"cell_type":"code","source":"import pandas as pd\n\nsubmission = pd.DataFrame(columns=['id', 'label'], index=[i for i in range(len(test_pred))])\n\nfor name, score, row in zip(test_files, test_pred, range(len(test_pred))):\n    submission.loc[row]['id'] = name.split('/')[1].split('.')[0]\n    submission.loc[row]['label'] = float(np.round(score, decimals=5))\n\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"id":"5bxxygRHr1dU","trusted":true},"cell_type":"code","source":"submission.to_csv('submission.csv', index=False)","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}