{"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":30700,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Name: Mukul Aggarwal \n\n# Enrollment Number: MSD230087","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:53:08.691859Z","iopub.execute_input":"2024-05-15T17:53:08.692275Z","iopub.status.idle":"2024-05-15T17:53:08.704128Z","shell.execute_reply.started":"2024-05-15T17:53:08.692244Z","shell.execute_reply":"2024-05-15T17:53:08.703100Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\ndef extract_zip(input_zip, output_dir=\".\"):\n    with zipfile.ZipFile(input_zip, \"r\") as z:\n        z.extractall(output_dir)\n\ntrain_zip_path = \"/kaggle/input/dogs-vs-cats/train.zip\"\ntest_zip_path = \"/kaggle/input/dogs-vs-cats/test1.zip\"\nextract_zip(train_zip_path)\nextract_zip(test_zip_path)","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:53:08.706159Z","iopub.execute_input":"2024-05-15T17:53:08.706512Z","iopub.status.idle":"2024-05-15T17:53:19.087441Z","shell.execute_reply.started":"2024-05-15T17:53:08.706479Z","shell.execute_reply":"2024-05-15T17:53:19.086366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Import necessary libraries\nimport os\nimport pandas as pd\n\n# Get a list of filenames in the \"train\" directory\nfilenames = os.listdir(\"train\")\n\n# Initialize an empty list to store labels\nlabels = []\n\n# Loop through each filename to determine its label based on its name\nfor filename in filenames:\n    if \"cat\" in filename:\n        labels.append('cat')  # Append 'cat' if the filename contains \"cat\"\n    elif \"dog\" in filename:\n        labels.append('dog')  # Append 'dog' if the filename contains \"dog\"\n    \n# Create a DataFrame with filenames and their corresponding labels\ndf = pd.DataFrame({\n    'Filename': filenames,\n    'Label': labels\n})\n\n# Display the first five rows of the DataFrame\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:53:19.088662Z","iopub.execute_input":"2024-05-15T17:53:19.089048Z","iopub.status.idle":"2024-05-15T17:53:19.123592Z","shell.execute_reply.started":"2024-05-15T17:53:19.089014Z","shell.execute_reply":"2024-05-15T17:53:19.122552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.info()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:53:19.125033Z","iopub.execute_input":"2024-05-15T17:53:19.125352Z","iopub.status.idle":"2024-05-15T17:53:19.977681Z","shell.execute_reply.started":"2024-05-15T17:53:19.125325Z","shell.execute_reply":"2024-05-15T17:53:19.976639Z"},"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:53:19.981041Z","iopub.execute_input":"2024-05-15T17:53:19.981707Z","iopub.status.idle":"2024-05-15T17:53:19.989437Z","shell.execute_reply.started":"2024-05-15T17:53:19.981665Z","shell.execute_reply":"2024-05-15T17:53:19.988458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# train test split using dataframe\n\nlabels = df['Label']\n\n# 20% split\n# 80%.    20%\nX_train, X_temp = train_test_split(df, 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:53:19.990595Z","iopub.execute_input":"2024-05-15T17:53:19.991447Z","iopub.status.idle":"2024-05-15T17:53:20.042093Z","shell.execute_reply.started":"2024-05-15T17:53:19.991413Z","shell.execute_reply":"2024-05-15T17:53:20.041159Z"},"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:53:20.043390Z","iopub.execute_input":"2024-05-15T17:53:20.043862Z","iopub.status.idle":"2024-05-15T17:53:23.417060Z","shell.execute_reply.started":"2024-05-15T17:53:20.043828Z","shell.execute_reply":"2024-05-15T17:53:23.416063Z"},"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:53:23.418423Z","iopub.execute_input":"2024-05-15T17:53:23.418815Z","iopub.status.idle":"2024-05-15T17:53:23.423390Z","shell.execute_reply.started":"2024-05-15T17:53:23.418782Z","shell.execute_reply":"2024-05-15T17:53:23.422466Z"},"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:53:23.424731Z","iopub.execute_input":"2024-05-15T17:53:23.425027Z","iopub.status.idle":"2024-05-15T17:53:23.432932Z","shell.execute_reply.started":"2024-05-15T17:53:23.425004Z","shell.execute_reply":"2024-05-15T17:53:23.432161Z"},"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:53:23.434012Z","iopub.execute_input":"2024-05-15T17:53:23.434271Z","iopub.status.idle":"2024-05-15T17:53:23.730780Z","shell.execute_reply.started":"2024-05-15T17:53:23.434249Z","shell.execute_reply":"2024-05-15T17:53:23.729886Z"},"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:53:23.731989Z","iopub.execute_input":"2024-05-15T17:53:23.732349Z","iopub.status.idle":"2024-05-15T17:53:24.402089Z","shell.execute_reply.started":"2024-05-15T17:53:23.732317Z","shell.execute_reply":"2024-05-15T17:53:24.401142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport os\nimport random\nimport matplotlib.image as mpimg\n\n# Function to display a specified number of images for a given category (cats or dogs)\ndef display_images(image_paths, category):\n    plt.figure(figsize=(24, 4))  # Set figure size for the display\n    for i, img_path in enumerate(image_paths):\n        plt.subplot(1, 3, i + 1)  # Arrange images in a single row\n        img = mpimg.imread(os.path.join('train', img_path))  # Read the image file\n        plt.imshow(img)  # Display the image\n        plt.title(category)  # Set the title to the category (cat or dog)\n        plt.axis('off')  # Hide the axis for a cleaner look\n    plt.show()  # Display the plot\n\n# List all cat and dog filenames in the \"train\" directory\ncat_images = [filename for filename in filenames if 'cat' in filename]\ndog_images = [filename for filename in filenames if 'dog' in filename]\n\n# Randomly select three images from each category\nselected_cat_images = random.sample(cat_images, 3)\nselected_dog_images = random.sample(dog_images, 3)\n\n# Display the selected images for each category\ndisplay_images(selected_cat_images, 'Cat')\ndisplay_images(selected_dog_images, 'Dog')","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:53:24.403316Z","iopub.execute_input":"2024-05-15T17:53:24.403599Z","iopub.status.idle":"2024-05-15T17:53:25.439917Z","shell.execute_reply.started":"2024-05-15T17:53:24.403575Z","shell.execute_reply":"2024-05-15T17:53:25.438962Z"},"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\ndef VGG16(input_tensor=None, input_shape=None,\n          pooling=None,\n          classes=1000,\n          block2_layers=2, block2_neurons=128,\n          block3_layers=3, block3_neurons=256,\n          block4_layers=3, block4_neurons=512):\n    \"\"\"\n    Instantiates the VGG16 architecture with configurable parameters.\n    \"\"\"\n    # Original VGG16 architecture code goes here...\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    for i in range(block2_layers):\n        x = Conv2D(block2_neurons, (3, 3), activation='relu', padding='same', name=f'block2_conv{i+1}')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\n\n    # Block 3\n    for i in range(block3_layers):\n        x = Conv2D(block3_neurons, (3, 3), activation='relu', padding='same', name=f'block3_conv{i+1}')(x)\n    x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\n\n    # Block 4\n    for i in range(block4_layers):\n        x = Conv2D(block4_neurons, (3, 3), activation='relu', padding='same', name=f'block4_conv{i+1}')(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:53:25.441386Z","iopub.execute_input":"2024-05-15T17:53:25.441744Z","iopub.status.idle":"2024-05-15T17:53:25.460765Z","shell.execute_reply.started":"2024-05-15T17:53:25.441715Z","shell.execute_reply":"2024-05-15T17:53:25.459864Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"configurations = [\n    {'block2_layers': 2, 'block2_neurons': 128, 'block3_layers': 3, 'block3_neurons': 256, 'block4_layers': 3, 'block4_neurons': 512},\n    {'block2_layers': 2, 'block2_neurons': 64, 'block3_layers': 3, 'block3_neurons': 128, 'block4_layers': 3, 'block4_neurons': 256},\n    {'block2_layers': 3, 'block2_neurons': 128, 'block3_layers': 2, 'block3_neurons': 256, 'block4_layers': 4, 'block4_neurons': 512},\n    {'block2_layers': 4, 'block2_neurons': 128, 'block3_layers': 3, 'block3_neurons': 256, 'block4_layers': 2, 'block4_neurons': 512},\n    {'block2_layers': 3, 'block2_neurons': 64, 'block3_layers': 4, 'block3_neurons': 128, 'block4_layers': 4, 'block4_neurons': 256}\n]\nhistories = []\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:53:25.464405Z","iopub.execute_input":"2024-05-15T17:53:25.464719Z","iopub.status.idle":"2024-05-15T17:53:27.103369Z","shell.execute_reply.started":"2024-05-15T17:53:25.464694Z","shell.execute_reply":"2024-05-15T17:53:27.102335Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Model 1","metadata":{}},{"cell_type":"code","source":"config = configurations[0]\n\nmodel = VGG16(input_shape = (image_size, image_size, image_channel), # No pre-trained weights\n              block2_layers=config['block2_layers'], block2_neurons=config['block2_neurons'],\n              block3_layers=config['block3_layers'], block3_neurons=config['block3_neurons'],\n              block4_layers=config['block4_layers'], block4_neurons=config['block4_neurons'])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\nlearning_rate_reduction = ReduceLROnPlateau(monitor = 'val_accuracy',\n                                        patience=2,\n                                        factor=0.5,\n                                        min_lr = 0.00001,\n                                        verbose = 1)\n# Train the model\nhistory = model.fit(train_generator, validation_data = val_generator, callbacks = [learning_rate_reduction], epochs = 5\n)\n\n# Evaluate the model on validation set\nloss, accuracy = model.evaluate(val_generator, steps=val_generator.samples // bat_size)\nprint(f\"Configuration: {config}, Validation Accuracy: {accuracy}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:53:27.104775Z","iopub.execute_input":"2024-05-15T17:53:27.105113Z","iopub.status.idle":"2024-05-15T17:58:00.839545Z","shell.execute_reply.started":"2024-05-15T17:53:27.105050Z","shell.execute_reply":"2024-05-15T17:58:00.838704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:58:00.840546Z","iopub.execute_input":"2024-05-15T17:58:00.840833Z","iopub.status.idle":"2024-05-15T17:58:00.881023Z","shell.execute_reply.started":"2024-05-15T17:58:00.840808Z","shell.execute_reply":"2024-05-15T17:58:00.880170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"histories.append(history)\nimport matplotlib.pyplot as plt\n\n# Plot training & validation accuracy values\nplt.plot(histories[0].history['accuracy'])\nplt.title('Model accuracy and loss')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Accuracy'], loc='upper left')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:58:00.882069Z","iopub.execute_input":"2024-05-15T17:58:00.882339Z","iopub.status.idle":"2024-05-15T17:58:01.089827Z","shell.execute_reply.started":"2024-05-15T17:58:00.882316Z","shell.execute_reply":"2024-05-15T17:58:01.088872Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Model 2","metadata":{}},{"cell_type":"code","source":"config = configurations[1]\n\nmodel = VGG16(input_shape = (image_size, image_size, image_channel), # No pre-trained weights\n              block2_layers=config['block2_layers'], block2_neurons=config['block2_neurons'],\n              block3_layers=config['block3_layers'], block3_neurons=config['block3_neurons'],\n              block4_layers=config['block4_layers'], block4_neurons=config['block4_neurons'])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\nlearning_rate_reduction = ReduceLROnPlateau(monitor = 'val_accuracy',\n                                        patience=2,\n                                        factor=0.5,\n                                        min_lr = 0.00001,\n                                        verbose = 1)\n# Train the model\nhistory = model.fit(train_generator, validation_data = val_generator, callbacks = [learning_rate_reduction], epochs = 5\n)\n\n# Evaluate the model on validation set\nloss, accuracy = model.evaluate(val_generator, steps=val_generator.samples // bat_size)\nprint(f\"Configuration: {config}, Validation Accuracy: {accuracy}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T17:58:01.091029Z","iopub.execute_input":"2024-05-15T17:58:01.091351Z","iopub.status.idle":"2024-05-15T18:01:07.559229Z","shell.execute_reply.started":"2024-05-15T17:58:01.091324Z","shell.execute_reply":"2024-05-15T18:01:07.558288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T18:01:07.560461Z","iopub.execute_input":"2024-05-15T18:01:07.560913Z","iopub.status.idle":"2024-05-15T18:01:07.598404Z","shell.execute_reply.started":"2024-05-15T18:01:07.560878Z","shell.execute_reply":"2024-05-15T18:01:07.597486Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"histories.append(history)\nimport matplotlib.pyplot as plt\n\n# Plot training & validation accuracy values\nplt.plot(histories[1].history['accuracy'])\nplt.title('Model accuracy and loss')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Accuracy'], loc='upper left')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T18:01:07.599411Z","iopub.execute_input":"2024-05-15T18:01:07.599687Z","iopub.status.idle":"2024-05-15T18:01:07.817634Z","shell.execute_reply.started":"2024-05-15T18:01:07.599647Z","shell.execute_reply":"2024-05-15T18:01:07.816702Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Model 3","metadata":{}},{"cell_type":"code","source":"config = configurations[2]\n\nmodel = VGG16(input_shape = (image_size, image_size, image_channel), # No pre-trained weights\n              block2_layers=config['block2_layers'], block2_neurons=config['block2_neurons'],\n              block3_layers=config['block3_layers'], block3_neurons=config['block3_neurons'],\n              block4_layers=config['block4_layers'], block4_neurons=config['block4_neurons'])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\nlearning_rate_reduction = ReduceLROnPlateau(monitor = 'val_accuracy',\n                                        patience=2,\n                                        factor=0.5,\n                                        min_lr = 0.00001,\n                                        verbose = 1)\n# Train the model\nhistory = model.fit(train_generator, validation_data = val_generator, callbacks = [learning_rate_reduction], epochs = 5\n)\n\n# Evaluate the model on validation set\nloss, accuracy = model.evaluate(val_generator, steps=val_generator.samples // bat_size)\nprint(f\"Configuration: {config}, Validation Accuracy: {accuracy}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T18:01:07.818856Z","iopub.execute_input":"2024-05-15T18:01:07.819121Z","iopub.status.idle":"2024-05-15T18:06:04.350819Z","shell.execute_reply.started":"2024-05-15T18:01:07.819097Z","shell.execute_reply":"2024-05-15T18:06:04.349817Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T18:06:04.352178Z","iopub.execute_input":"2024-05-15T18:06:04.352845Z","iopub.status.idle":"2024-05-15T18:06:04.394535Z","shell.execute_reply.started":"2024-05-15T18:06:04.352806Z","shell.execute_reply":"2024-05-15T18:06:04.393716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"histories.append(history)\nimport matplotlib.pyplot as plt\n\n# Plot training & validation accuracy values\nplt.plot(histories[2].history['accuracy'])\nplt.title('Model accuracy and loss')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Accuracy'], loc='upper left')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T18:06:04.395731Z","iopub.execute_input":"2024-05-15T18:06:04.396078Z","iopub.status.idle":"2024-05-15T18:06:04.626878Z","shell.execute_reply.started":"2024-05-15T18:06:04.396045Z","shell.execute_reply":"2024-05-15T18:06:04.625986Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Model 4","metadata":{}},{"cell_type":"code","source":"config = configurations[3]\n\nmodel = VGG16(input_shape = (image_size, image_size, image_channel), # No pre-trained weights\n              block2_layers=config['block2_layers'], block2_neurons=config['block2_neurons'],\n              block3_layers=config['block3_layers'], block3_neurons=config['block3_neurons'],\n              block4_layers=config['block4_layers'], block4_neurons=config['block4_neurons'])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\nlearning_rate_reduction = ReduceLROnPlateau(monitor = 'val_accuracy',\n                                        patience=2,\n                                        factor=0.5,\n                                        min_lr = 0.00001,\n                                        verbose = 1)\n# Train the model\nhistory = model.fit(train_generator, validation_data = val_generator, callbacks = [learning_rate_reduction], epochs = 5\n)\n\n# Evaluate the model on validation set\nloss, accuracy = model.evaluate(val_generator, steps=val_generator.samples // bat_size)\nprint(f\"Configuration: {config}, Validation Accuracy: {accuracy}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T18:06:04.627991Z","iopub.execute_input":"2024-05-15T18:06:04.628266Z","iopub.status.idle":"2024-05-15T18:11:05.413487Z","shell.execute_reply.started":"2024-05-15T18:06:04.628241Z","shell.execute_reply":"2024-05-15T18:11:05.412570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T18:11:05.414596Z","iopub.execute_input":"2024-05-15T18:11:05.414921Z","iopub.status.idle":"2024-05-15T18:11:05.455010Z","shell.execute_reply.started":"2024-05-15T18:11:05.414894Z","shell.execute_reply":"2024-05-15T18:11:05.454185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"histories.append(history)\nimport matplotlib.pyplot as plt\n\n# Plot training & validation accuracy values\nplt.plot(histories[3].history['accuracy'])\nplt.title('Model accuracy and loss')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Accuracy'], loc='upper left')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T18:11:05.456054Z","iopub.execute_input":"2024-05-15T18:11:05.456325Z","iopub.status.idle":"2024-05-15T18:11:05.700249Z","shell.execute_reply.started":"2024-05-15T18:11:05.456301Z","shell.execute_reply":"2024-05-15T18:11:05.699337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Model 5","metadata":{}},{"cell_type":"code","source":"config = configurations[4]\n\nmodel = VGG16(input_shape = (image_size, image_size, image_channel), # No pre-trained weights\n              block2_layers=config['block2_layers'], block2_neurons=config['block2_neurons'],\n              block3_layers=config['block3_layers'], block3_neurons=config['block3_neurons'],\n              block4_layers=config['block4_layers'], block4_neurons=config['block4_neurons'])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\nlearning_rate_reduction = ReduceLROnPlateau(monitor = 'val_accuracy',\n                                        patience=2,\n                                        factor=0.5,\n                                        min_lr = 0.00001,\n                                        verbose = 1)\n# Train the model\nhistory = model.fit(train_generator, validation_data = val_generator, callbacks = [learning_rate_reduction], epochs = 5\n)\n\n# Evaluate the model on validation set\nloss, accuracy = model.evaluate(val_generator, steps=val_generator.samples // bat_size)\nprint(f\"Configuration: {config}, Validation Accuracy: {accuracy}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T18:11:05.701433Z","iopub.execute_input":"2024-05-15T18:11:05.701755Z","iopub.status.idle":"2024-05-15T18:14:34.119209Z","shell.execute_reply.started":"2024-05-15T18:11:05.701729Z","shell.execute_reply":"2024-05-15T18:14:34.118320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-15T18:14:34.120347Z","iopub.execute_input":"2024-05-15T18:14:34.120686Z","iopub.status.idle":"2024-05-15T18:14:34.164643Z","shell.execute_reply.started":"2024-05-15T18:14:34.120629Z","shell.execute_reply":"2024-05-15T18:14:34.163777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"histories.append(history)\nimport matplotlib.pyplot as plt\n\n# Plot training & validation accuracy values\nplt.plot(histories[4].history['accuracy'])\nplt.title('Model accuracy and loss')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Accuracy'], loc='upper left')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T18:14:34.166028Z","iopub.execute_input":"2024-05-15T18:14:34.166293Z","iopub.status.idle":"2024-05-15T18:14:34.416338Z","shell.execute_reply.started":"2024-05-15T18:14:34.166269Z","shell.execute_reply":"2024-05-15T18:14:34.415338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Comparison of all 5 models","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Plot training & validation accuracy values for all models\nplt.plot(histories[0].history['accuracy'])\nplt.plot(histories[1].history['accuracy'])\nplt.plot(histories[2].history['accuracy'])\nplt.plot(histories[3].history['accuracy'])\nplt.plot(histories[4].history['accuracy'])\n\n# Add legend with model names\nplt.legend(['Model 1', 'Model 2', 'Model 3', 'Model 4', 'Model 5'], loc='upper left')\n\n# Add title and labels\nplt.title('Model Accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\n\n# Show plot\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-15T18:14:34.417720Z","iopub.execute_input":"2024-05-15T18:14:34.418434Z","iopub.status.idle":"2024-05-15T18:14:34.696586Z","shell.execute_reply.started":"2024-05-15T18:14:34.418398Z","shell.execute_reply":"2024-05-15T18:14:34.695665Z"},"trusted":true},"execution_count":null,"outputs":[]}]}