{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"},{"sourceId":122519208,"sourceType":"kernelVersion"}],"dockerImageVersionId":30840,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"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","trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:28:08.975832Z","iopub.execute_input":"2025-02-17T06:28:08.976192Z","iopub.status.idle":"2025-02-17T06:28:08.995867Z","shell.execute_reply.started":"2025-02-17T06:28:08.976151Z","shell.execute_reply":"2025-02-17T06:28:08.995110Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:28:08.996837Z","iopub.execute_input":"2025-02-17T06:28:08.997076Z","iopub.status.idle":"2025-02-17T06:28:22.542822Z","shell.execute_reply.started":"2025-02-17T06:28:08.997057Z","shell.execute_reply":"2025-02-17T06:28:22.542182Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'dog.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:28:22.544226Z","iopub.execute_input":"2025-02-17T06:28:22.544516Z","iopub.status.idle":"2025-02-17T06:28:23.461697Z","shell.execute_reply.started":"2025-02-17T06:28:22.544494Z","shell.execute_reply":"2025-02-17T06:28:23.460830Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport shutil\nimport zipfile\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n\n\n# Fix: Correct dataset path\noriginal_dataset_dir = './train/'\n\n# Create directories\nbase_dir = '/kaggle/working/dogs-vs-cats'\nos.makedirs(base_dir, exist_ok=True)\n\ntrain_dir = os.path.join(base_dir, 'train')\nvalidation_dir = os.path.join(base_dir, 'validation')\ntest_dir = os.path.join(base_dir, 'test')\n\nfor directory in [train_dir, validation_dir, test_dir]:\n    os.makedirs(directory, exist_ok=True)\n\ntrain_cats_dir = os.path.join(train_dir, 'cats')\ntrain_dogs_dir = os.path.join(train_dir, 'dogs')\nvalidation_cats_dir = os.path.join(validation_dir, 'cats')\nvalidation_dogs_dir = os.path.join(validation_dir, 'dogs')\ntest_cats_dir = os.path.join(test_dir, 'cats')\ntest_dogs_dir = os.path.join(test_dir, 'dogs')\n\nfor directory in [train_cats_dir, train_dogs_dir, validation_cats_dir, validation_dogs_dir, test_cats_dir, test_dogs_dir]:\n    os.makedirs(directory, exist_ok=True)\n\n# Function to copy images safely\ndef copy_images(file_list, src_folder, dest_folder):\n    for fname in file_list:\n        src = os.path.join(src_folder, fname)\n        dst = os.path.join(dest_folder, fname)\n        if os.path.exists(src):  # Fix: Avoid file not found errors\n            shutil.copyfile(src, dst)\n\n# Splitting dataset\ncopy_images(['cat.{}.jpg'.format(i) for i in range(1000)], original_dataset_dir, train_cats_dir)\ncopy_images(['cat.{}.jpg'.format(i) for i in range(1000, 1500)], original_dataset_dir, validation_cats_dir)\ncopy_images(['cat.{}.jpg'.format(i) for i in range(1500, 2000)], original_dataset_dir, test_cats_dir)\n\ncopy_images(['dog.{}.jpg'.format(i) for i in range(1000)], original_dataset_dir, train_dogs_dir)\ncopy_images(['dog.{}.jpg'.format(i) for i in range(1000, 1500)], original_dataset_dir, validation_dogs_dir)\ncopy_images(['dog.{}.jpg'.format(i) for i in range(1500, 2000)], original_dataset_dir, test_dogs_dir)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:28:23.463099Z","iopub.execute_input":"2025-02-17T06:28:23.463397Z","iopub.status.idle":"2025-02-17T06:28:23.857707Z","shell.execute_reply.started":"2025-02-17T06:28:23.463370Z","shell.execute_reply":"2025-02-17T06:28:23.857055Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Sanity check: Counting images in each dataset split\nprint('Total training cat images:', len(os.listdir(train_cats_dir)))\nprint('Total training dog images:', len(os.listdir(train_dogs_dir)))\nprint('Total validation cat images:', len(os.listdir(validation_cats_dir)))\nprint('Total validation dog images:', len(os.listdir(validation_dogs_dir)))\nprint('Total test cat images:', len(os.listdir(test_cats_dir)))\nprint('Total test dog images:', len(os.listdir(test_dogs_dir)))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:28:23.858559Z","iopub.execute_input":"2025-02-17T06:28:23.858772Z","iopub.status.idle":"2025-02-17T06:28:23.867837Z","shell.execute_reply.started":"2025-02-17T06:28:23.858754Z","shell.execute_reply":"2025-02-17T06:28:23.867136Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras import layers, models, optimizers\n\n# Define the CNN model\nmodel = models.Sequential()\n\n# First Conv-Pool Layer\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# Second Conv-Pool Layer\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# Third Conv-Pool Layer\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# Fourth Conv-Pool Layer\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# Flattening & Fully Connected Layers\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(512, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))  # Output layer for binary classification\n\n# Compile the model\nmodel.compile(\n    loss='binary_crossentropy',\n    optimizer=optimizers.RMSprop(learning_rate=1e-4),  # Updated API\n    metrics=['accuracy']\n)\n\n# Print model summary\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:28:23.868671Z","iopub.execute_input":"2025-02-17T06:28:23.868963Z","iopub.status.idle":"2025-02-17T06:28:26.210115Z","shell.execute_reply.started":"2025-02-17T06:28:23.868935Z","shell.execute_reply":"2025-02-17T06:28:26.209419Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Data Augmentation for Training (Rescaling only)\ntrain_datagen = ImageDataGenerator(rescale=1.0/255)\n\n# Rescaling Validation Data\nvalidation_datagen = ImageDataGenerator(rescale=1.0/255)\n\n# Training Data Generator\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,               # Directory path for training images\n    target_size=(150, 150),  # Resize images to match CNN input\n    batch_size=20,           # Batch size\n    class_mode='binary'      # Binary classification (Cats vs. Dogs)\n)\n\n# Validation Data Generator\nvalidation_generator = validation_datagen.flow_from_directory(\n    validation_dir,          # Directory path for validation images\n    target_size=(150, 150),  # Resize images\n    batch_size=20,           # Batch size\n    class_mode='binary'      # Binary classification\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:28:26.210894Z","iopub.execute_input":"2025-02-17T06:28:26.211227Z","iopub.status.idle":"2025-02-17T06:28:26.319841Z","shell.execute_reply.started":"2025-02-17T06:28:26.211194Z","shell.execute_reply":"2025-02-17T06:28:26.319258Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(\n    train_generator,          # Training Data Generator\n    steps_per_epoch=100,      # Number of batches per epoch\n    epochs=30,                # Total epochs\n    validation_data=validation_generator,  # Validation Data Generator\n    validation_steps=50       # Number of batches per validation step\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:28:26.322437Z","iopub.execute_input":"2025-02-17T06:28:26.322638Z","iopub.status.idle":"2025-02-17T06:29:36.799864Z","shell.execute_reply.started":"2025-02-17T06:28:26.322621Z","shell.execute_reply":"2025-02-17T06:29:36.799216Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('cats_and_dogs_small_1.h5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:29:36.801386Z","iopub.execute_input":"2025-02-17T06:29:36.801631Z","iopub.status.idle":"2025-02-17T06:29:36.888770Z","shell.execute_reply.started":"2025-02-17T06:29:36.801610Z","shell.execute_reply":"2025-02-17T06:29:36.888086Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Extract training history\nacc = history.history['accuracy']  # ✅ Corrected key\nval_acc = history.history['val_accuracy']  # ✅ Corrected key\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\n# Find the correct number of epochs to avoid mismatch\nnum_epochs = min(len(acc), len(val_acc))  # ✅ Use the shorter length\nepochs = range(1, num_epochs + 1)\n\n# Plot Training & Validation Accuracy\nplt.figure(figsize=(10, 5))\nplt.plot(epochs, acc[:num_epochs], 'bo', label='Training Accuracy')  # ✅ No mismatch\nplt.plot(epochs, val_acc[:num_epochs], 'b', label='Validation Accuracy')  # ✅ No mismatch\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.grid(True)\n\n# Plot Training & Validation Loss\nplt.figure(figsize=(10, 5))\nplt.plot(epochs, loss[:num_epochs], 'bo', label='Training Loss')  # ✅ No mismatch\nplt.plot(epochs, val_loss[:num_epochs], 'b', label='Validation Loss')  # ✅ No mismatch\nplt.title('Training and Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.grid(True)\n\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:29:36.889570Z","iopub.execute_input":"2025-02-17T06:29:36.889852Z","iopub.status.idle":"2025-02-17T06:29:37.293448Z","shell.execute_reply.started":"2025-02-17T06:29:36.889827Z","shell.execute_reply":"2025-02-17T06:29:37.292613Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen = ImageDataGenerator(\n    rotation_range=40,              # Random rotation between -40 and +40 degrees\n    width_shift_range=0.2,          # Random horizontal shift\n    height_shift_range=0.2,         # Random vertical shift\n    shear_range=0.2,                # Random shear\n    zoom_range=0.2,                 # Random zoom\n    horizontal_flip=True,           # Randomly flip images horizontally\n    fill_mode='nearest'             # Use nearest pixel value for filling empty pixels\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:29:37.294374Z","iopub.execute_input":"2025-02-17T06:29:37.294697Z","iopub.status.idle":"2025-02-17T06:29:37.298572Z","shell.execute_reply.started":"2025-02-17T06:29:37.294665Z","shell.execute_reply":"2025-02-17T06:29:37.297758Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Assuming 'train_cats_dir' is defined and contains the images\nfnames = [os.path.join(train_cats_dir, fname) for fname in os.listdir(train_cats_dir)]\nimg_path = fnames[3]  # Get a specific image file path (3rd image in the directory)\n\n# Load the image and resize it to (150, 150)\nimg = image.load_img(img_path, target_size=(150, 150))\n\n# Convert image to array\nx = image.img_to_array(img)\n\n# Reshape image to add a batch dimension\nx = x.reshape((1,) + x.shape)\n\n# Define the data generator for augmentation\ndatagen = ImageDataGenerator(\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    fill_mode='nearest'\n)\n\n# Create augmented images and display them\ni = 0\nfor batch in datagen.flow(x, batch_size=1):\n    # Plot the augmented image\n    plt.figure(i)\n    imgplot = plt.imshow(image.array_to_img(batch[0]))  # Convert array back to image and display\n    i += 1\n    \n    # Stop after generating and displaying 4 augmented images\n    if i % 4 == 0:\n        break\n\n# Show the generated images\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:29:37.299361Z","iopub.execute_input":"2025-02-17T06:29:37.299576Z","iopub.status.idle":"2025-02-17T06:29:38.362780Z","shell.execute_reply.started":"2025-02-17T06:29:37.299546Z","shell.execute_reply":"2025-02-17T06:29:38.362024Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras import models, layers, optimizers\n\n# Define the model architecture\nmodel = models.Sequential()\n\n# Add the first convolutional layer\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# Add the second convolutional layer\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# Add the third convolutional layer\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# Add the fourth convolutional layer\nmodel.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\n\n# Flatten the 3D feature maps to 1D vector\nmodel.add(layers.Flatten())\n\n# Add dropout layer to avoid overfitting\nmodel.add(layers.Dropout(0.5))\n\n# Add a fully connected layer\nmodel.add(layers.Dense(512, activation='relu'))\n\n# Output layer with sigmoid activation for binary classification\nmodel.add(layers.Dense(1, activation='sigmoid'))\n\n# Compile the model with binary crossentropy loss and RMSprop optimizer\nmodel.compile(\n    loss='binary_crossentropy',\n    optimizer=optimizers.RMSprop(learning_rate=1e-4),  # Updated syntax for learning rate\n    metrics=['accuracy']  # Use 'accuracy' instead of 'acc'\n)\n\n# Model summary to check architecture\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:29:38.363844Z","iopub.execute_input":"2025-02-17T06:29:38.364500Z","iopub.status.idle":"2025-02-17T06:29:38.484457Z","shell.execute_reply.started":"2025-02-17T06:29:38.364469Z","shell.execute_reply":"2025-02-17T06:29:38.483800Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# from keras.preprocessing.image import ImageDataGenerator\n\n# Data augmentation for training images\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,  # Normalize pixel values to [0, 1]\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)\n\n# Data preprocessing for validation images (only rescaling)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n# Training data generator\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,  # Directory where training images are located\n    target_size=(150, 150),  # Resize images to 150x150\n    batch_size=32,  # Number of images per batch\n    class_mode='binary',  # Binary classification (cats vs dogs)\n)\n\n# Validation data generator\nvalidation_generator = test_datagen.flow_from_directory(\n    validation_dir,  # Directory where validation images are located\n    target_size=(150, 150),  # Resize images to 150x150\n    batch_size=32,  # Number of images per batch\n    class_mode='binary',  # Binary classification (cats vs dogs)\n)\n\n# Training the model\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch=100,  # Number of batches per epoch\n    epochs=100,  # Number of epochs to train\n    validation_data=validation_generator,\n    validation_steps=50,  # Number of validation batches per epoch\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-17T06:29:38.485135Z","iopub.execute_input":"2025-02-17T06:29:38.485338Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('cats_and_dogs_small_1.h5')","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Assuming 'history' is the variable storing your model's training history\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(acc) + 1)\n\n# Plotting training and validation accuracy\nplt.plot(epochs, acc, 'bo', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\n\n# Plotting training and validation loss\nplt.figure()\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\n# Display the plots\nplt.show()\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":" from keras.applications import VGG16\n conv_base = VGG16(weights='imagenet',\n include_top=False,\n input_shape=(150, 150, 3))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import VGG16\n\n# Define base directory paths for datasets\nbase_dir = '/kaggle/working/dogs-vs-cats'\ntrain_dir = os.path.join(base_dir, 'train')\nvalidation_dir = os.path.join(base_dir, 'validation')\ntest_dir = os.path.join(base_dir, 'test')\n\n# Load the pre-trained VGG16 model, excluding the top classification layers\nconv_base = VGG16(weights='imagenet', include_top=False, input_shape=(150, 150, 3))\n\n# Define the ImageDataGenerator for rescaling images\ndatagen = ImageDataGenerator(rescale=1./255)\nbatch_size = 20\n\ndef extract_features(directory, sample_count):\n    features = np.zeros(shape=(sample_count, 4, 4, 512))\n    labels = np.zeros(shape=(sample_count))\n    generator = datagen.flow_from_directory(\n        directory,\n        target_size=(150, 150),\n        batch_size=batch_size,\n        class_mode='binary'\n    )\n    i = 0\n    for inputs_batch, labels_batch in generator:\n        features_batch = conv_base.predict(inputs_batch)\n        features[i * batch_size : (i + 1) * batch_size] = features_batch\n        labels[i * batch_size : (i + 1) * batch_size] = labels_batch\n        i += 1\n        if i * batch_size >= sample_count:\n            break\n    return features, labels\n\n# Extract features and labels for training, validation, and test datasets\ntrain_features, train_labels = extract_features(train_dir, 2000)\nvalidation_features, validation_labels = extract_features(validation_dir, 1000)\ntest_features, test_labels = extract_features(test_dir, 1000)\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import models\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import optimizers\n\n# Define the model\nmodel = models.Sequential()\nmodel.add(layers.Flatten(input_shape=(4, 4, 512)))  # Flatten the input\nmodel.add(layers.Dense(256, activation='relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(1, activation='sigmoid'))\n\n# Compile the model\nmodel.compile(optimizer=optimizers.RMSprop(learning_rate=2e-5),\n              loss='binary_crossentropy',\n              metrics=['accuracy'])\n\n# Train the model\nhistory = model.fit(train_features, train_labels,\n                    epochs=30,\n                    batch_size=20,\n                    validation_data=(validation_features, validation_labels))\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Assuming 'history' is the variable storing your model's training history\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(acc) + 1)\n\n# Plotting training and validation accuracy\nplt.plot(epochs, acc, 'bo', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\n\n# Plotting training and validation loss\nplt.figure()\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\n# Display the plots\nplt.show()\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras import models\nfrom keras import layers\nmodel = models.Sequential()\nmodel.add(conv_base)\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(256, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":" model.summary()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import optimizers\n\n# Define the ImageDataGenerator for training and validation datasets\ntrain_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    fill_mode='nearest'\n)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n# Set up the data generators\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=(150, 150),\n    batch_size=20,\n    class_mode='binary'\n)\nvalidation_generator = test_datagen.flow_from_directory(\n    validation_dir,\n    target_size=(150, 150),\n    batch_size=20,\n    class_mode='binary'\n)\n\n# Compile the model\nmodel.compile(loss='binary_crossentropy',\n              optimizer=optimizers.RMSprop(learning_rate=2e-5),\n              metrics=['accuracy'])\n\n# Train the model\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch=100,\n    epochs=30,\n    validation_data=validation_generator,\n    validation_steps=50\n)\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(len(acc), len(val_acc), len(loss), len(val_loss))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Ensure epochs array matches the shortest metric array\nepochs = range(1, min(len(acc), len(val_acc)) + 1)\n\n# Plotting training and validation accuracy\nplt.figure(figsize=(12, 4))\nplt.subplot(1, 2, 1)\nplt.plot(epochs, acc[:len(epochs)], 'bo', label='Training accuracy')  # Truncate acc\nplt.plot(epochs, val_acc[:len(epochs)], 'b', label='Validation accuracy')  # Truncate val_acc\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\n\n# Plotting training and validation loss\nplt.subplot(1, 2, 2)\nplt.plot(epochs, loss[:len(epochs)], 'ro', label='Training loss')  # Truncate loss\nplt.plot(epochs, val_loss[:len(epochs)], 'r', label='Validation loss')  # Truncate val_loss\nplt.title('Training and Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.models import load_model\nmodel = load_model('/kaggle/input/dogs-vs-cats/cats_and_dogs_small_1.h5')\nmodel.summary() ","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}