{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport matplotlib.pyplot as plt\nfrom tensorflow import keras \nfrom keras import layers\nfrom keras import models \nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport warnings\nimport os\nwarnings.filterwarnings(\"ignore\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-11-18T16:26:04.272082Z","iopub.execute_input":"2024-11-18T16:26:04.272393Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(os.listdir(\"/kaggle/input/dogs-vs-cats\"))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import zipfile\nzip_files = ['test1','train']\nfor zip_file in zip_files:\n    with zipfile.ZipFile(f'/kaggle/input/dogs-vs-cats/{zip_file}.zip','r') as file:\n        file.extractall(\".\")\n        print(\"{} unzipped successfully\".format(zip_file))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(os.listdir(\".\"))\ntrain_path=\"./train\"\nfile_names=os.listdir(train_path)\nprint(\"train samples \",len(file_names))\nprint(file_names[:3])","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_path=\"./test1\"\nfile_names=os.listdir(test_path)\nprint(\"test samples \",len(file_names))\nprint(file_names[:3])","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def path_to_frame(files):\n    paths,labels=[],[]\n    path=f\"./{files}\"\n    file_names=os.listdir(path)\n    for name in file_names:\n        paths.append(name)\n        labels.append(name[:3])\n    return pd.DataFrame({\"path\":paths,\"target\":labels})","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df=path_to_frame(\"train\")\ntest_df=path_to_frame(\"test1\")\nprint(\"train shape\",train_df.shape)\nprint(\"test shape\", test_df.shape)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"train: \")\nprint(train_df.head(2))\nprint()\nprint(\"test: \")\nprint(test_df.head(2))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns \n\nsns.countplot(x=train_df[\"target\"],alpha=0.2,color=\"g\")\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ntrain_df,valid_df=train_test_split(train_df,test_size=0.2,stratify=train_df[\"target\"],random_state=42)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fig,ax=plt.subplots(nrows=1,ncols=2,figsize=(10,4))\nsns.countplot(x=train_df[\"target\"],alpha=0.2,color=\"g\",ax=ax[0])\nax[0].set_title(\"Train data\")\nsns.countplot(x=valid_df[\"target\"],alpha=0.2,color=\"g\",ax=ax[1])\nax[1].set_title(\"Validition data\")\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"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    fill_mode=\"nearest\"\n)\ntraining_data = train_datagen.flow_from_dataframe(\n    dataframe=train_df,\n    directory='./train',\n    x_col = 'path',\n    y_col='target',\n    target_size=(150,150),\n    class_mode='binary',\n    batch_size=50) ","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"valid_datagen=ImageDataGenerator(rescale=1/255)\n\nvalidation_data = valid_datagen.flow_from_dataframe(\n    dataframe=valid_df,\n    directory='./train',\n    x_col = 'path',\n    y_col='target',\n    target_size=(150,150),\n    class_mode='binary',\n    batch_size=50) ","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df=test_df.drop(\"target\",axis=1)\ntest_datagen=ImageDataGenerator(rescale=1/255)\n\ntest_data = test_datagen.flow_from_dataframe(\n    dataframe=test_df,\n    directory='./test1',\n    x_col = 'path',\n    y_col=None,\n    target_size=(150,150),\n    class_mode=None,\n    batch_size=50) ","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"counts, idx = 5, 0\nprint(\"Training samples\",end=\"\\n\\n\")\nfig, ax = plt.subplots(1, counts, figsize=(15, 5))\nfor img_batch, _ in training_data:  # Unpack batch to separate images and labels\n    # Display one sample image from the batch\n    ax[idx].imshow(img_batch[0])\n    ax[idx].axis(\"off\") \n    idx += 1\n    if idx == counts:\n        break\n\nplt.show()\n\n\ncounts, idx = 5, 0\nprint(\"Validation samples\",end=\"\\n\\n\")\nfig, ax = plt.subplots(1, counts, figsize=(15, 5))\nfor img_batch, _ in validation_data:  # Unpack batch to separate images and labels\n    # Display one sample image from the batch\n    ax[idx].imshow(img_batch[0])\n    ax[idx].axis(\"off\") \n    idx += 1\n    if idx == counts:\n        break\n\nplt.show()\n\n\ncounts, idx = 5, 0\nprint(\"Test samples\",end=\"\\n\\n\")\nfig, ax = plt.subplots(1, counts, figsize=(15, 5))\nfor img_batch in test_data:  # Unpack batch to separate images and labels\n    # Display one sample image from the batch\n    ax[idx].imshow(img_batch[0])\n    ax[idx].axis(\"off\") \n    idx += 1\n    if idx == counts:\n        break\n\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model=models.Sequential(\n[\n    layers.Conv2D(32,(3,3),input_shape=(150,150,3,),activation=\"relu\"),\n    layers.MaxPooling2D((2,2)),\n    \n    layers.Conv2D(64,(3,3),activation=\"relu\"),\n    layers.MaxPooling2D((2,2)),\n    layers.Dropout((0.5)),\n\n    layers.Conv2D(128,(3,3),activation=\"relu\"),\n    layers.MaxPooling2D((2,2)),\n    \n    layers.Conv2D(128,(3,3),activation=\"relu\"),\n    layers.MaxPooling2D((2,2)),\n    \n    layers.Flatten(),\n    layers.Dropout((0.5)),\n    layers.Dense(512,activation=\"relu\"),\n    layers.Dense(1,activation=\"sigmoid\")\n])\nmodel.summary()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(\n    loss=\"binary_crossentropy\",\n    optimizer=\"adam\",\n    metrics=[\"accuracy\"]\n)\nkeras.utils.plot_model(model,show_layer_activations=True,show_layer_names=True,show_shapes=True,show_dtype=True)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history=model.fit(\n    training_data,\n    steps_per_epoch=train_df.shape[0]//32,\n    epochs=10,\n    validation_data= validation_data, \n    validation_steps= valid_df.shape[0]// 32,\n)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def plot_model_parameters(history):\n    acc=history[\"accuracy\"]\n    val_acc=history[\"val_accuracy\"]\n    loss=history[\"loss\"]\n    val_loss=history[\"val_loss\"]\n    fig, ax = plt.subplots(2, 1, figsize = (8, 10))\n\n    epochs = range(1, len(acc) + 1)\n    ax[0].plot(epochs, acc, '--', label='Training acc')\n    ax[0].plot(epochs, val_acc, label='Validation acc')\n    ax[0].set_title('Training and validation accuracy')\n    ax[0].set_ylim([0.0, 1.0])\n    ax[0].legend()\n\n    ax[1].plot(epochs, loss, '--', label='Training loss')\n    ax[1].plot(epochs, val_loss, label='Validation loss')\n    ax[1].set_title('Training and validation loss')\n    ax[1].legend()\n    \n    plt.show()\n    plot_model_parameters(history.history)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.applications.vgg16 import VGG16\n\nmodel2 = Sequential([\n    VGG16(include_top=False, pooling='max', input_shape=(150, 150, 3), weights='imagenet'),\n    layers.Flatten(),\n    layers.Dense(512, activation='relu'),\n    layers.Dense(512, activation='relu'),\n    layers.BatchNormalization(),\n    layers.Dropout(0.5),\n    layers.Dense(1, activation='sigmoid')\n])\n\n# Freeze the VGG16 model layers to prevent training\nmodel2.layers[0].trainable = False\n\nmodel2.summary()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model2.compile(\n    loss=\"binary_crossentropy\",\n    optimizer=\"adam\",\n    metrics=[\"accuracy\"]\n)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history=model2.fit(\n    training_data,\n    steps_per_epoch=train_df.shape[0]//32,\n    epochs=10,\n    validation_data= validation_data, \n    validation_steps= valid_df.shape[0]// 32,\n)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Function to plot model training parameters\ndef plot_model_parameters(history_dict):\n    plt.figure(figsize=(12, 8))\n    \n    # Plot accuracy\n    plt.subplot(2, 1, 1)\n    plt.plot(history_dict['accuracy'], label='Training Accuracy')\n    plt.plot(history_dict['val_accuracy'], label='Validation Accuracy')\n    plt.title('Model Accuracy')\n    plt.xlabel('Epochs')\n    plt.ylabel('Accuracy')\n    plt.legend()\n    \n    # Plot loss\n    plt.subplot(2, 1, 2)\n    plt.plot(history_dict['loss'], label='Training Loss')\n    plt.plot(history_dict['val_loss'], label='Validation Loss')\n    plt.title('Model Loss')\n    plt.xlabel('Epochs')\n    plt.ylabel('Loss')\n    plt.legend()\n    \n    plt.tight_layout()\n    plt.show()\n\n# Correct usage\nplot_model_parameters(history.history)","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}