{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"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"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30699,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"","metadata":{}},{"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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-15T17:14:10.689484Z","iopub.execute_input":"2024-05-15T17:14:10.690288Z","iopub.status.idle":"2024-05-15T17:14:11.082707Z","shell.execute_reply.started":"2024-05-15T17:14:10.690252Z","shell.execute_reply":"2024-05-15T17:14:11.081688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:14:11.084703Z","iopub.execute_input":"2024-05-15T17:14:11.085273Z","iopub.status.idle":"2024-05-15T17:14:14.968111Z","shell.execute_reply.started":"2024-05-15T17:14:11.085237Z","shell.execute_reply":"2024-05-15T17:14:14.967278Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:14:14.969379Z","iopub.execute_input":"2024-05-15T17:14:14.970200Z","iopub.status.idle":"2024-05-15T17:14:26.462079Z","shell.execute_reply.started":"2024-05-15T17:14:14.970161Z","shell.execute_reply":"2024-05-15T17:14:26.461110Z"},"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-15T17:14:26.465119Z","iopub.execute_input":"2024-05-15T17:14:26.465526Z","iopub.status.idle":"2024-05-15T17:14:26.507417Z","shell.execute_reply.started":"2024-05-15T17:14:26.465491Z","shell.execute_reply":"2024-05-15T17:14:26.506403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.shape","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:14:26.508661Z","iopub.execute_input":"2024-05-15T17:14:26.508942Z","iopub.status.idle":"2024-05-15T17:14:26.896027Z","shell.execute_reply.started":"2024-05-15T17:14:26.508917Z","shell.execute_reply":"2024-05-15T17:14:26.894977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:14:26.897358Z","iopub.execute_input":"2024-05-15T17:14:26.897699Z","iopub.status.idle":"2024-05-15T17:14:26.960763Z","shell.execute_reply.started":"2024-05-15T17:14:26.897671Z","shell.execute_reply":"2024-05-15T17:14:26.959795Z"},"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-15T17:14:26.962102Z","iopub.execute_input":"2024-05-15T17:14:26.962472Z","iopub.status.idle":"2024-05-15T17:14:30.722514Z","shell.execute_reply.started":"2024-05-15T17:14:26.962442Z","shell.execute_reply":"2024-05-15T17:14:30.721398Z"},"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-15T17:14:30.723688Z","iopub.execute_input":"2024-05-15T17:14:30.723966Z","iopub.status.idle":"2024-05-15T17:14:30.728746Z","shell.execute_reply.started":"2024-05-15T17:14:30.723942Z","shell.execute_reply":"2024-05-15T17:14:30.727659Z"},"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-15T17:14:30.730033Z","iopub.execute_input":"2024-05-15T17:14:30.730334Z","iopub.status.idle":"2024-05-15T17:14:32.627300Z","shell.execute_reply.started":"2024-05-15T17:14:30.730308Z","shell.execute_reply":"2024-05-15T17:14:32.626191Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:14:32.632508Z","iopub.execute_input":"2024-05-15T17:14:32.632939Z","iopub.status.idle":"2024-05-15T17:14:32.967731Z","shell.execute_reply.started":"2024-05-15T17:14:32.632900Z","shell.execute_reply":"2024-05-15T17:14:32.966874Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:14:32.968898Z","iopub.execute_input":"2024-05-15T17:14:32.969274Z","iopub.status.idle":"2024-05-15T17:14:33.675581Z","shell.execute_reply.started":"2024-05-15T17:14:32.969239Z","shell.execute_reply":"2024-05-15T17:14:33.674762Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:14:33.676683Z","iopub.execute_input":"2024-05-15T17:14:33.676962Z","iopub.status.idle":"2024-05-15T17:14:33.682251Z","shell.execute_reply.started":"2024-05-15T17:14:33.676938Z","shell.execute_reply":"2024-05-15T17:14:33.681276Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Making changes in the archtecture","metadata":{}},{"cell_type":"markdown","source":"# VGG16-1(Original)--->no changes","metadata":{}},{"cell_type":"code","source":"def 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-15T17:14:33.683789Z","iopub.execute_input":"2024-05-15T17:14:33.684115Z","iopub.status.idle":"2024-05-15T17:14:33.703484Z","shell.execute_reply.started":"2024-05-15T17:14:33.684089Z","shell.execute_reply":"2024-05-15T17:14:33.702528Z"},"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-15T17:14:33.704728Z","iopub.execute_input":"2024-05-15T17:14:33.705113Z","iopub.status.idle":"2024-05-15T17:14:34.343075Z","shell.execute_reply.started":"2024-05-15T17:14:33.705075Z","shell.execute_reply":"2024-05-15T17:14:34.342154Z"},"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-15T17:14:34.344044Z","iopub.execute_input":"2024-05-15T17:14:34.344308Z","iopub.status.idle":"2024-05-15T17:14:34.350681Z","shell.execute_reply.started":"2024-05-15T17:14:34.344284Z","shell.execute_reply":"2024-05-15T17:14:34.349616Z"},"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-15T17:14:34.351863Z","iopub.execute_input":"2024-05-15T17:14:34.352900Z","iopub.status.idle":"2024-05-15T17:14:34.369507Z","shell.execute_reply.started":"2024-05-15T17:14:34.352864Z","shell.execute_reply":"2024-05-15T17:14:34.368770Z"},"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-15T17:14:34.370677Z","iopub.execute_input":"2024-05-15T17:14:34.371433Z","iopub.status.idle":"2024-05-15T17:19:22.390953Z","shell.execute_reply.started":"2024-05-15T17:14:34.371400Z","shell.execute_reply":"2024-05-15T17:19:22.390066Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# VGG16-2(Adding L2 regularization)","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.regularizers import l2\n\ndef VGG16_two(input_shape=(224, 224, 3), l2_reg=0.01):\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        l2_reg: L2 regularization parameter.\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', \n               kernel_regularizer=l2(l2_reg), name='block1_conv1')(img_input)\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', \n               kernel_regularizer=l2(l2_reg), 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', \n               kernel_regularizer=l2(l2_reg), name='block2_conv1')(x)\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', \n               kernel_regularizer=l2(l2_reg), 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', \n               kernel_regularizer=l2(l2_reg), name='block3_conv1')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', \n               kernel_regularizer=l2(l2_reg), name='block3_conv2')(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', \n               kernel_regularizer=l2(l2_reg), 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', \n               kernel_regularizer=l2(l2_reg), name='block4_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', \n               kernel_regularizer=l2(l2_reg), name='block4_conv2')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', \n               kernel_regularizer=l2(l2_reg), 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', \n               kernel_regularizer=l2(l2_reg), name='block5_conv1')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', \n               kernel_regularizer=l2(l2_reg), name='block5_conv2')(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', \n               kernel_regularizer=l2(l2_reg), 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', kernel_regularizer=l2(l2_reg), name='fc1')(x)\n    x = Dense(4096, activation='relu', kernel_regularizer=l2(l2_reg), 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\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:19:22.394333Z","iopub.execute_input":"2024-05-15T17:19:22.394737Z","iopub.status.idle":"2024-05-15T17:19:22.413698Z","shell.execute_reply.started":"2024-05-15T17:19:22.394707Z","shell.execute_reply":"2024-05-15T17:19:22.412665Z"},"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-15T17:19:22.415027Z","iopub.execute_input":"2024-05-15T17:19:22.415398Z","iopub.status.idle":"2024-05-15T17:19:22.550109Z","shell.execute_reply.started":"2024-05-15T17:19:22.415365Z","shell.execute_reply":"2024-05-15T17:19:22.549203Z"},"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-15T17:19:22.551339Z","iopub.execute_input":"2024-05-15T17:19:22.551652Z","iopub.status.idle":"2024-05-15T17:19:22.560426Z","shell.execute_reply.started":"2024-05-15T17:19:22.551621Z","shell.execute_reply":"2024-05-15T17:19:22.559470Z"},"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-15T17:19:22.561919Z","iopub.execute_input":"2024-05-15T17:19:22.562330Z","iopub.status.idle":"2024-05-15T17:24:03.525384Z","shell.execute_reply.started":"2024-05-15T17:19:22.562297Z","shell.execute_reply":"2024-05-15T17:24:03.524578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# VGG16-3 ( increase the neuron to 6666 and use dropout regularization , dropout rate being 0.5)","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Dropout\n\ndef VGG16_three(input_shape=(224, 224, 3), dropout_rate=0.5):\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        dropout_rate: dropout rate for Dropout layers.\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    x = Dropout(dropout_rate)(x)  # Adding dropout after block 1\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    x = Dropout(dropout_rate)(x)  # Adding dropout after block 2\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    x = Dropout(dropout_rate)(x)  # Adding dropout after block 3\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    x = Dropout(dropout_rate)(x)  # Adding dropout after block 4\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    x = Dropout(dropout_rate)(x)  # Adding dropout after block 5\n\n    # Classification block\n    x = Flatten(name='flatten')(x)\n    x = Dense(6666, activation='relu', name='fc1')(x)\n    x = Dropout(dropout_rate)(x)  # Adding dropout after fc1\n    x = Dense(6666, activation='relu', name='fc2')(x)\n    x = Dropout(dropout_rate)(x)  # Adding dropout after fc2\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\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:24:03.527262Z","iopub.execute_input":"2024-05-15T17:24:03.527701Z","iopub.status.idle":"2024-05-15T17:24:03.545114Z","shell.execute_reply.started":"2024-05-15T17:24:03.527661Z","shell.execute_reply":"2024-05-15T17:24:03.544126Z"},"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-15T17:24:03.546234Z","iopub.execute_input":"2024-05-15T17:24:03.546502Z","iopub.status.idle":"2024-05-15T17:24:03.712231Z","shell.execute_reply.started":"2024-05-15T17:24:03.546479Z","shell.execute_reply":"2024-05-15T17:24:03.711266Z"},"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-15T17:24:03.713252Z","iopub.execute_input":"2024-05-15T17:24:03.713525Z","iopub.status.idle":"2024-05-15T17:29:14.819704Z","shell.execute_reply.started":"2024-05-15T17:24:03.713500Z","shell.execute_reply":"2024-05-15T17:29:14.818756Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# VGG16-4 (Use batch normalization and elastic net  regularization )","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, BatchNormalization\nfrom tensorflow.keras.regularizers import l1_l2\n\ndef VGG16_four(input_shape=(224, 224, 3), l1=0.01, l2=0.01):\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        l1: L1 regularization parameter.\n        l2: L2 regularization parameter.\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', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='block1_conv1')(img_input)\n    x = BatchNormalization()(x)\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='block1_conv2')(x)\n    x = BatchNormalization()(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', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='block2_conv1')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='block2_conv2')(x)\n    x = BatchNormalization()(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', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='block3_conv1')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='block3_conv2')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='block3_conv3')(x)\n    x = BatchNormalization()(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', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='block4_conv1')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='block4_conv2')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='block4_conv3')(x)\n    x = BatchNormalization()(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', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='block5_conv1')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='block5_conv2')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='block5_conv3')(x)\n    x = BatchNormalization()(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', kernel_regularizer=l1_l2(l1=l1, l2=l2), name='fc1')(x)\n    x = Dense(4096, activation='relu', kernel_regularizer=l1_l2(l1=l1, l2=l2), 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\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:29:14.821147Z","iopub.execute_input":"2024-05-15T17:29:14.821438Z","iopub.status.idle":"2024-05-15T17:29:14.844565Z","shell.execute_reply.started":"2024-05-15T17:29:14.821411Z","shell.execute_reply":"2024-05-15T17:29:14.843667Z"},"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-15T17:29:14.845895Z","iopub.execute_input":"2024-05-15T17:29:14.846544Z","iopub.status.idle":"2024-05-15T17:29:15.098739Z","shell.execute_reply.started":"2024-05-15T17:29:14.846511Z","shell.execute_reply":"2024-05-15T17:29:15.097827Z"},"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-15T17:29:15.099922Z","iopub.execute_input":"2024-05-15T17:29:15.100214Z","iopub.status.idle":"2024-05-15T17:34:55.992139Z","shell.execute_reply.started":"2024-05-15T17:29:15.100188Z","shell.execute_reply":"2024-05-15T17:34:55.991330Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# VGG16-5 ( incresed the neuron the 6666 , dropout rate is 0.5 , batch normalization)","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, BatchNormalization, Dropout\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 = BatchNormalization()(x)\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)\n    x = BatchNormalization()(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 = BatchNormalization()(x)\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)\n    x = BatchNormalization()(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 = BatchNormalization()(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)\n    x = BatchNormalization()(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 = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)\n    x = BatchNormalization()(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 = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)\n    x = BatchNormalization()(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(6666, activation='relu', name='fc1')(x)\n    x = Dropout(0.5)(x)\n    x = Dense(6666, activation='relu', name='fc2')(x)\n    x = Dropout(0.5)(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\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:34:55.997429Z","iopub.execute_input":"2024-05-15T17:34:55.997766Z","iopub.status.idle":"2024-05-15T17:34:56.016862Z","shell.execute_reply.started":"2024-05-15T17:34:55.997736Z","shell.execute_reply":"2024-05-15T17:34:56.015826Z"},"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-15T17:34:56.017985Z","iopub.execute_input":"2024-05-15T17:34:56.018272Z","iopub.status.idle":"2024-05-15T17:34:56.277378Z","shell.execute_reply.started":"2024-05-15T17:34:56.018247Z","shell.execute_reply":"2024-05-15T17:34:56.276474Z"},"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-15T17:34:56.278558Z","iopub.execute_input":"2024-05-15T17:34:56.278885Z","iopub.status.idle":"2024-05-15T17:40:24.539505Z","shell.execute_reply.started":"2024-05-15T17:34:56.278858Z","shell.execute_reply":"2024-05-15T17:40:24.538657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# VGG16-6 (Increased the convolution layer in each block and dropout regularization also added)","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Dropout\n\ndef VGG16_six(input_shape=(224, 224, 3), dropout_rate=0.5):\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        dropout_rate: dropout rate for Dropout layers.\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 = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv3')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\n    x = Dropout(dropout_rate)(x)  # Adding dropout after block 1\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    x = Dropout(dropout_rate)(x)  # Adding dropout after block 2\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    x = Dropout(dropout_rate)(x)  # Adding dropout after block 3\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    x = Dropout(dropout_rate)(x)  # Adding dropout after block 4\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 = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv4')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)\n    x = Dropout(dropout_rate)(x)  # Adding dropout after block 5\n\n    # Classification block\n    x = Flatten(name='flatten')(x)\n    x = Dense(6666, activation='relu', name='fc1')(x)\n    x = Dropout(dropout_rate)(x)  # Adding dropout after fc1\n    x = Dense(6666, activation='relu', name='fc2')(x)\n    x = Dropout(dropout_rate)(x)  # Adding dropout after fc2\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\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:40:24.541151Z","iopub.execute_input":"2024-05-15T17:40:24.541440Z","iopub.status.idle":"2024-05-15T17:40:24.561789Z","shell.execute_reply.started":"2024-05-15T17:40:24.541415Z","shell.execute_reply":"2024-05-15T17:40:24.560763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_six = VGG16_six(input_shape=(image_size, image_size, image_channel))\nmodel_six.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:40:24.562984Z","iopub.execute_input":"2024-05-15T17:40:24.563284Z","iopub.status.idle":"2024-05-15T17:40:24.754577Z","shell.execute_reply.started":"2024-05-15T17:40:24.563253Z","shell.execute_reply":"2024-05-15T17:40:24.753644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_six.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\nmodel_six_logs = model_six.fit(train_generator,\n                    validation_data = val_generator, \n                    callbacks=[learning_rate_reduction],\n                    epochs = 5)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:40:24.755849Z","iopub.execute_input":"2024-05-15T17:40:24.756138Z","iopub.status.idle":"2024-05-15T17:47:17.607413Z","shell.execute_reply.started":"2024-05-15T17:40:24.756114Z","shell.execute_reply":"2024-05-15T17:47:17.606376Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# VGG16-7 (covolution layer+batch normalization+dropout)","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization\n\ndef VGG16_seven(input_shape=(224, 224, 3), dropout_rate=0.5):\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        dropout_rate: dropout rate for Dropout layers.\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 = BatchNormalization()(x)\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv3')(x)\n    x = BatchNormalization()(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\n    x = Dropout(dropout_rate)(x)  # Adding dropout after block 1\n\n    # Block 2\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv3')(x)\n    x = BatchNormalization()(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\n    x = Dropout(dropout_rate)(x)  # Adding dropout after block 2\n\n    # Block 3\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv4')(x)\n    x = BatchNormalization()(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\n    x = Dropout(dropout_rate)(x)  # Adding dropout after block 3\n\n    # Block 4\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv4')(x)\n    x = BatchNormalization()(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)\n    x = Dropout(dropout_rate)(x)  # Adding dropout after block 4\n\n    # Block 5\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)\n    x = BatchNormalization()(x)\n    x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv4')(x)\n    x = BatchNormalization()(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)\n    x = Dropout(dropout_rate)(x)  # Adding dropout after block 5\n\n    # Classification block\n    x = Flatten(name='flatten')(x)\n    x = Dense(6666, activation='relu', name='fc1')(x)\n    x = Dropout(dropout_rate)(x)  # Adding dropout after fc1\n    x = Dense(6666, activation='relu', name='fc2')(x)\n    x = Dropout(dropout_rate)(x)  # Adding dropout after fc2\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\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:47:17.609991Z","iopub.execute_input":"2024-05-15T17:47:17.610384Z","iopub.status.idle":"2024-05-15T17:47:17.633944Z","shell.execute_reply.started":"2024-05-15T17:47:17.610346Z","shell.execute_reply":"2024-05-15T17:47:17.633000Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_seven = VGG16_seven(input_shape=(image_size, image_size, image_channel))\nmodel_seven.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:47:17.635313Z","iopub.execute_input":"2024-05-15T17:47:17.635776Z","iopub.status.idle":"2024-05-15T17:47:17.990847Z","shell.execute_reply.started":"2024-05-15T17:47:17.635742Z","shell.execute_reply":"2024-05-15T17:47:17.989924Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_seven.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\nmodel_seven_logs = model_seven.fit(train_generator,\n                    validation_data = val_generator, \n                    callbacks=[learning_rate_reduction],\n                    epochs = 5)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:47:17.992106Z","iopub.execute_input":"2024-05-15T17:47:17.992397Z","iopub.status.idle":"2024-05-15T17:54:59.625198Z","shell.execute_reply.started":"2024-05-15T17:47:17.992371Z","shell.execute_reply":"2024-05-15T17:54:59.624350Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Plortting the Metrics","metadata":{}},{"cell_type":"code","source":"logs_list=[model_one_logs,model_two_logs,model_three_logs,model_four_logs,model_five_logs,model_six_logs,model_seven_logs]","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:54:59.626667Z","iopub.execute_input":"2024-05-15T17:54:59.627059Z","iopub.status.idle":"2024-05-15T17:54:59.631939Z","shell.execute_reply.started":"2024-05-15T17:54:59.627028Z","shell.execute_reply":"2024-05-15T17:54:59.631060Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_accuracy_from_logs(logs_list, epochs=5):\n    # Dictionary to store training history of all models\n    history_dict = {}\n\n    # Extract accuracy from logs and store in history dictionary\n    for i, logs in enumerate(logs_list, start=1):\n        history_dict[f\"Model_{i}\"] = logs.history\n\n    # Plot the accuracy of all models\n    plt.figure(figsize=(10, 6))\n    for model_name, history in history_dict.items():\n        accuracy = history['accuracy']\n        plt.plot(range(1, epochs + 1), accuracy, label=model_name)\n\n    plt.title('Accuracy of Models')\n    plt.xlabel('Epochs')\n    plt.ylabel('Accuracy')\n    plt.legend()\n    plt.grid()\n    plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:54:59.633414Z","iopub.execute_input":"2024-05-15T17:54:59.634021Z","iopub.status.idle":"2024-05-15T17:54:59.655675Z","shell.execute_reply.started":"2024-05-15T17:54:59.633986Z","shell.execute_reply":"2024-05-15T17:54:59.654851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_accuracy_from_logs(logs_list,5)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:55:39.554054Z","iopub.execute_input":"2024-05-15T17:55:39.554441Z","iopub.status.idle":"2024-05-15T17:55:39.906201Z","shell.execute_reply.started":"2024-05-15T17:55:39.554411Z","shell.execute_reply":"2024-05-15T17:55:39.905262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_loss_from_logs(logs_list, epochs=5):\n    # Dictionary to store training history of all models\n    history_dict = {}\n\n    # Extract loss from logs and store in history dictionary\n    for i, logs in enumerate(logs_list, start=1):\n        history_dict[f\"Model_{i}\"] = logs.history\n\n    # Plot the loss of all models\n    plt.figure(figsize=(10, 6))\n    for model_name, history in history_dict.items():\n        loss = history['loss']\n        plt.plot(range(1, epochs + 1), loss, label=model_name)\n\n    plt.title('Loss of Models')\n    plt.xlabel('Epochs')\n    plt.ylabel('Loss')\n    plt.legend()\n    plt.grid()\n    plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:55:52.109198Z","iopub.execute_input":"2024-05-15T17:55:52.109660Z","iopub.status.idle":"2024-05-15T17:55:52.117074Z","shell.execute_reply.started":"2024-05-15T17:55:52.109605Z","shell.execute_reply":"2024-05-15T17:55:52.116071Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_loss_from_logs(logs_list,5)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:55:52.548983Z","iopub.execute_input":"2024-05-15T17:55:52.549527Z","iopub.status.idle":"2024-05-15T17:55:52.841020Z","shell.execute_reply.started":"2024-05-15T17:55:52.549489Z","shell.execute_reply":"2024-05-15T17:55:52.840034Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_metrics_from_logs(logs_list, epochs=5):\n    \"\"\"\n    Plot the metrics (accuracy, loss, validation accuracy, validation loss) of models using their training logs.\n\n    Args:\n    - logs_list: A list of training logs for different models.\n    - epochs (int): Number of epochs for each model.\n\n    Returns:\n    - None\n    \"\"\"\n    # Dictionary to store training history of all models\n    history_dict = {}\n\n    # Extract metrics from logs and store in history dictionary\n    for i, logs in enumerate(logs_list, start=1):\n        history_dict[f\"Model_{i}\"] = logs.history\n\n    # Plot the metrics of all models\n    plt.figure(figsize=(16, 10))\n\n    # Plot accuracy\n    plt.subplot(2, 2, 1)\n    for model_name, history in history_dict.items():\n        accuracy = history['accuracy']\n        plt.plot(range(1, epochs + 1), accuracy, label=model_name)\n    plt.title('Training Accuracy')\n    plt.xlabel('Epochs')\n    plt.ylabel('Accuracy')\n    plt.legend()\n    plt.grid()\n\n    # Plot loss\n    plt.subplot(2, 2, 2)\n    for model_name, history in history_dict.items():\n        loss = history['loss']\n        plt.plot(range(1, epochs + 1), loss, label=model_name)\n    plt.title('Training Loss')\n    plt.xlabel('Epochs')\n    plt.ylabel('Loss')\n    plt.legend()\n    plt.grid()\n\n    # Plot validation accuracy\n    plt.subplot(2, 2, 3)\n    for model_name, history in history_dict.items():\n        val_accuracy = history.get('val_accuracy', [])\n        if val_accuracy:\n            plt.plot(range(1, epochs + 1), val_accuracy, label=model_name)\n    plt.title('Validation Accuracy')\n    plt.xlabel('Epochs')\n    plt.ylabel('Accuracy')\n    plt.legend()\n    plt.grid()\n\n    # Plot validation loss\n    plt.subplot(2, 2, 4)\n    for model_name, history in history_dict.items():\n        val_loss = history.get('val_loss', [])\n        if val_loss:\n            plt.plot(range(1, epochs + 1), val_loss, label=model_name)\n    plt.title('Validation Loss')\n    plt.xlabel('Epochs')\n    plt.ylabel('Loss')\n    plt.legend()\n    plt.grid()\n\n    plt.tight_layout()\n    plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:55:53.470019Z","iopub.execute_input":"2024-05-15T17:55:53.470744Z","iopub.status.idle":"2024-05-15T17:55:53.484609Z","shell.execute_reply.started":"2024-05-15T17:55:53.470710Z","shell.execute_reply":"2024-05-15T17:55:53.483583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_metrics_from_logs(logs_list,5)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:55:59.388959Z","iopub.execute_input":"2024-05-15T17:55:59.389619Z","iopub.status.idle":"2024-05-15T17:56:00.821106Z","shell.execute_reply.started":"2024-05-15T17:55:59.389566Z","shell.execute_reply":"2024-05-15T17:56:00.820005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}