{"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 in \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 \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"from zipfile import ZipFile\n# Create a ZipFile Object and load sample.zip in it\n# Create a ZipFile Object and load sample.zip in it\nwith ZipFile('/kaggle/input/dogs-vs-cats/train.zip', 'r') as zipObj:\n   # Extract all the contents of zip file in different directory\n   zipObj.extractall('temp')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with ZipFile('/kaggle/input/dogs-vs-cats/test1.zip', 'r') as zipObj:\n   # Extract all the contents of zip file in different directory\n   zipObj.extractall('temp')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"categories = []\nimport os\nfor dirname, _, filenames in os.walk('temp'):\n    for filename in filenames:\n        category = filename.split('.')[0]\n        if category == 'dog':\n            categories.append(1)\n        if category == 'cat':\n            categories.append(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2\nimport glob","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import re\nnumbers = re.compile(r'(\\d+)')\ndef numericalSort(value):\n    parts = numbers.split(value)\n    parts[1::2] = map(int, parts[1::2])\n    return parts","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from PIL import Image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dim = (150,150)\nfilelist_trainx = sorted(glob.glob('temp/train/*.jpg'), key=numericalSort)\n#filelist_trainx.sort()\nx_train = np.array([np.array(cv2.resize(cv2.imread(fname), dim, interpolation = cv2.INTER_AREA)) for fname in filelist_trainx])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dim = (150,150)\nfilelist_testx = sorted(glob.glob('temp/test1/*.jpg'), key=numericalSort)\n#filelist_trainx.sort()\nx_test = np.array([np.array(cv2.resize(cv2.imread(fname), dim, interpolation = cv2.INTER_AREA)) for fname in filelist_testx])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_categories = []\nimport os\nfor dirname, _, filenames in os.walk('temp/test1'):\n    for filename in filenames:\n        print(filename)\n        category = filename.split('.')[0]\n        test_categories.append(category)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.unique(test_categories)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom keras.layers import Conv2D,Dense,Dropout\nfrom keras.applications import InceptionV3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!wget --no-check-certificate \\\n    https://storage.googleapis.com/mledu-datasets/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5 \\\n    -O /tmp/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5\n  \n\nlocal_weights_file = '/tmp/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pre_trained_model = InceptionV3(input_shape = (150, 150, 3), \n                                include_top = False, \n                                weights = None)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_input = pre_trained_model.input","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pre_trained_model.load_weights(local_weights_file)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for layer in pre_trained_model.layers:\n  layer.trainable = False\n  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"last_layer = pre_trained_model.get_layer('mixed7')\nprint('last layer output shape: ', last_layer.output_shape)\nlast_output = last_layer.output\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.optimizers import Adam\nfrom keras.models import Model\nimport keras\n# Flatten the output layer to 1 dimension\nx = keras.layers.Flatten()(last_output)\n# Add a fully connected layer with 1,024 hidden units and ReLU activation\nx = keras.layers.Dense(1024, activation='relu')(x)\n# Add a dropout rate of 0.2\nx = keras.layers.Dropout(0.5)(x)\n# Add a final sigmoid layer for classification\npreds = keras.layers.Dense(1, activation='sigmoid')(x)           \n\nmodel = Model(img_input,preds) \n\nmodel.compile(optimizer = Adam(lr=0.0001), \n              loss = 'binary_crossentropy', \n              metrics = ['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = categories","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(x_train,y_train,epochs=30,batch_size=1000)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = model.predict(x_test)\nmodel.save_weights(\"model.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = []\nfor i in range(preds.shape[0]):\n    if(preds[i]<=0.5):\n        predictions.append(0)\n    else:\n        predictions.append(1)\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.DataFrame()\ndf[\"id\"] = test_categories\ndf[\"label\"] = predictions","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.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}