{"cells":[{"metadata":{},"cell_type":"markdown","source":"# This notebook works with the Cat VS Dog dataset."},{"metadata":{},"cell_type":"markdown","source":"## Importing the libraries"},{"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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt \nimport zipfile\nimport os \nimport random\nimport cv2","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Extracting the files using zipfile module into designated folders"},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile('/kaggle/input/dogs-vs-cats/train.zip','r') as zip_ref:\n    zip_ref.extractall('train')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile('/kaggle/input/dogs-vs-cats/test1.zip','r') as zip_ref:\n    zip_ref.extractall('test')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Building a dataframe with the list of all training images and their labels "},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames=os.listdir('train/train')\ncategory=[]\n\nfor filename in filenames:\n    if 'dog' in filename:\n        category.append('dog')\n    else:\n        category.append('cat')\n\ndf={'filename':filenames,'category':category}\ndf=pd.DataFrame(df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Opening a random image"},{"metadata":{"trusted":true},"cell_type":"code","source":"any_file=random.choice(df.filename)\nprint(any_file)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img=cv2.imread('train/train/'+str(any_file))\nimg=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\nplt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Inorder to build a good model we need to check the size of each images and resize the images which we will do later"},{"metadata":{"trusted":true},"cell_type":"code","source":"def checking_size(path,n=5):\n    filenames=os.listdir(path)\n    randomly_selected_files=[]\n    sizes=[]\n    for i in range(n):\n        randomly_selected_files.append(random.choice(filenames))\n    for j in randomly_selected_files:\n        img=cv2.imread(path+'/'+str(j))\n        sizes.append(img.shape)\n    for k in range(len(sizes)):\n        print(sizes[k])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"checking_size('train/train')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"checking_size('test/test1')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Since the size of the images are very different we would be resizing them in a standard size of 128X128X3.\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"imageHeight=128\nimageWidth=128\nchannels=3","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## We are going to build a deep learning model using tensorflow api"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Creating the model\nimport tensorflow as tf \nfrom tensorflow.keras.layers import Input,Conv2D,BatchNormalization,MaxPooling2D,Dense,Dropout,GlobalMaxPooling2D,Flatten\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import EarlyStopping,ModelCheckpoint","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"i=Input((imageHeight,imageWidth,channels))\nx=Conv2D(32,(3,3),activation='relu',padding='same')(i)\nx=BatchNormalization()(x)\nx=Conv2D(32,(3,3),activation='relu',padding='same')(x)\nx=BatchNormalization()(x)\nx=MaxPooling2D((2,2))(x)\n\nx=Conv2D(64,(3,3),activation='relu',padding='same')(x)\nx=BatchNormalization()(x)\nx=Conv2D(64,(3,3),activation='relu',padding='same')(x)\nx=BatchNormalization()(x)\nx=MaxPooling2D((2,2))(x)\n\nx=Conv2D(128,(3,3),activation='relu',padding='same')(x)\nx=BatchNormalization()(x)\nx=Conv2D(128,(3,3),activation='relu',padding='same')(x)\nx=BatchNormalization()(x)\nx=GlobalMaxPooling2D()(x)\nx=Dropout(0.2)(x)\nx=Flatten()(x)\nx=Dense(2056,activation='relu')(x)\nx=Dropout(0.2)(x)\nx=Dense(2,activation='softmax')(x)\n\nmodel=Model(i,x)\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Splitting the training dataset into training and validation set"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain_df,validation_df=train_test_split(df)\nprint(train_df.shape)\nprint(validation_df.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Building the training, validation and test generators"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data_generator=tf.keras.preprocessing.image.ImageDataGenerator(rotation_range=20,rescale=1/255,width_shift_range=0.1,\n                                                                     height_shift_range=0.1,horizontal_flip=True)\n\ntrain_data=train_data_generator.flow_from_dataframe(train_df,'train/train',x_col='filename',y_col='category',\n                                                    target_size=(imageHeight,imageWidth),batch_size=32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validation_data_generator=tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)\n\nvalidation_data=validation_data_generator.flow_from_dataframe(validation_df,'train/train',x_col='filename',y_col='category',\n                                                    target_size=(128,128),batch_size=32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_filenames=os.listdir('test/test1')\ntest_df=pd.DataFrame(test_filenames,columns=['filename'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data_generator=tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)\ntest_data=test_data_generator.flow_from_dataframe(test_df,'test/test1',x_col='filename',y_col=None,class_mode=None,\n                                                    target_size=(128,128),batch_size=32)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Inorder to avoid overfitting we will be using earlyStopping method \n## We then compile the model and run it for a maximum 50 epochs"},{"metadata":{"trusted":true},"cell_type":"code","source":"callbacks=[EarlyStopping(monitor='val_loss',patience=3)] #Early Stopping\nmodel.compile(loss='categorical_crossentropy',metrics=['accuracy'],optimizer='adam')\nr=model.fit(train_data,validation_data=validation_data,steps_per_epoch=train_df.shape[0]//32,batch_size=32,callbacks=callbacks,epochs=50)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting loss and accuracy"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(r.history['loss'],label='loss')\nplt.plot(r.history['val_loss'],label='val_loss')\nplt.legend()\nplt.ylabel('Loss')\nplt.xlabel('Epochs')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(r.history['accuracy'],label='accuracy')\nplt.plot(r.history['val_accuracy'],label='val_accuracy')\nplt.legend()\nplt.ylabel('Accuracy')\nplt.xlabel('Epochs')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predicting the results"},{"metadata":{"trusted":true},"cell_type":"code","source":"y_hat=model.predict(test_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred=np.argmax(y_hat,axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['label']=y_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Testing the checked result"},{"metadata":{"trusted":true},"cell_type":"code","source":"def check_prediction():\n    filename=test_df.filename\n    filename=filename[:5]\n    label=test_df.label\n    label=label[:5]\n    for i in range(len(filename)):\n        img=cv2.imread('test/test1/'+filename[i])\n        plt.imshow(img)\n        plt.title(str(label[i]))\n        plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"check_prediction()","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}