{"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 5GB 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","collapsed":true,"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":false},"cell_type":"markdown","source":"## 1. Load necessary libraries"},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom PIL import Image\nfrom keras.models import Sequential\nimport keras, shutil\nfrom keras.layers import Conv2D, ZeroPadding2D,Flatten,Dense, MaxPooling2D\nfrom zipfile import ZipFile\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import Adam","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 2. Load Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# extract train.zip\nzip_train_path = \"/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip\"\nwith ZipFile(zip_train_path) as myzip:\n    myzip.extractall('/kaggle/temp/') ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# extract test.zip\nzip_test_path = \"/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip\"\nwith ZipFile(zip_test_path) as myzip:\n    myzip.extractall('/kaggle/temp/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"files = os.listdir('/kaggle/temp/train/') ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# view sample submission\nsample_submission = pd.read_csv('/kaggle/input/dogs-vs-cats-redux-kernels-edition/sample_submission.csv')\nsample_submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_files = os.listdir('/kaggle/temp/test/')\ntest_files[0:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# create sub directory cat and dog in train\nos.mkdir('/kaggle/temp/train/cat') \nos.mkdir('/kaggle/temp/train/dog') ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# create validation set directory and sub directories cat and dog\nos.mkdir('/kaggle/temp/val') \nos.mkdir('/kaggle/temp/val/cat') \nos.mkdir('/kaggle/temp/val/dog') ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# move cat images to train/cat\n# and dog images to train/dog\nimages_path = '/kaggle/temp/train/'\nfor file in files[0:20000]:\n    if file[0] == 'd':\n        dst = '/kaggle/temp/train/dog/'\n        img = os.path.join(images_path, file) \n        shutil.move(img, dst) \n    elif file[0] == 'c':\n        dst = '/kaggle/temp/train/cat/'\n        img = os.path.join(images_path, file) \n        shutil.move(img, dst) \n        \n# rest of files move to validation directory\nfor file in files[20000:25000]:\n    if file[0] == 'd':\n        dst = '/kaggle/temp/val/dog/'\n        img = os.path.join(images_path, file) \n        shutil.move(img, dst) \n    elif file[0] == 'c':\n        dst = '/kaggle/temp/val/cat/'\n        img = os.path.join(images_path, file) \n        shutil.move(img, dst) \n        \n# ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# print num of samples in training and validation directory\ntrain_num_samples = 0\nfor _,_,filenames in os.walk('/kaggle/temp/train/'):\n    train_num_samples += len(filenames) \n    \nprint('train_num_samples: ', train_num_samples) \n\nval_num_samples = 0\nfor _, _, filenames in os.walk('/kaggle/temp/val/'):\n    val_num_samples += len(filenames) \n    \nprint('val_num_samples: ', val_num_samples) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# create Image Data Generator\ndatagen = ImageDataGenerator(rescale = 1.0/255) \n\ntrain_batch_size = 16\ntrain_dir = '/kaggle/temp/train/'\n# create train generator\ntrain_gen = datagen.flow_from_directory(train_dir, \n                                        target_size = (224, 224), \n                                        batch_size = train_batch_size, \n                                        class_mode = 'binary') \n\nval_batch_size = 16\nval_dir = '/kaggle/temp/val/'\nval_gen = datagen.flow_from_directory(val_dir, \n                                      target_size = (224, 224), \n                                      batch_size = val_batch_size, \n                                      class_mode = 'binary') ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train_gen.class_indices) ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 3. Visualize images generated by the image generator"},{"metadata":{"trusted":true},"cell_type":"code","source":"x, y = train_gen.next()\nplt.figure(figsize = (13,13))\n\nfor i,(img, label) in enumerate(zip(x, y)):\n    plt.subplot(4, 4,i+1) \n    if label == 1:\n        plt.title('Dog') \n    else:\n        plt.title('Cat') \n        \n    plt.axis('off') \n    plt.imshow(img) ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 4. create VGG16 CNN model architecture"},{"metadata":{"trusted":true},"cell_type":"code","source":"n_h = 224 # height of the image\nn_w = 224 # width of the image\nn_c = 3 # num of channels in image\n\n# num of filters for convolutional layers\nn_filters = [64,64,128,128,256,256,256,512,512,512,512,512,512]\nlen(n_filters) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\n# create 2 conv layers with 64 filters of size 3,padding same and stride of 1\nmodel.add(Conv2D(filters = n_filters[0], input_shape = (n_w, n_h, n_c), kernel_size = 3,\n                 padding = 'SAME', activation='relu')) \nmodel.add(Conv2D(filters = n_filters[1],kernel_size = 3,\n                 padding = 'SAME', activation='relu'))\n\n# create max pooling layer\nmodel.add(MaxPooling2D(pool_size = (2,2), strides = (2,2)))\n\n# create 2 conv layers with 128 filters\nmodel.add(Conv2D(filters = n_filters[2],kernel_size = 3,\n                 padding = 'SAME', activation='relu'))\nmodel.add(Conv2D(filters = n_filters[3],kernel_size = 3,\n                 padding = 'SAME', activation='relu'))\n# create max pooling layer\nmodel.add(MaxPooling2D(pool_size = (2, 2), strides = (2, 2))) \n\n# create 3 conv layers with 256 filters\nmodel.add(Conv2D(filters = n_filters[4],kernel_size = 3,\n                 padding = 'SAME', activation='relu'))\nmodel.add(Conv2D(filters = n_filters[5],kernel_size = 3,\n                 padding = 'SAME', activation='relu'))\nmodel.add(Conv2D(filters = n_filters[6],kernel_size = 3,\n                 padding = 'SAME', activation='relu'))\n# create max pooling layer\nmodel.add(MaxPooling2D(pool_size = (2, 2), strides = (2, 2))) \n\n# create 3 conv layers with 512 filters\n\nmodel.add(Conv2D(filters = n_filters[7],kernel_size = 3,\n                 padding = 'SAME', activation='relu'))\nmodel.add(Conv2D(filters = n_filters[8],kernel_size = 3,\n                 padding = 'SAME', activation='relu'))\nmodel.add(Conv2D(filters = n_filters[9],kernel_size = 3,\n                 padding = 'SAME', activation='relu'))\n# create max pooling layer\nmodel.add(MaxPooling2D(pool_size = (2,2), strides = (2,2)))\n\n# create 3 conv layers with 512 filters\n\nmodel.add(Conv2D(filters = n_filters[10],kernel_size = 3,\n                 padding = 'SAME', activation='relu'))\nmodel.add(Conv2D(filters = n_filters[11],kernel_size = 3,\n                 padding = 'SAME', activation='relu'))\nmodel.add(Conv2D(filters = n_filters[12],kernel_size = 3,\n                 padding = 'SAME', activation='relu'))\n# create max pooling layer\nmodel.add(MaxPooling2D(pool_size = (2,2), strides = (2,2)))\n\n# flatten the layer\nmodel.add(Flatten())\n\n# create 2 fully connected layers with 4096 neurons\nmodel.add(Dense(units = 4096, activation='relu')) \nmodel.add(Dense(units = 4096, activation='relu')) \n\n# final add the output layer\nmodel.add(Dense(units = 1, activation = 'sigmoid')) \n\n\n# print model summary\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 5. Compile, Train and Evaluate the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# compile the model\nmodel.compile(loss='binary_crossentropy', \n              optimizer = Adam(learning_rate = 0.00003), \n              metrics = ['accuracy']) \n\n# calculate train_steps and val_steps\ntrain_steps = np.ceil(train_num_samples / train_batch_size) \nval_steps = np.ceil(val_num_samples / val_batch_size) \n\n# train the model\nhistory = model.fit_generator(train_gen, \n                              steps_per_epoch = train_steps, \n                              epochs = 12,\n                              validation_data = val_gen, \n                              validation_steps = val_steps) ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 6. Save the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('/kaggle/working/recognizing_cats_and_dogs_using_vgg16.h5') ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 7. Make Predictions"},{"metadata":{"trusted":true},"cell_type":"code","source":"# load the model\nmodel = keras.models.load_model(\"/kaggle/working/recognizing_cats_and_dogs_using_vgg16.h5\")\n\ntest_path = \"/kaggle/temp/test/\"\n\n# create sub directory all_data inside test directory\nos.mkdir(\"/kaggle/temp/test/all_data\")\n\n# move all test images to all_data\nfor file in test_files:\n    img = os.path.join(test_path, file)\n    dst = \"/kaggle/temp/test/all_data/\"\n    shutil.move(img, dst)\n\n# create test generator\ntest_gen = datagen.flow_from_directory(test_path,\n                                      target_size = (224, 224),\n                                      batch_size = 16,\n                                      class_mode = None,\n                                      shuffle = False)\n# make predictions\npreds = model.predict_generator(test_gen, \n                               steps = len(test_gen))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = np.squeeze(preds)\n\n# create the dataframe\nsubmission = pd.DataFrame({\"files\": test_files, \"label\": preds})\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission['label'] = submission['label'].round(3)\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission['files'] = submission['files'].str.replace('.jpg', '')\nsubmission['files'] = submission['files'].astype('int')\nsubmission.sort_values(['files'], ascending=True, inplace = True)\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = submission.rename(columns = {'files': 'id'})\nsubmission.to_csv('/kaggle/working/submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.head()","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}