{"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)\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import zipfile\nwith zipfile.ZipFile(\"../input/dogs-vs-cats-redux-kernels-edition/train.zip\",\"r\") as z:\n    z.extractall(\".\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile(\"../input/dogs-vs-cats-redux-kernels-edition/test.zip\",'r') as z:\n    z.extractall(\".\") ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\ntrain_path='/kaggle/working/train'\nfilenames=os.listdir(train_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"categories=[]\nfor f in filenames:\n    category=f.split(\".\")[0]\n    if category=='dog':\n        categories.append(1)\n    else:\n        categories.append(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(categories)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\ntrain=pd.DataFrame({'file':filenames,'category':categories})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['category'].value_counts()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# **Visualisation**"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing import image\nimport matplotlib.pyplot as plt\nfor i in range(4):\n    plt.figure(figsize=(10,10))\n    plt.subplot(2,3,i+1)\n    img_path=os.path.join(train_path,filenames[i])\n    img=image.load_img(img_path)\n    plt.imshow(img)\nplt.tight_layout()    \nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"raw","source":"Pre-trained Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.applications.vgg19 import VGG19\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.vgg19 import preprocess_input\nfrom tensorflow.keras.models import Model\nimport numpy as np\n\nbase_model = VGG19(weights='imagenet',include_top=False,input_shape=(224,224,3))\nmodel = Model(inputs=base_model.input, outputs=base_model.get_layer('block4_pool').output)\n\n#img_path = '../input/dogs-vs-cats-redux-kernels-edition/train.zip'\n#img = image.load_img(img_path, target_size=(150, 150))\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nx = preprocess_input(x)\nbase_model.trainable=False\nbase_model.summary()\n\nblock4_pool_features = model.predict(x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"from keras import models\nfrom keras import layers\nfrom keras import regularizers\nmodel=models.Sequential()\nmodel.add(base_model)\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(512,activation='relu',kernel_regularizer=regularizers.l2(0.001)))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(1,activation='sigmoid'))\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss='binary_crossentropy',optimizer='rmsprop',metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['category']=train['category'].map({1:'dog',0:'cat'})\nfrom sklearn.model_selection import train_test_split\ntrain,validate=train_test_split(train,train_size=0.9)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\ntrain_datagen=ImageDataGenerator(rescale=1./255,width_shift_range=0.2,height_shift_range=0.2,shear_range=0.5,rotation_range=40,zoom_range=0.2,horizontal_flip=True,fill_mode='nearest')\ntest_datagen=ImageDataGenerator(rescale=1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator=train_datagen.flow_from_dataframe(train,directory=train_path,x_col='file',y_col='category',target_size=(224,224),batch_size=20,class_mode='binary')\ntest_generator=test_datagen.flow_from_dataframe(validate,directory=train_path,x_col='file',y_col='category',target_size=(224,224),batch_size=20,class_mode='binary')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Data Augmentation**"},{"metadata":{"trusted":true},"cell_type":"code","source":"sample=train.sample(n=1)\nsample_generator=train_datagen.flow_from_dataframe(sample,directory=train_path,x_col='file',y_col='category',target_size=(224,224),class_mode='categorical')\nfor i in range(6):\n    plt.subplot(2,3,i+1)\n    for i,l in sample_generator:\n        plt.imshow(i[0])\n        break\nplt.show()        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history=model.fit(train_generator,steps_per_epoch=1000,epochs=7,validation_data=test_generator,validation_steps=250)","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}