{"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)\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\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\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":{"trusted":true},"cell_type":"code","source":"#where am I?\n!pwd","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!apt-get install tree","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#list the directory tree of 'kaggle'\n!tree '/kaggle'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Unzip files\nimport zipfile\n\n# Since the input folder is read-only, lets create a folder called data and put the images there\nbase_dir = '../input/dogs-vs-cats-redux-kernels-edition'\ntrain_dir = '../data/train'\ntest_dir = '../data/test'\n\n# Extract All Data From Zip to \"../data\" Directory\nwith zipfile.ZipFile(os.path.join(base_dir, 'train.zip')) as train_zip:\n    train_zip.extractall('../data')\n    \nwith zipfile.ZipFile(os.path.join(base_dir, 'test.zip')) as test_zip:\n    test_zip.extractall('../data')\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#list the directory tree but ignore the images (since it will flood the output)\n!tree '/kaggle' -I '*.jpg'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Check Current Directory\nos.listdir(base_dir)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"#Check the images\nos.listdir(train_dir)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Images in train_dir\nlen(os.listdir(train_dir))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Images in test_dir\nlen(os.listdir(test_dir))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\nfrom PIL import Image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import glob","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# put the FilePath images into a List\ntrain_list = glob.glob(os.path.join(train_dir, '*.jpg'))\ntest_list = glob.glob(os.path.join(test_dir, '*.jpg'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Show some images (Train images)\nfig=plt.figure(figsize=(14, 10))\ncolumns = 4\nrows = 5\nfor i in range(1, columns*rows +1):\n    photo_num = np.random.randint(len(train_list))\n    img = Image.open(train_list[photo_num])\n    fig.add_subplot(rows, columns, i)\n    plt.axis('off')\n    plt.imshow(img)\nplt.suptitle(\"Train Images\", fontsize = 22)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Show some images (Test images)\nfig=plt.figure(figsize=(14, 10))\ncolumns = 4\nrows = 5\nfor i in range(1, columns*rows +1):\n    photo_num = np.random.randint(len(test_list))\n    img = Image.open(train_list[photo_num])\n    fig.add_subplot(rows, columns, i)\n    plt.axis('off')\n    plt.imshow(img)\nplt.suptitle(\"Test Images\", fontsize = 22)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Get the list of filenames in train_dir\nlist_of_images_names = os.listdir(train_dir)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_labels(list_of_images):\n    names = [] # images names\n    labels = [] # labels\n    \n    for i in list_of_images:\n        names.append(i)\n        if 'dog' in i:\n            labels.append(1)\n        elif 'cat' in i:\n            labels.append(0)\n    \n    df_train_labels = pd.DataFrame({'image_id':names, 'label':labels})\n            \n    return df_train_labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_labels = get_labels(list_of_images_names)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Check if the data are balanaced\nsns.countplot(train_labels.label)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_labels.label.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Main hyperparameters\nBATCH_SIZE = 8\nSTEPS_PER_EPOCH = len(train_labels)*0.8 / BATCH_SIZE\nVALIDATION_STEPS = len(train_labels)*0.2 / BATCH_SIZE\nEPOCHS = 20\nTARGET_SIZE = 224","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Cast label to string\ntrain_labels.label = train_labels.label.astype('str')\n\ntrain_datagen = tf.keras.preprocessing.image.ImageDataGenerator(\n                                     validation_split = 0.2,\n                                     preprocessing_function = None,\n                                     zoom_range = 0.2,\n                                     cval = 0.2,\n                                     horizontal_flip = True,\n                                     vertical_flip = True,\n                                     fill_mode = 'nearest',\n                                     shear_range = 0.2,\n                                     height_shift_range = 0.2,\n                                     width_shift_range = 0.2)\n\ntrain_generator = train_datagen.flow_from_dataframe(train_labels,\n                                                    directory = train_dir,\n                                                    subset = \"training\",\n                                                    x_col = \"image_id\",\n                                                    y_col = \"label\",\n                                                    target_size=(TARGET_SIZE, TARGET_SIZE),\n                                                    batch_size=BATCH_SIZE,\n                                                    class_mode='binary')\n\nvalidation_datagen = tf.keras.preprocessing.image.ImageDataGenerator(validation_split = 0.2)\n\n\nvalidation_generator = validation_datagen.flow_from_dataframe(train_labels,\n                                                                directory = train_dir,\n                                                                subset = \"validation\",\n                                                                x_col = \"image_id\",\n                                                                y_col = \"label\",\n                                                                target_size=(TARGET_SIZE, TARGET_SIZE),\n                                                                batch_size=BATCH_SIZE,\n                                                                class_mode='binary')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Load our pretrained model\npretrained_model = tf.keras.applications.EfficientNetB0(include_top = False, weights = 'imagenet', input_shape = (TARGET_SIZE, TARGET_SIZE, 3))\npretrained_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_model(pretrained):\n    model = tf.keras.Sequential()\n\n    # load pretrained model\n    model.add(pretrained)\n    \n    # Applies average pooling on the spatial dimensions until each spatial dimension is one\n    model.add(tf.keras.layers.GlobalAveragePooling2D())\n    \n    # Classifier\n    model.add(tf.keras.layers.Dense(256, activation = \"relu\"))\n    model.add(tf.keras.layers.Dense(1, activation = \"sigmoid\"))\n\n    return model\n\nmodel = create_model(pretrained_model)\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer = tf.keras.optimizers.Adam(lr = 0.001),\n                  loss = \"binary_crossentropy\",\n                  metrics = [\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"model_save = tf.keras.callbacks.ModelCheckpoint('./best_trial0_catdog_model.h5', \n                             save_best_only = True, \n                             save_weights_only = True,\n                             monitor = 'val_loss', \n                             mode = 'min', verbose = 1)\n\nearly_stop = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss', min_delta = 0.001, \n                           patience = 5, mode = 'min', verbose = 1,\n                           restore_best_weights = True)\n\nreduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor = 'val_loss', factor = 0.3, \n                              patience = 2, min_delta = 0.001, \n                              mode = 'min', verbose = 1)\n\nhistory = model.fit_generator(\n    train_generator,\n    steps_per_epoch = STEPS_PER_EPOCH,\n    epochs = EPOCHS,\n    validation_data = validation_generator,\n    validation_steps = VALIDATION_STEPS,\n    callbacks = [model_save, early_stop, reduce_lr]\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"acc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))\nsns.set_style(\"white\")\nplt.suptitle('Train history', size = 15)\n\nax1.plot(epochs, acc, \"bo\", label = \"Training acc\")\nax1.plot(epochs, val_acc, \"b\", label = \"Validation acc\")\nax1.set_title(\"Training and validation acc\")\nax1.legend()\n\nax2.plot(epochs, loss, \"bo\", label = \"Training loss\", color = 'red')\nax2.plot(epochs, val_loss, \"b\", label = \"Validation loss\", color = 'red')\nax2.set_title(\"Training and validation loss\")\nax2.legend()\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.evaluate_generator(generator=validation_generator, steps=VALIDATION_STEPS)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('./trial0_catdog_model_overfitted_97.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ss = pd.read_csv(os.path.join(base_dir, \"sample_submission.csv\"))\nss","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ss.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ss.id = ss.id.astype('str')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"os.listdir(test_dir)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"For each image in the test set, you should predict a probability that the image is a dog (1 = dog, 0 = cat)."},{"metadata":{"trusted":true},"cell_type":"code","source":"image = Image.open(os.path.join(train_dir,'cat.3660'+'.jpg'))\nimage","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image = np.expand_dims(image, axis = 0)\nmodel.predict(image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image = Image.open(os.path.join(test_dir,'1000'+'.jpg'))\nimage","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image = image.resize((TARGET_SIZE, TARGET_SIZE))\nimage = np.expand_dims(image, axis = 0)\nmodel.predict(image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = []\n\nfor image_id in ss.id:\n    image = Image.open(os.path.join(test_dir, image_id+'.jpg'))\n    image = image.resize((TARGET_SIZE, TARGET_SIZE))\n    image = np.expand_dims(image, axis = 0)\n    preds.append(model.predict(image))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ss['label'] = preds\nss","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ss.label = ss.label.astype('float32')\nss","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ss.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ss.to_csv('submission.csv',header=True,index = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!tree","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}