{"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":"none","dataSources":[{"sourceId":7703883,"sourceType":"datasetVersion","datasetId":4497421},{"sourceId":12365,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":10048}],"dockerImageVersionId":30646,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, BatchNormalization, Dropout\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport matplotlib.pyplot as plt\nfrom keras.applications import VGG16  # Pre-trained model for image classification\nfrom keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-02-27T08:27:25.032790Z","iopub.execute_input":"2024-02-27T08:27:25.033286Z","iopub.status.idle":"2024-02-27T08:27:42.679650Z","shell.execute_reply.started":"2024-02-27T08:27:25.033238Z","shell.execute_reply":"2024-02-27T08:27:42.678240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TRAIN_DIR = \"/kaggle/input/catvsdog/dataset/train\"\nTEST_DIR = \"/kaggle/input/catvsdog/dataset/test\"\nIMAGE_SIZE = (128, 128)\nBATCH_SIZE = 2\nIMAGE_CHANNELS=3","metadata":{"execution":{"iopub.status.busy":"2024-02-27T08:27:42.681854Z","iopub.execute_input":"2024-02-27T08:27:42.682511Z","iopub.status.idle":"2024-02-27T08:27:42.690262Z","shell.execute_reply.started":"2024-02-27T08:27:42.682482Z","shell.execute_reply":"2024-02-27T08:27:42.687388Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=40,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    validation_split=0.4  # 10% of the data will be used for validation\n\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-27T08:27:42.693991Z","iopub.execute_input":"2024-02-27T08:27:42.695244Z","iopub.status.idle":"2024-02-27T08:27:42.717158Z","shell.execute_reply.started":"2024-02-27T08:27:42.695189Z","shell.execute_reply":"2024-02-27T08:27:42.716150Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=40,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-27T08:27:42.720175Z","iopub.execute_input":"2024-02-27T08:27:42.721643Z","iopub.status.idle":"2024-02-27T08:27:42.731787Z","shell.execute_reply.started":"2024-02-27T08:27:42.721600Z","shell.execute_reply":"2024-02-27T08:27:42.730387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_directory(\n    TRAIN_DIR,\n    target_size=IMAGE_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode='binary',\n    subset=\"training\",  # Subset for training data\n)\n\nvalidation_generator = train_datagen.flow_from_directory(\n    TRAIN_DIR,\n    target_size=IMAGE_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode='binary',\n    subset=\"validation\",  # Subset for validation data\n)\n\ntest_generator = test_datagen.flow_from_directory(\n    TEST_DIR,\n    target_size=IMAGE_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode='binary'\n)\n","metadata":{"execution":{"iopub.status.busy":"2024-02-27T08:27:42.733762Z","iopub.execute_input":"2024-02-27T08:27:42.734504Z","iopub.status.idle":"2024-02-27T08:27:42.797640Z","shell.execute_reply.started":"2024-02-27T08:27:42.734467Z","shell.execute_reply":"2024-02-27T08:27:42.796185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = VGG16(weights=None, include_top=False, input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3))\n\n# Load the weights you downloaded manually\nweights_path = '/kaggle/input/vgg16_weights/tensorflow2/vvg16_wts/1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5'\nbase_model.load_weights(weights_path)","metadata":{"execution":{"iopub.status.busy":"2024-02-27T08:28:13.739409Z","iopub.execute_input":"2024-02-27T08:28:13.739891Z","iopub.status.idle":"2024-02-27T08:28:14.814081Z","shell.execute_reply.started":"2024-02-27T08:28:13.739854Z","shell.execute_reply":"2024-02-27T08:28:14.812823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a custom model on top of the pretrained VGG16 model\nx = Flatten()(base_model.output)  # Flatten the output of the base model\nx = Dense(512, activation='relu')(x)  # Add a fully connected layer with 512 units and ReLU activation\nx = Dropout(0.5)(x)  # Apply dropout regularization to prevent overfitting\npredictions = Dense(1, activation='sigmoid')(x)  # Add a final output layer with sigmoid activation for binary classification\nmodel = Model(inputs=base_model.input, outputs=predictions)  # Define the input and output of the custom model","metadata":{"execution":{"iopub.status.busy":"2024-02-27T08:28:16.765831Z","iopub.execute_input":"2024-02-27T08:28:16.766303Z","iopub.status.idle":"2024-02-27T08:28:16.849610Z","shell.execute_reply.started":"2024-02-27T08:28:16.766267Z","shell.execute_reply":"2024-02-27T08:28:16.847927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compile the model with Adam optimizer, binary crossentropy loss, and accuracy metric\nmodel.compile(optimizer=Adam(learning_rate=0.0001), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-02-27T08:28:18.811071Z","iopub.execute_input":"2024-02-27T08:28:18.811564Z","iopub.status.idle":"2024-02-27T08:28:18.836478Z","shell.execute_reply.started":"2024-02-27T08:28:18.811528Z","shell.execute_reply":"2024-02-27T08:28:18.835266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-27T08:28:20.729386Z","iopub.execute_input":"2024-02-27T08:28:20.730315Z","iopub.status.idle":"2024-02-27T08:28:20.812873Z","shell.execute_reply.started":"2024-02-27T08:28:20.730256Z","shell.execute_reply":"2024-02-27T08:28:20.810350Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train the model with optimized configurations\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch=len(train_generator),\n    validation_data=validation_generator,\n    validation_steps=len(validation_generator),\n    epochs=10\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-27T08:28:22.406972Z","iopub.execute_input":"2024-02-27T08:28:22.407424Z","iopub.status.idle":"2024-02-27T08:30:38.860870Z","shell.execute_reply.started":"2024-02-27T08:28:22.407392Z","shell.execute_reply":"2024-02-27T08:30:38.859256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = plt.subplots(1, 2, figsize=(10, 3))\nax = ax.ravel()\n\nfor i, met in enumerate(['accuracy', 'loss']):\n    ax[i].plot(history.history[met])\n    ax[i].plot(history.history['val_' + met])\n    ax[i].set_title('Model {}'.format(met))\n    ax[i].set_xlabel('epochs')\n    ax[i].set_ylabel(met)\n    ax[i].legend(['train', 'val'])","metadata":{"execution":{"iopub.status.busy":"2024-02-27T08:30:45.253310Z","iopub.execute_input":"2024-02-27T08:30:45.253801Z","iopub.status.idle":"2024-02-27T08:30:45.828537Z","shell.execute_reply.started":"2024-02-27T08:30:45.253760Z","shell.execute_reply":"2024-02-27T08:30:45.827609Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate the model on the test set\ntest_loss, test_accuracy = model.evaluate(test_generator)\n\nprint(\"Test Accuracy:\", test_accuracy)\nprint(\"Test Loss:\", test_loss)","metadata":{"execution":{"iopub.status.busy":"2024-02-27T08:30:49.467334Z","iopub.execute_input":"2024-02-27T08:30:49.467863Z","iopub.status.idle":"2024-02-27T08:30:50.845808Z","shell.execute_reply.started":"2024-02-27T08:30:49.467825Z","shell.execute_reply":"2024-02-27T08:30:50.844524Z"},"trusted":true},"execution_count":null,"outputs":[]}]}