{"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":"code","source":"import numpy as np \nimport pandas as pd \nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-16T10:19:58.466375Z","iopub.execute_input":"2024-05-16T10:19:58.466757Z","iopub.status.idle":"2024-05-16T10:19:58.473392Z","shell.execute_reply.started":"2024-05-16T10:19:58.466728Z","shell.execute_reply":"2024-05-16T10:19:58.472535Z"},"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\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-16T10:19:58.673710Z","iopub.execute_input":"2024-05-16T10:19:58.674045Z","iopub.status.idle":"2024-05-16T10:20:09.815628Z","shell.execute_reply.started":"2024-05-16T10:19:58.674018Z","shell.execute_reply":"2024-05-16T10:20:09.814588Z"},"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-16T10:20:09.817527Z","iopub.execute_input":"2024-05-16T10:20:09.817810Z","iopub.status.idle":"2024-05-16T10:20:09.863880Z","shell.execute_reply.started":"2024-05-16T10:20:09.817787Z","shell.execute_reply":"2024-05-16T10:20:09.862955Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nfrom sklearn.model_selection import train_test_split\n\ntrain_df, val_df = train_test_split(data, test_size=0.2, stratify=data[\"label\"], random_state=42)\n\n# Create ImageDataGenerators\ntrain_datagen = ImageDataGenerator(rescale=1./255, horizontal_flip=True, rotation_range=20, zoom_range=0.15)\nval_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_dataframe(train_df, directory=image_dir, x_col='filename', y_col='label', target_size=(150, 150), class_mode='binary', batch_size=32)\nval_generator = val_datagen.flow_from_dataframe(val_df, directory=image_dir, x_col='filename', y_col='label', target_size=(150, 150), class_mode='binary', batch_size=32)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-16T10:22:41.978243Z","iopub.execute_input":"2024-05-16T10:22:41.978963Z","iopub.status.idle":"2024-05-16T10:22:53.585053Z","shell.execute_reply.started":"2024-05-16T10:22:41.978933Z","shell.execute_reply":"2024-05-16T10:22:53.584264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_modified_vgg16(num_layers_block2, num_layers_block3, num_layers_block4, num_neurons_block2, num_neurons_block3, num_neurons_block4):\n    input_tensor = Input(shape=(150, 150, 3))\n    base_model = VGG16(include_top=False, weights='imagenet', input_tensor=input_tensor)\n    \n    # Modify the number of layers and neurons\n    x = base_model.get_layer('block1_pool').output\n    \n    # Block 2\n    for i in range(num_layers_block2):\n        x = Conv2D(num_neurons_block2, (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(num_layers_block3):\n        x = Conv2D(num_neurons_block3, (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(num_layers_block4):\n        x = Conv2D(num_neurons_block4, (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    x = base_model.get_layer('block5_pool').output\n    \n    x = Flatten(name='flatten')(x)\n    x = Dense(256, activation='relu', name='fc1')(x)\n    x = Dense(1, activation='sigmoid', name='predictions')(x)\n    \n    model = Model(inputs=base_model.input, outputs=x)\n    \n    for layer in base_model.layers:\n        layer.trainable = False\n    \n    return model\n","metadata":{"execution":{"iopub.status.busy":"2024-05-16T10:23:41.510809Z","iopub.execute_input":"2024-05-16T10:23:41.511174Z","iopub.status.idle":"2024-05-16T10:23:41.523117Z","shell.execute_reply.started":"2024-05-16T10:23:41.511146Z","shell.execute_reply":"2024-05-16T10:23:41.522207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.layers import Input\nfrom tensorflow.keras.optimizers import Adam\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.applications import VGG16\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense\nfrom tensorflow.keras.models import Model\ndef train_and_evaluate_model(model, train_generator, val_generator, epochs=3):\n    model.compile(optimizer=Adam(), loss='binary_crossentropy', metrics=['accuracy'])\n    \n    history = model.fit(train_generator, validation_data=val_generator, epochs=epochs, verbose=1)\n    \n    return history\n\ntrain_path = \"../input/dogs-vs-cats/train.zip\"\ntest_path = \"../input/dogs-vs-cats/test1.zip\"\nfiles = \"/kaggle/working/\"\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)\n\nimage_dir = \"/kaggle/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\ntrain_df, val_df = train_test_split(data, test_size=0.2, stratify=data[\"label\"], random_state=42)\n\ntrain_datagen = ImageDataGenerator(rescale=1./255, horizontal_flip=True, rotation_range=20, zoom_range=0.15)\nval_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_dataframe(train_df, directory=image_dir, x_col='filename', y_col='label', target_size=(150, 150), class_mode='binary', batch_size=32)\nval_generator = val_datagen.flow_from_dataframe(val_df, directory=image_dir, x_col='filename', y_col='label', target_size=(150, 150), class_mode='binary', batch_size=32)\n\nexperiments = [\n    (2, 3, 3, 64, 128, 256),\n    (1, 2, 2, 32, 64, 128),\n    (3, 4, 4, 128, 256, 512),\n    (4,5,5,256,512,1024),\n    (5,6,6,512,1024,2048)\n    # Add more configurations as needed\n]\n\nhistories = []\n\nfor exp in experiments:\n    model = create_modified_vgg16(*exp)\n    history = train_and_evaluate_model(model, train_generator, val_generator)\n    histories.append(history)\n\n# Plotting the results\nplt.figure(figsize=(14, 7))\n\nfor i, history in enumerate(histories):\n    plt.plot(history.history['val_accuracy'], label=f'Experiment {i+1}')\n\nplt.title('Validation Accuracy Comparison')\nplt.xlabel('Epochs')\nplt.ylabel('Validation Accuracy')\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-16T10:31:03.117120Z","iopub.execute_input":"2024-05-16T10:31:03.117491Z","iopub.status.idle":"2024-05-16T11:01:53.041051Z","shell.execute_reply.started":"2024-05-16T10:31:03.117438Z","shell.execute_reply":"2024-05-16T11:01:53.039685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Define the accuracies for all 5 models\naccuracies_model1 = [0.8235, 0.8773, 0.8124]\naccuracies_model2 = [0.8774, 0.8882, 0.8152]\naccuracies_model3 = [0.8768, 0.8873, 0.8174]\naccuracies_model4 = [0.8727, 0.8848, 0.8139]\naccuracies_model5 = [0.8905, 0.8662, 0.9042]\n\n# Extract the accuracy of each model from the last epoch\nlast_epoch_accuracies = [\n    accuracies_model1[-1],\n    accuracies_model2[-1],\n    accuracies_model3[-1],\n    accuracies_model4[-1],\n    accuracies_model5[-1]\n]\n\n# Plotting\nplt.figure(figsize=(10, 6))\nmodels = ['Model 1', 'Model 2', 'Model 3', 'Model 4', 'Model 5']\nplt.bar(models, last_epoch_accuracies, color=['blue', 'green', 'orange', 'red', 'purple'])\nplt.xlabel('Models')\nplt.ylabel('Accuracy')\nplt.title('Accuracy of Models (Last Epoch)')\nplt.ylim(0.8, 0.92)  # Adjust y-axis limits if needed\nplt.grid(axis='y', linestyle='--', alpha=0.7)\nplt.show()\n\n","metadata":{"execution":{"iopub.status.busy":"2024-05-16T11:26:12.071107Z","iopub.execute_input":"2024-05-16T11:26:12.071738Z","iopub.status.idle":"2024-05-16T11:26:12.373498Z","shell.execute_reply.started":"2024-05-16T11:26:12.071704Z","shell.execute_reply":"2024-05-16T11:26:12.372585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Define the epochs\nepochs = [1, 2, 3]\n\n# Define the accuracies for all 5 models\naccuracies_model1 = [0.8235, 0.8773, 0.8124]\naccuracies_model2 = [0.8774, 0.8882, 0.8152]\naccuracies_model3 = [0.8768, 0.8873, 0.8174]\naccuracies_model4 = [0.8727, 0.8848, 0.8139]\naccuracies_model5 = [0.8905, 0.8662, 0.9042]\n\n# Plot accuracies for all 5 models\nplt.plot(epochs, accuracies_model1, label='Model 1')\nplt.plot(epochs, accuracies_model2, label='Model 2')\nplt.plot(epochs, accuracies_model3, label='Model 3')\nplt.plot(epochs, accuracies_model4, label='Model 4')\nplt.plot(epochs, accuracies_model5, label='Model 5')\n\n# Add labels and title\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.title('Accuracy of Models over Epochs')\nplt.xticks(epochs)\nplt.legend()\n\n# Show the plot\nplt.grid(True)\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-16T11:27:23.226325Z","iopub.execute_input":"2024-05-16T11:27:23.227195Z","iopub.status.idle":"2024-05-16T11:27:23.529954Z","shell.execute_reply.started":"2024-05-16T11:27:23.227162Z","shell.execute_reply":"2024-05-16T11:27:23.529093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}