{"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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\nfrom matplotlib import style\nstyle.use('dark_background')\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":"#pip install --user --upgrade tensorflow-gpu","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Unzipping the zips"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import zipfile\nbase_dir_train='/kaggle/input/dogs-vs-cats/train.zip'\nlocal_zip=zipfile.ZipFile(base_dir_train,'r')\nlocal_zip.extractall('/tmp')\nlocal_zip.close()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_dir_test='/kaggle/input/dogs-vs-cats/test1.zip'\nlocal_zip=zipfile.ZipFile(base_dir_test,'r')\nlocal_zip.extractall('/tmp')\nlocal_zip.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dir_train='/tmp/train'\ntrain_images=os.listdir(os.path.join(dir_train))\ntrain_images[0:9]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dir_test='/tmp/test1'\ntest_images=os.listdir(os.path.join(dir_test))\ntest_images[0:9]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# lets see some images"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import load_img\nimg1=load_img(dir_train+'/dog.890.jpg')\nimg2=load_img(dir_train+'/cat.8375.jpg')\nf,(ax1,ax2)=plt.subplots(1,2,figsize=(15,15))\nax1.imshow(img1)\nax2.imshow(img2)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img1=load_img(dir_test+'/4644.jpg')\nimg2=load_img(dir_test+'/8044.jpg')\nf,(ax1,ax2)=plt.subplots(1,2,figsize=(15,15))\nax1.imshow(img1)\nax2.imshow(img2)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Labelling the train images"},{"metadata":{"trusted":true},"cell_type":"code","source":"filename=train_images\ncategories=[]\nfor filenm in filename:\n    label=filenm.split('.')[0]\n    if label=='dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n        \ntrain=pd.DataFrame({'filename':filename,'category':categories}) \ntrain[0:10]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Splitting the dataset into train set and validation set"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain_df,validate_df=train_test_split(train,test_size=0.2,random_state=0)\ntrain_df=train_df.reset_index(drop=True)\nvalidate_df=validate_df.reset_index(drop=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras import applications\nfrom keras.layers import Conv2D,Dense,Dropout,Activation,Flatten,BatchNormalization,MaxPooling2D,GlobalAveragePooling2D,GlobalMaxPooling2D\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_width=150\nimg_height=150\nimg_size=(img_width,img_height)\nbatch_size=16\nepochs=15\nnb_train_samples=train_df.shape[0]\nnb_validation_samples=validate_df.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model=applications.VGG16(include_top=False,weights='imagenet')\nprint('VGG16 is loaded....')\n\nfor layer in base_model.layers[:11]:\n    layer.trainable=False\nfor layer in base_model.layers[11:]:\n    layer.trainable=True    \nbase_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"top_model=Sequential()\ntop_model.add(GlobalAveragePooling2D(input_shape=base_model.output_shape[1:]))\ntop_model.add(Dense(512,activation='relu'))\ntop_model.add(BatchNormalization())\ntop_model.add(Dropout(0.5))\ntop_model.add(Dense(256,activation='relu'))\ntop_model.add(BatchNormalization())\ntop_model.add(Dropout(0.5))\ntop_model.add(Dense(128,activation='relu'))\ntop_model.add(BatchNormalization())\ntop_model.add(Dropout(0.5))\ntop_model.add(Dense(1,activation='sigmoid'))\ntop_model.summary()\n\n\n# top_model = Sequential()  \n# top_model.add(GlobalAveragePooling2D(input_shape=base_model.output_shape[1:]))\n# top_model.add(Dense(no_of_classes, activation='softmax')) \n# top_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import optimizers\nmodel=Sequential()\nmodel.add(base_model)\nmodel.add(top_model)\nmodel.summary()\n\nmodel.compile(loss='binary_crossentropy', optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),metrics='accuracy')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen=ImageDataGenerator(\n   \n    vertical_flip=True,\n     rotation_range=15,\n    rescale=1/255,\n    shear_range=0.1,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    width_shift_range=0.1,\n    height_shift_range=0.1,\n    \n)\ntrain_generator=train_datagen.flow_from_dataframe(\n    train_df,\n    '/tmp/train',\n    x_col='filename',\n    y_col='category',\n    target_size=img_size,\n    batch_size=batch_size,\n    class_mode='raw',\n    shuffle=False\n   \n)\nvalid_datagen=ImageDataGenerator(rescale=1/255)\nvalid_generator=valid_datagen.flow_from_dataframe(\n       validate_df,\n        '/tmp/train',\n        x_col='filename',\n        y_col='category',\n       target_size=img_size,\n       batch_size=batch_size,\n    class_mode='raw',\n    shuffle=False\n)          \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nb_validation_samples","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import backend as K","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import math\nfrom keras.callbacks import ModelCheckpoint\nbest_model_path='best_model.hdf5'\ncheckpointer=ModelCheckpoint(best_model_path,save_best_only=True,verbose=1)\n\ntrain_size=nb_train_samples//batch_size\nvalidation_size=nb_validation_samples//batch_size\n#validation_size=int(math.ceil(nb_validation_samples//batch_size))\n\n\nhistory=model.fit_generator(train_generator,\n                            epochs=20,\n                            validation_data=valid_generator,\n                            steps_per_epoch=train_size,\n                            validation_steps=validation_size)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Training vs Validation accuracy')\nplt.legend(['Training Accuracy','Validation Accuracy'],loc='lower right')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.title('Training vs Validation accuracy')\nplt.legend(['Training Loss','Validation Loss'],loc='upper right')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix,accuracy_score,classification_report","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_val=validate_df['category']\nval_pred=model.predict_generator(valid_generator,steps=np.ceil(nb_validation_samples/batch_size))\nthresh=0.5\nval_pred=np.where(val_pred>thresh,1,0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#y_val=y_val.replace({'dog':1,'cat':0})#","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ncm=confusion_matrix(y_val,val_pred)\nf,ax=plt.subplots(figsize=(8,8))\nsns.heatmap(cm,annot=True,linewidth=0.01,cmap='Blues',linecolor='gray',fmt='.1f',ax=ax)\nplt.xlabel('Predicted Label')\nplt.ylabel('Actual Label')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"accScore=accuracy_score(y_val,val_pred)\nprint(f' Accuracy Score is {accScore}')\nprint()\nprint('classification report is ---->')\nprint(classification_report(y_val,val_pred))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df=pd.DataFrame({'filename':test_images})\nnb_samples=test_df.shape[0]\ntest_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_datagen=ImageDataGenerator(\nrescale=1/255)\ntest_generator=test_datagen.flow_from_dataframe(\n     test_df,\n    '/tmp/test1',\n    x_col='filename',\n    y_col=None,\n    class_mode=None,\n    target_size=img_size,\n    batch_size=batch_size,\n    shuffle=False\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_pred=model.predict_generator(test_generator,steps=np.ceil(nb_samples/batch_size))\ntest_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"thresh=0.5\ntest_pred=np.where(test_pred>thresh,1,0)\ntest_pred[0:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['filename'][0:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_pred[0:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category']=test_pred\ntest_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Sub_df=test_df.copy()\nSub_df['id']=test_df['filename'].str.split('.').str[0]\nSub_df['label']=test_df['category']\nSub_df.drop(['filename','category'],axis=1,inplace=True)\nSub_df.to_csv('CatsVsDogsVGGfinetunning.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Sub_df[0:50]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Using the power of bottleneck features"},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\nfrom keras.callbacks import EarlyStopping,ReduceLROnPlateau\nearlystop = EarlyStopping(patience=10)\n#earlystopping = EarlyStopping(monitor =\"val_accuracy\",\n#                              mode = 'auto', patience = 10,\n #                             restore_best_weights = True)\n\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=2, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)\ncallbacks = [earlystop,learning_rate_reduction]\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# filename=train_images\n# categories=[]\n# for files in filename:\n#     category=files.split('.')[0]\n#     if category=='dog':\n#         categories.append(1)\n#     else:\n#         categories.append(0)\n\n# train=pd.DataFrame({'filename':filename,'category':categories})\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train_df,validate_df=train_test_split(train,test_size=0.2,random_state=0)\n# train_df=train_df.reset_index(drop=True)\n# validate_df=validate_df.reset_index(drop=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nimport math\nmodel=applications.VGG16(include_top=False,weights='imagenet')\ntop_model_weights_path='final_cnn_code.h5'\ntrain_datagen1=ImageDataGenerator(\n   rotation_range=15,\n    rescale=1/255,\n    shear_range=0.1,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\ntrain_generator1=train_datagen1.flow_from_dataframe(\n train_df,\n    '/tmp/train/',\n    x_col='filename',\n    y_col='category',\n    target_size=img_size,\n    class_mode='raw',\n    batch_size=batch_size,\n     shuffle=False\n    \n)\ntrain_size=int(math.ceil(nb_train_samples/batch_size))\nbottleneck_features_train=model.predict_generator(train_generator1,train_size)\nnp.save(open('bottleneck_features_train.npy','wb'),bottleneck_features_train)\n\nvalid_datagen1=ImageDataGenerator(\n  rescale=1/255\n)\nvalidation_generator1=valid_datagen1.flow_from_dataframe(\n  validate_df,\n    '/tmp/train/',\n   x_col='filename',\n    y_col='category',\n    target_size=img_size,\n    class_mode='raw',\n    batch_size=batch_size,\n     shuffle=False\n)\nvalidate_size=int(math.ceil(nb_validation_samples/batch_size))\nbottleneck_features_validate=model.predict_generator(validation_generator1,validate_size)\nnp.save(open('bottleneck_features_validate.npy','wb'),bottleneck_features_validate)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\ntrain_labels=train_df['category']\nvalidation_labels=validate_df['category']\n\n\nepochs=50\n\n\n\ntotal_train=train_df.shape[0]\ntotal_validate=validate_df.shape[0]\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validate_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"total_validate","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntrain_data=np.load(open('bottleneck_features_train.npy','rb'))\ntrain_labels.to_numpy()\nvalidation_data=np.load(open('bottleneck_features_validate.npy','rb'))\nvalidation_labels.to_numpy()\n\n\n    \nmodel1=Sequential()\n#model.add(GlobalAveragePooling2D(input_shape=train_data.shape[1:]))\nmodel1.add(Flatten(input_shape=train_data.shape[1:]))\nmodel1.add(Dense(1024, activation='relu'))\nmodel1.add(BatchNormalization())\nmodel1.add(Dropout(0.5))\nmodel1.add(Dense(512, activation='relu'))\nmodel1.add(BatchNormalization())\nmodel1.add(Dropout(0.5))\nmodel1.add(Dense(256, activation='relu'))\nmodel1.add(BatchNormalization())\nmodel1.add(Dropout(0.5))\nmodel1.add(Dense(128, activation='relu'))\nmodel1.add(BatchNormalization())\nmodel1.add(Dropout(0.5))\nmodel1.add(Dense(1, activation='sigmoid'))\n\nmodel1.compile(optimizer='adam',\n              loss='binary_crossentropy', metrics=['accuracy'])\n\nhistory=model1.fit(train_data, train_labels,\n        epochs=epochs,\n                  steps_per_epoch=total_train// batch_size,\n         batch_size=batch_size,\n                  validation_steps=total_validate // batch_size,\n         validation_data=(validation_data, validation_labels),callbacks=callbacks)\n# history=model.fit_generator(\n#     train_generator,\n#     steps_per_epoch=total_train// batch_size,\n#     epochs=50,\n#     validation_data=validation_generator,\n#     validation_steps=total_validate // batch_size,\n# callbacks=callbacks)\nmodel1.save_weights('final_cnn_code.h5')\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend(['training_accuracy','Validation_accuracy'],loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend(['training_loss','validation_loss'],loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# %% [code]\nmodel1.load_weights('final_cnn_code.h5')  \n   \n(eval_loss, eval_accuracy) = model1.evaluate(  \n     validation_data, validation_labels, batch_size=batch_size, verbose=1)\n\nprint(\"Accuracy: {:.2f}%\".format(eval_accuracy * 100))  \nprint(\"Loss: {}\".format(eval_loss)) \n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# %% [code]\ny_val=validate_df['category']\ny_pred=model1.predict(validation_data)\n\n# %% [code]\nthresh=0.5\ny_final=np.where(y_pred>thresh,1,0)\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# %% [code]\ncm=confusion_matrix(y_val,y_final)\nf,ax=plt.subplots(figsize=(8,8))\nsns.heatmap(cm,annot=True,linewidths=0.01,cmap='Blues',linecolor='gray',fmt='.1f',ax=ax)\nplt.xlabel(\"Predicted Label\")\nplt.ylabel('Actual Label')\nplt.title('Confusion matrix')\nplt.show()\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# %% [code]\naccScore=accuracy_score(y_val,y_final)\nprint(f' Accuracy score is {accScore}')\nprint()\nclassificationreport=classification_report(y_val,y_final)\nprint(f' Classification Report is --->')\nprint(classificationreport)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# %% [code]\ntest_filename=test_images\ntest_df=pd.DataFrame({'filename':test_filename})\nnb_samples=test_df.shape[0]\n\n# %% [code]\ntest_datagen=ImageDataGenerator(\n  rescale=1/255\n)\ntest_generator=test_datagen.flow_from_dataframe(\n   test_df,\n    '/tmp/test1/',\n   x_col='filename',\n    y_col=None,\n    target_size=img_size,\n    class_mode=None,\n    batch_size=batch_size,\n     shuffle=False\n)\ntest_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_size=int(math.ceil(nb_samples/batch_size))\nbottleneck_features_test=model.predict_generator(test_generator,test_size)\nnp.save(open('bottleneck_features_test.npy','wb'),bottleneck_features_test)\ntest_data=np.load(open('bottleneck_features_test.npy','rb'))\n\n# %% [code]\ny_pred=model1.predict(test_data)\n\n# %% [code]\ny_pred[0:20]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"threshold = 0.5\ntest_df['category'] = np.where( y_pred> threshold, 1,0)\n\n# %% [code]\ntest_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Sub_df1=test_df.copy()\nSub_df1['id']=test_df['filename'].str.split('.').str[0]\nSub_df1['label']=test_df['category']\nSub_df1.drop(['filename','category'],axis=1,inplace=True)\nSub_df1.to_csv('Bottleneck_CatsVsDogs.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}