{"metadata":{"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30699,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true},"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Santosh Kumar\n# MSA23005\n","metadata":{"execution":{"iopub.execute_input":"2024-05-15T10:57:17.761409Z","iopub.status.busy":"2024-05-15T10:57:17.760812Z","iopub.status.idle":"2024-05-15T10:57:29.376970Z","shell.execute_reply":"2024-05-15T10:57:29.375998Z","shell.execute_reply.started":"2024-05-15T10:57:17.761375Z"}}},{"cell_type":"markdown","source":"## creating various variants of vgg16 for the dogs vs. cats classification and comparing their performances.","metadata":{}},{"cell_type":"markdown","source":"## Importing relevant Libraries","metadata":{}},{"cell_type":"code","source":"# Basic\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport os\nfrom os import makedirs # make directory\nfrom os import listdir # list directories\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random\nimport numpy as np\nimport pandas as pd\n\n# visuals\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imread # Used to read images\nfrom PIL import Image # Image Visulization\n\n# Scikit-learn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report,confusion_matrix,ConfusionMatrixDisplay\n\n# Tensorflow\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential \nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Dense,MaxPooling2D,Dropout,Flatten,BatchNormalization,Conv2D\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau,EarlyStopping","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:30.741090Z","iopub.execute_input":"2024-05-15T14:14:30.741730Z","iopub.status.idle":"2024-05-15T14:14:30.749049Z","shell.execute_reply.started":"2024-05-15T14:14:30.741698Z","shell.execute_reply":"2024-05-15T14:14:30.747979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Data Extraction","metadata":{}},{"cell_type":"code","source":"train_path = \"../input/dogs-vs-cats/test1.zip\"\ntest_path = \"../input/dogs-vs-cats/train.zip\"\n\nfiles = \"/kaggle/working/\"\n\n# zipfile - python module for extracting files from a zip file\nimport zipfile\n\nwith zipfile.ZipFile(train_path, 'r') as zipp:\n    zipp.extractall(files)\n    \nwith zipfile.ZipFile(test_path, 'r') as zipp:\n    zipp.extractall(files)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:30.751227Z","iopub.execute_input":"2024-05-15T14:14:30.751490Z","iopub.status.idle":"2024-05-15T14:14:41.194799Z","shell.execute_reply.started":"2024-05-15T14:14:30.751466Z","shell.execute_reply":"2024-05-15T14:14:41.193972Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_dir = \"../working/train/\"\n\nfilenames = os.listdir(image_dir)\nlabels = [x.split(\".\")[0] for x in filenames]\n\ndata = pd.DataFrame({\"filename\": filenames, \"label\": labels})\n\ndata.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:41.196300Z","iopub.execute_input":"2024-05-15T14:14:41.196598Z","iopub.status.idle":"2024-05-15T14:14:41.231355Z","shell.execute_reply.started":"2024-05-15T14:14:41.196572Z","shell.execute_reply":"2024-05-15T14:14:41.230623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"The shape of the data : \",data.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:41.232531Z","iopub.execute_input":"2024-05-15T14:14:41.232879Z","iopub.status.idle":"2024-05-15T14:14:42.294672Z","shell.execute_reply.started":"2024-05-15T14:14:41.232848Z","shell.execute_reply":"2024-05-15T14:14:42.293694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Splitting the data into trainig and testing sets","metadata":{}},{"cell_type":"code","source":"# train test split using dataframe\n\nlabels = data['label']\n\n# 20% split\n# 80%.    20%\nX_train, X_temp = train_test_split(data, test_size=0.2, stratify=labels, random_state = 42)\n\nlabel_test_val = X_temp['label']\n\n# 10%.   10%\nX_test, X_val = train_test_split(X_temp, test_size=0.5, stratify=label_test_val, random_state = 42)\n\nprint('The shape of train data',X_train.shape)\nprint('The shape of test data',X_test.shape)\nprint('The shape of validation data',X_val.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:42.297352Z","iopub.execute_input":"2024-05-15T14:14:42.298094Z","iopub.status.idle":"2024-05-15T14:14:42.359072Z","shell.execute_reply.started":"2024-05-15T14:14:42.298065Z","shell.execute_reply":"2024-05-15T14:14:42.358188Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\n\nfor subdir in subdirs:\n    # create label subdirectories\n    labeldirs = ['dogs/', 'cats/']\n    for labldir in labeldirs:\n        newdir = dataset_home + subdir + labldir\n        makedirs(newdir, exist_ok=True) # Create 4 directories\n# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nval_ratio = 0.2\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\nfor file in listdir(src_directory):\n        src = src_directory + '/' + file\n        dst_dir = 'train/'\n        if random() < val_ratio:\n            dst_dir = 'test/'\n        if file.startswith('cat'):\n            dst = dataset_home + dst_dir + 'cats/' + file\n            copyfile(src, dst)\n        elif file.startswith('dog'):\n            dst = dataset_home + dst_dir + 'dogs/' + file\n            copyfile(src, dst)\n\n            \npath1 = \"/kaggle/working/dataset_dogs_vs_cats/train/cats\"\npath2 = \"/kaggle/working/dataset_dogs_vs_cats/train/dogs\"\npath3 = \"/kaggle/working/dataset_dogs_vs_cats/test/cats\"\npath4 = \"/kaggle/working/dataset_dogs_vs_cats/test/dogs\"\n\n\nprint('Then number of cat images in training data is' ,len(os.listdir(path1)))\nprint('Then number of dog images in training data is' ,len(os.listdir(path2)))\nprint('Then number of cat images in validation data is' ,len(os.listdir(path3)))\nprint('Then number of dog images in validation data is' ,len(os.listdir(path4)))","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:42.360150Z","iopub.execute_input":"2024-05-15T14:14:42.360438Z","iopub.status.idle":"2024-05-15T14:14:45.834595Z","shell.execute_reply.started":"2024-05-15T14:14:42.360412Z","shell.execute_reply":"2024-05-15T14:14:45.833551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# parameters\nimage_size = 128 # Size of the image\nimage_channel = 3 # Colour scale (RGB)\nbat_size = 32 # Number of files/images processed at once","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:45.835919Z","iopub.execute_input":"2024-05-15T14:14:45.836237Z","iopub.status.idle":"2024-05-15T14:14:45.840744Z","shell.execute_reply.started":"2024-05-15T14:14:45.836210Z","shell.execute_reply":"2024-05-15T14:14:45.839692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating image data generator\n# Preprocess images ==> Feature Engineering for Images\ntrain_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:45.842034Z","iopub.execute_input":"2024-05-15T14:14:45.842648Z","iopub.status.idle":"2024-05-15T14:14:45.853543Z","shell.execute_reply.started":"2024-05-15T14:14:45.842597Z","shell.execute_reply":"2024-05-15T14:14:45.852678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Using DataFrame","metadata":{}},{"cell_type":"code","source":"# Applying image data gernerator to train and test data\n\ntrain_generator = train_datagen.flow_from_dataframe(X_train,\n                                                    directory = 'train/',\n                                                    x_col= 'filename',\n                                                    y_col= 'label',\n                                                    batch_size = bat_size,\n                                                    target_size = (image_size,image_size)\n                                                   )\nval_generator = test_datagen.flow_from_dataframe(X_val, \n                                                 directory = 'train/',\n                                                 x_col= 'filename',\n                                                 y_col= 'label',\n                                                 batch_size = bat_size,\n                                                 target_size = (image_size,image_size),\n                                                 shuffle=False\n                                                )\n\ntest_generator = test_datagen.flow_from_dataframe(X_test, \n                                                  directory = 'train/',\n                                                  x_col= 'filename',\n                                                  y_col= 'label',\n                                                  batch_size = bat_size,\n                                                  target_size = (image_size,image_size),\n                                                  shuffle=False\n                                                 )","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:45.854820Z","iopub.execute_input":"2024-05-15T14:14:45.855600Z","iopub.status.idle":"2024-05-15T14:14:46.163100Z","shell.execute_reply.started":"2024-05-15T14:14:45.855566Z","shell.execute_reply":"2024-05-15T14:14:46.162227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Using Directory","metadata":{}},{"cell_type":"code","source":"train_gen = train_datagen.flow_from_directory('/kaggle/working/dataset_dogs_vs_cats/train/', \n                                              class_mode='binary',\n                                              target_size = (image_size,image_size),\n                                              batch_size = bat_size,\n                                             )\n\nval_gen = test_datagen.flow_from_directory('/kaggle/working/dataset_dogs_vs_cats/test/', \n                                          class_mode='binary',\n                                          batch_size = bat_size,\n                                          target_size = (image_size,image_size),\n                                          shuffle = False\n                                         )","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:46.164154Z","iopub.execute_input":"2024-05-15T14:14:46.164482Z","iopub.status.idle":"2024-05-15T14:14:46.852456Z","shell.execute_reply.started":"2024-05-15T14:14:46.164455Z","shell.execute_reply":"2024-05-15T14:14:46.851559Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### VGG Model One","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense\n\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense\n\ndef VGG16_one(input_shape=(224, 224, 3)):\n    \"\"\"Instantiates the VGG16 architecture for binary classification.\n\n    # Arguments\n        input_shape: optional shape tuple, only to be specified\n            if `include_top` is False (otherwise the input shape\n            has to be `(224, 224, 3)` (with `channels_last` data format)\n            or `(3, 224, 244)` (with `channels_first` data format).\n            It should have exactly 3 inputs channels,\n            and width and height should be no smaller than 48.\n            E.g. `(200, 200, 3)` would be one valid value.\n\n    # Returns\n        A Keras model instance.\n    \"\"\"\n    img_input = Input(shape=input_shape)\n\n    # Block 1\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\n\n    # Block 2\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\n\n    # Block 3\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\n\n    # Block 4\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)\n\n    # Block 5\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)\n\n    # Classification block\n    x = Flatten(name='flatten')(x)\n    x = Dense(4096, activation='relu', name='fc1')(x)\n    x = Dense(4096, activation='relu', name='fc2')(x)\n    output = Dense(2, activation='softmax', name='predictions')(x)\n\n    # Create model\n    model = Model(img_input, output, name='vgg16_binary')\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:46.855620Z","iopub.execute_input":"2024-05-15T14:14:46.855932Z","iopub.status.idle":"2024-05-15T14:14:46.872179Z","shell.execute_reply.started":"2024-05-15T14:14:46.855906Z","shell.execute_reply":"2024-05-15T14:14:46.871302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_one = VGG16_one(input_shape=(image_size, image_size, image_channel))\nmodel_one.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:46.873264Z","iopub.execute_input":"2024-05-15T14:14:46.873522Z","iopub.status.idle":"2024-05-15T14:14:49.129851Z","shell.execute_reply.started":"2024-05-15T14:14:46.873500Z","shell.execute_reply":"2024-05-15T14:14:49.128961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor = 'val_accuracy',\n                                            patience=2,\n                                            factor=0.5,\n                                            min_lr = 0.00001,\n                                            verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:49.131246Z","iopub.execute_input":"2024-05-15T14:14:49.131884Z","iopub.status.idle":"2024-05-15T14:14:49.136664Z","shell.execute_reply.started":"2024-05-15T14:14:49.131850Z","shell.execute_reply":"2024-05-15T14:14:49.135667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_one.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:49.137886Z","iopub.execute_input":"2024-05-15T14:14:49.138222Z","iopub.status.idle":"2024-05-15T14:14:49.150610Z","shell.execute_reply.started":"2024-05-15T14:14:49.138192Z","shell.execute_reply":"2024-05-15T14:14:49.149865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_one_logs = model_one.fit(train_generator,\n                    validation_data = val_generator, \n                    callbacks=[learning_rate_reduction],\n                    epochs = 5)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:14:49.151732Z","iopub.execute_input":"2024-05-15T14:14:49.152022Z","iopub.status.idle":"2024-05-15T14:19:15.768456Z","shell.execute_reply.started":"2024-05-15T14:14:49.151983Z","shell.execute_reply":"2024-05-15T14:19:15.767548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### VGG Model Two\n**Adding one more Conv layer in Block4 and increasing the number of neurons in final layer from 4096 to 6000**","metadata":{}},{"cell_type":"code","source":"# from tensorflow.keras.models import Model\n# from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense\n\n# from tensorflow.keras.models import Model\n# from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense\n\ndef VGG16_two(input_shape=(224, 224, 3)):\n    \"\"\"Instantiates the VGG16 architecture for binary classification.\n\n    # Arguments\n        input_shape: optional shape tuple, only to be specified\n            if `include_top` is False (otherwise the input shape\n            has to be `(224, 224, 3)` (with `channels_last` data format)\n            or `(3, 224, 244)` (with `channels_first` data format).\n            It should have exactly 3 inputs channels,\n            and width and height should be no smaller than 48.\n            E.g. `(200, 200, 3)` would be one valid value.\n\n    # Returns\n        A Keras model instance.\n    \"\"\"\n    img_input = Input(shape=input_shape)\n\n    # Block 1\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\n\n    # Block 2\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\n\n    # Block 3\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\n\n    # Block 4\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv4')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)\n\n    # Block 5\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)\n\n    # Classification block\n    x = Flatten(name='flatten')(x)\n    x = Dense(6000, activation='relu', name='fc1')(x)\n    x = Dense(6000, activation='relu', name='fc2')(x)\n    output = Dense(2, activation='softmax', name='predictions')(x)\n\n    # Create model\n    model = Model(img_input, output, name='vgg16_binary')\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:19:15.769797Z","iopub.execute_input":"2024-05-15T14:19:15.770077Z","iopub.status.idle":"2024-05-15T14:19:15.786603Z","shell.execute_reply.started":"2024-05-15T14:19:15.770051Z","shell.execute_reply":"2024-05-15T14:19:15.785689Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_two = VGG16_two(input_shape=(image_size, image_size, image_channel))\nmodel_two.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:19:15.787737Z","iopub.execute_input":"2024-05-15T14:19:15.787992Z","iopub.status.idle":"2024-05-15T14:19:15.922210Z","shell.execute_reply.started":"2024-05-15T14:19:15.787970Z","shell.execute_reply":"2024-05-15T14:19:15.921390Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_two.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:19:15.923366Z","iopub.execute_input":"2024-05-15T14:19:15.923655Z","iopub.status.idle":"2024-05-15T14:19:15.931166Z","shell.execute_reply.started":"2024-05-15T14:19:15.923613Z","shell.execute_reply":"2024-05-15T14:19:15.930360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_two_logs = model_two.fit(train_generator,\n                    validation_data = val_generator, \n                    callbacks=[learning_rate_reduction],\n                    epochs = 5)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:19:15.932189Z","iopub.execute_input":"2024-05-15T14:19:15.932452Z","iopub.status.idle":"2024-05-15T14:24:14.151312Z","shell.execute_reply.started":"2024-05-15T14:19:15.932430Z","shell.execute_reply":"2024-05-15T14:24:14.150377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### VGG Model Three\nreducing one conv layers from each block 2,3,4 of original vgg16 and keeping increasing the number of neurons to 7000","metadata":{}},{"cell_type":"code","source":"\ndef VGG16_three(input_shape=(224, 224, 3)):\n    \"\"\"Instantiates the VGG16 architecture for binary classification.\n\n    # Arguments\n        input_shape: optional shape tuple, only to be specified\n            if `include_top` is False (otherwise the input shape\n            has to be `(224, 224, 3)` (with `channels_last` data format)\n            or `(3, 224, 244)` (with `channels_first` data format).\n            It should have exactly 3 inputs channels,\n            and width and height should be no smaller than 48.\n            E.g. `(200, 200, 3)` would be one valid value.\n\n    # Returns\n        A Keras model instance.\n    \"\"\"\n    img_input = Input(shape=input_shape)\n\n    # Block 1\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\n\n    # Block 2\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\n\n    # Block 3\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\n\n    # Block 4\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)\n\n    # Block 5\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)\n\n    # Classification block\n    x = Flatten(name='flatten')(x)\n    x = Dense(7000, activation='relu', name='fc1')(x)\n    x = Dense(7000, activation='relu', name='fc2')(x)\n    output = Dense(2, activation='softmax', name='predictions')(x)\n\n    # Create model\n    model = Model(img_input, output, name='vgg16_binary')\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:24:14.152833Z","iopub.execute_input":"2024-05-15T14:24:14.153529Z","iopub.status.idle":"2024-05-15T14:24:14.167040Z","shell.execute_reply.started":"2024-05-15T14:24:14.153490Z","shell.execute_reply":"2024-05-15T14:24:14.166147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_three = VGG16_three(input_shape=(image_size, image_size, image_channel))\nmodel_three.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:24:14.168120Z","iopub.execute_input":"2024-05-15T14:24:14.168456Z","iopub.status.idle":"2024-05-15T14:24:14.289768Z","shell.execute_reply.started":"2024-05-15T14:24:14.168424Z","shell.execute_reply":"2024-05-15T14:24:14.288968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_three.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\nmodel_three_logs = model_three.fit(train_generator,\n                    validation_data = val_generator, \n                    callbacks=[learning_rate_reduction],\n                    epochs = 5)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:24:14.290704Z","iopub.execute_input":"2024-05-15T14:24:14.290934Z","iopub.status.idle":"2024-05-15T14:28:05.186020Z","shell.execute_reply.started":"2024-05-15T14:24:14.290913Z","shell.execute_reply":"2024-05-15T14:28:05.185165Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### VGG Model Four\nadding 1  conv layers to each block 2,3,4 and reducing the number of neurons to 3000","metadata":{}},{"cell_type":"code","source":"\n\ndef VGG16_four(input_shape=(224, 224, 3)):\n    \"\"\"Instantiates the VGG16 architecture for binary classification.\n\n    # Arguments\n        input_shape: optional shape tuple, only to be specified\n            if `include_top` is False (otherwise the input shape\n            has to be `(224, 224, 3)` (with `channels_last` data format)\n            or `(3, 224, 244)` (with `channels_first` data format).\n            It should have exactly 3 inputs channels,\n            and width and height should be no smaller than 48.\n            E.g. `(200, 200, 3)` would be one valid value.\n\n    # Returns\n        A Keras model instance.\n    \"\"\"\n    img_input = Input(shape=input_shape)\n\n    # Block 1\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\n\n    # Block 2\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv3')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\n\n    # Block 3\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv4')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\n\n    # Block 4\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv4')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv5')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)\n\n    # Block 5\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)\n\n    # Classification block\n    x = Flatten(name='flatten')(x)\n    x = Dense(3000, activation='relu', name='fc1')(x)\n    x = Dense(3000, activation='relu', name='fc2')(x)\n    output = Dense(2, activation='softmax', name='predictions')(x)\n\n    # Create model\n    model = Model(img_input, output, name='vgg16_binary')\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:28:05.187978Z","iopub.execute_input":"2024-05-15T14:28:05.188367Z","iopub.status.idle":"2024-05-15T14:28:05.206467Z","shell.execute_reply.started":"2024-05-15T14:28:05.188330Z","shell.execute_reply":"2024-05-15T14:28:05.205590Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_four = VGG16_four(input_shape=(image_size, image_size, image_channel))\nmodel_four.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:28:05.207617Z","iopub.execute_input":"2024-05-15T14:28:05.207971Z","iopub.status.idle":"2024-05-15T14:28:05.376975Z","shell.execute_reply.started":"2024-05-15T14:28:05.207939Z","shell.execute_reply":"2024-05-15T14:28:05.376123Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_four.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\nmodel_four_logs = model_four.fit(train_generator,\n                    validation_data = val_generator, \n                    callbacks=[learning_rate_reduction],\n                    epochs = 5)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:28:05.378164Z","iopub.execute_input":"2024-05-15T14:28:05.378407Z","iopub.status.idle":"2024-05-15T14:33:46.089062Z","shell.execute_reply.started":"2024-05-15T14:28:05.378385Z","shell.execute_reply":"2024-05-15T14:33:46.088095Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### VGG Five\nSame as model 4 but last fully connected layer input neurons to 1024","metadata":{}},{"cell_type":"code","source":"\n\ndef VGG16_five(input_shape=(224, 224, 3)):\n    \"\"\"Instantiates the VGG16 architecture for binary classification.\n\n    # Arguments\n        input_shape: optional shape tuple, only to be specified\n            if `include_top` is False (otherwise the input shape\n            has to be `(224, 224, 3)` (with `channels_last` data format)\n            or `(3, 224, 244)` (with `channels_first` data format).\n            It should have exactly 3 inputs channels,\n            and width and height should be no smaller than 48.\n            E.g. `(200, 200, 3)` would be one valid value.\n\n    # Returns\n        A Keras model instance.\n    \"\"\"\n    img_input = Input(shape=input_shape)\n\n    # Block 1\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\n\n    # Block 2\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv3')(x)\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv4')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\n\n    # Block 3\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv4')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\n\n    # Block 4\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv4')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)\n\n    # Block 5\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)\n\n    # Classification block\n    x = Flatten(name='flatten')(x)\n    x = Dense(6000, activation='relu', name='fc1')(x)\n    x = Dense(6000, activation='relu', name='fc2')(x)\n    output = Dense(2, activation='softmax', name='predictions')(x)\n\n    # Create model\n    model = Model(img_input, output, name='vgg16_binary')\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:33:46.090670Z","iopub.execute_input":"2024-05-15T14:33:46.091303Z","iopub.status.idle":"2024-05-15T14:33:46.108538Z","shell.execute_reply.started":"2024-05-15T14:33:46.091267Z","shell.execute_reply":"2024-05-15T14:33:46.107681Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_five = VGG16_five(input_shape=(image_size, image_size, image_channel))\nmodel_five.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:33:46.109743Z","iopub.execute_input":"2024-05-15T14:33:46.110347Z","iopub.status.idle":"2024-05-15T14:33:46.262537Z","shell.execute_reply.started":"2024-05-15T14:33:46.110312Z","shell.execute_reply":"2024-05-15T14:33:46.261695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_five.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\nmodel_five_logs = model_five.fit(train_generator,\n                    validation_data = val_generator, \n                    callbacks=[learning_rate_reduction],\n                    epochs = 5)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:33:46.263831Z","iopub.execute_input":"2024-05-15T14:33:46.264447Z","iopub.status.idle":"2024-05-15T14:39:50.364887Z","shell.execute_reply.started":"2024-05-15T14:33:46.264412Z","shell.execute_reply":"2024-05-15T14:39:50.363977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport pandas as pd\n\n# Example list of models and their training histories\nmodels = [model_one_logs, model_two_logs, model_three_logs, model_four_logs, model_five_logs]\nmodel_names = ['Model 1', 'Model 2', 'Model 3', 'Model 4', 'Model 5']\n\n# Function to plot training history\ndef plot_metrics(history, model_name):\n    plt.figure(figsize=(6, 3))\n\n    # Plot training & validation accuracy values\n    plt.subplot(1, 2, 1)\n    plt.plot(history.history['accuracy'])\n    plt.plot(history.history['val_accuracy'])\n    plt.title('Model Accuracy: ' + model_name)\n    plt.xlabel('Epoch')\n    plt.ylabel('Accuracy')\n    plt.legend(['Train', 'Validation'], loc='upper left')\n\n    # Plot training & validation loss values\n    plt.subplot(1, 2, 2)\n    plt.plot(history.history['loss'])\n    plt.plot(history.history['val_loss'])\n    plt.title('Model Loss: ' + model_name)\n    plt.xlabel('Epoch')\n    plt.ylabel('Loss')\n    plt.legend(['Train', 'Validation'], loc='upper left')\n\n    plt.tight_layout()\n    plt.show()\n\n# Plotting for each model\nfor i, (history, model_name) in enumerate(zip(models, model_names), 1):\n    plot_metrics(history, model_name)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:40:38.375030Z","iopub.execute_input":"2024-05-15T14:40:38.375996Z","iopub.status.idle":"2024-05-15T14:40:40.622402Z","shell.execute_reply.started":"2024-05-15T14:40:38.375960Z","shell.execute_reply":"2024-05-15T14:40:40.621424Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport pandas as pd\n\n# Example list of models and their training histories\nmodels = [model_one_logs, model_two_logs, model_three_logs, model_four_logs, model_five_logs]\nmodel_names = ['Model 1', 'Model 2', 'Model 3', 'Model 4', 'Model 5']\n\n# Plotting\nplt.figure(figsize=(12, 6))\n\n# Plot training & validation accuracy values for each model\nfor history, model_name in zip(models, model_names):\n    plt.plot(history.history['accuracy'], label=model_name + ' Train')\n    plt.plot(history.history['val_accuracy'], label=model_name + ' Validation')\n\nplt.title('Model Accuracy Comparison')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()\n\nplt.figure(figsize=(12, 6))\n\n# Plot training & validation loss values for each model\nfor history, model_name in zip(models, model_names):\n    plt.plot(history.history['loss'], label=model_name + ' Train')\n    plt.plot(history.history['val_loss'], label=model_name + ' Validation')\n\nplt.title('Model Loss Comparison')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:41:49.442291Z","iopub.execute_input":"2024-05-15T14:41:49.443180Z","iopub.status.idle":"2024-05-15T14:41:50.327319Z","shell.execute_reply.started":"2024-05-15T14:41:49.443138Z","shell.execute_reply":"2024-05-15T14:41:50.326374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Example list of models and their training histories\nmodels = [model_one_logs, model_two_logs, model_three_logs, model_four_logs, model_five_logs]\nmodel_names = ['Model 1', 'Model 2', 'Model 3', 'Model 4', 'Model 5']\n\n# Extract final validation accuracy for each model\nfinal_val_acc = [history.history['val_accuracy'][-1] for history in models]\n\n# Plotting\nplt.figure(figsize=(10, 6))\nplt.bar(model_names, final_val_acc, color='skyblue')\nplt.title('Final Validation Accuracy Comparison')\nplt.xlabel('Model')\nplt.ylabel('Final Validation Accuracy')\nplt.ylim(0, 1)  # Set y-axis limit to ensure proper visualization of accuracy values\nplt.xticks(rotation=45)  # Rotate x-axis labels for better readability\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:43:19.864743Z","iopub.execute_input":"2024-05-15T14:43:19.865560Z","iopub.status.idle":"2024-05-15T14:43:20.121194Z","shell.execute_reply.started":"2024-05-15T14:43:19.865529Z","shell.execute_reply":"2024-05-15T14:43:20.120278Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Example list of models and their training histories\nmodels = [model_one_logs, model_two_logs, model_three_logs, model_four_logs, model_five_logs]\nmodel_names = ['Model 1', 'Model 2', 'Model 3', 'Model 4', 'Model 5']\n\n# Extract final validation loss for each model\nfinal_val_loss = [history.history['val_loss'][-1] for history in models]\n\n# Plotting\nplt.figure(figsize=(10, 6))\nplt.bar(model_names, final_val_loss, color='salmon')\nplt.title('Final Validation Loss Comparison')\nplt.xlabel('Model')\nplt.ylabel('Final Validation Loss')\nplt.ylim(0, max(final_val_loss)*1.2)  # Set y-axis limit to ensure proper visualization of loss values\nplt.xticks(rotation=45)  # Rotate x-axis labels for better readability\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T14:44:29.863956Z","iopub.execute_input":"2024-05-15T14:44:29.864297Z","iopub.status.idle":"2024-05-15T14:44:30.057031Z","shell.execute_reply.started":"2024-05-15T14:44:29.864270Z","shell.execute_reply":"2024-05-15T14:44:30.056085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}