{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30664,"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","execution":{"iopub.status.busy":"2024-03-12T04:20:37.289718Z","iopub.execute_input":"2024-03-12T04:20:37.290061Z","iopub.status.idle":"2024-03-12T04:20:38.264772Z","shell.execute_reply.started":"2024-03-12T04:20:37.290030Z","shell.execute_reply":"2024-03-12T04:20:38.263685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\n\n# Load the dataset\nsampleSubmission = pd.read_csv('/kaggle/input/dogs-vs-cats/sampleSubmission.csv')\n\n# Now you can work with the dataset as usual\nprint(sampleSubmission.head())\n","metadata":{"execution":{"iopub.status.busy":"2024-03-12T07:53:56.877815Z","iopub.execute_input":"2024-03-12T07:53:56.878108Z","iopub.status.idle":"2024-03-12T07:53:57.241164Z","shell.execute_reply.started":"2024-03-12T07:53:56.878081Z","shell.execute_reply":"2024-03-12T07:53:57.240070Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\nimport os\n\n# Path to the zip file\ntest1_zip_path = '/kaggle/input/dogs-vs-cats/test1.zip'\ntrain_zip_path = '/kaggle/input/dogs-vs-cats/train.zip'\n\n# Directory to extract to\nextract_path = '/kaggle/working/'\n\n# Extract the test1_zip_path file\nwith zipfile.ZipFile(test1_zip_path, 'r') as zip_ref1:\n    zip_ref1.extractall(extract_path)\n    \n    \n# Extract the train_zip_path file\nwith zipfile.ZipFile(train_zip_path, 'r') as zip_ref2:\n    zip_ref2.extractall(extract_path)\n\n    \n    \n# List the files in the Test and Trian directory\nTestDir = os.listdir(extract_path+\"test1\")\nTrainDir = os.listdir(extract_path+\"train\")\n\n# # Print the list of files in TestDir\n# for testfile in TestDir:\n#     print(testfile)\n\n# Print the list of files in TrainDir\nfor trainfile in TrainDir:\n    print(trainfile)","metadata":{"execution":{"iopub.status.busy":"2024-03-12T08:41:29.920494Z","iopub.execute_input":"2024-03-12T08:41:29.921060Z","iopub.status.idle":"2024-03-12T08:41:41.031010Z","shell.execute_reply.started":"2024-03-12T08:41:29.921033Z","shell.execute_reply":"2024-03-12T08:41:41.030041Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n# Path to the image file\nimage_path = '/kaggle/working/test1/1334.jpg'\n\n# Load the image\nimg = mpimg.imread(image_path)\n\n# Display the image using a specific image viewer\nplt.imshow(img)\nplt.axis('off')  # Hide axes\nplt.show(block=False)  # Non-blocking show\n\n# Using a custom image viewer, e.g., 'eog' for Linux, 'open' for macOS, 'start' for Windows\nimport os\nos.system('eog {}'.format(image_path))  # Replace 'eog' with your preferred image viewer\n","metadata":{"execution":{"iopub.status.busy":"2024-03-12T08:42:15.837332Z","iopub.execute_input":"2024-03-12T08:42:15.837726Z","iopub.status.idle":"2024-03-12T08:42:16.099315Z","shell.execute_reply.started":"2024-03-12T08:42:15.837696Z","shell.execute_reply":"2024-03-12T08:42:16.098409Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport os\n\n# Define paths to train and test datasets\ntrain_dir = '/kaggle/working/train/'\ntest_dir = '/kaggle/working/test1/'\n\n# Define constants\nimg_width, img_height = 150, 150\nbatch_size = 32\nepochs = 10\n\n# Create the CNN model\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(img_width, img_height, 3)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n\n# Data Augmentation for training images\ntrain_datagen = ImageDataGenerator(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\n# Load training data\ntrain_filenames = [os.path.join(train_dir, fname) for fname in os.listdir(train_dir)]\ntrain_labels = [1 if 'dog' in fname else 0 for fname in os.listdir(train_dir)]  # 1 for dog, 0 for cat\ntrain_labels = [str(label) for label in train_labels]  # Convert labels to strings\ntrain_df = pd.DataFrame({'filename': train_filenames, 'label': train_labels})\n\n# Create the generator for training data\ntrain_generator = train_datagen.flow_from_dataframe(train_df,\n                                                    x_col='filename',\n                                                    y_col='label',\n                                                    target_size=(img_width, img_height),\n                                                    batch_size=batch_size,\n                                                    class_mode='binary')\n\n# Train the model\nhistory = model.fit(train_generator,\n                    steps_per_epoch=len(train_generator),\n                    epochs=epochs)\n\n# Save the model\nmodel.save('/kaggle/working/cats_vs_dogs_cnn_model.h5')\n\n# Make predictions on the test set\ntest_datagen = ImageDataGenerator(rescale=1./255)\ntest_filenames = [os.path.join(test_dir, fname) for fname in os.listdir(test_dir)]\ntest_df = pd.DataFrame({'filename': test_filenames})\n\ntest_generator = test_datagen.flow_from_dataframe(test_df,\n                                                  x_col='filename',\n                                                  y_col=None,\n                                                  target_size=(img_width, img_height),\n                                                  batch_size=batch_size,\n                                                  class_mode=None,\n                                                  shuffle=False)\n\npredictions = model.predict(test_generator, verbose=1)\n\n# Save predictions to a CSV file for submission to Kaggle\nfilenames = [os.path.basename(filename) for filename in test_generator.filenames]\npredictions_df = pd.DataFrame({'id': filenames, 'label': predictions.flatten()})\npredictions_df['id'] = predictions_df['id'].apply(lambda x: x.split('.')[0])\npredictions_df.to_csv('/kaggle/working/cats_vs_dogs_predictions.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-03-12T08:11:58.667302Z","iopub.execute_input":"2024-03-12T08:11:58.668019Z","iopub.status.idle":"2024-03-12T08:24:52.775587Z","shell.execute_reply.started":"2024-03-12T08:11:58.667985Z","shell.execute_reply":"2024-03-12T08:24:52.774669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing import image\n\n# Load the trained model\nmodel = load_model('/kaggle/working/cats_vs_dogs_cnn_model.h5')\n\n# Function to preprocess the image\ndef preprocess_image(image_path):\n    img = image.load_img(image_path, target_size=(150, 150))\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)\n    img_array /= 255.0\n    return img_array\n\n# Test images\ntest_image_paths = [\n    '/kaggle/working/test1/3271.jpg',\n    '/kaggle/working/test1/410.jpg',\n    '/kaggle/working/test1/10134.jpg',\n    '/kaggle/working/test1/3804.jpg',\n    '/kaggle/working/test1/10986.jpg',\n    '/kaggle/working/test1/12081.jpg',\n    '/kaggle/working/test1/3660.jpg',\n    '/kaggle/working/test1/473.jpg',\n    '/kaggle/working/test1/4326.jpg',\n    '/kaggle/working/test1/10150.jpg',\n    '/kaggle/working/test1/7831.jpg',\n    '/kaggle/working/test1/1334.jpg',\n    '/kaggle/working/test1/4797.jpg',\n    '/kaggle/working/test1/9437.jpg',\n    '/kaggle/working/test1/182.jpg',\n    '/kaggle/working/test1/9798.jpg',\n    '/kaggle/working/test1/1275.jpg',\n    '/kaggle/working/test1/2197.jpg',\n    '/kaggle/working/test1/10543.jpg',\n    '/kaggle/working/test1/6565.jpg',\n    '/kaggle/working/test1/8926.jpg',\n    '/kaggle/working/test1/8993.jpg',\n    '/kaggle/working/test1/2251.jpg',\n    '/kaggle/working/test1/3473.jpg',\n    '/kaggle/working/test1/7227.jpg',\n    '/kaggle/working/test1/11820.jpg',\n    '/kaggle/working/test1/6128.jpg'\n   \n    \n    \n    # Add more test image paths as needed\n]\n\n# Make predictions\nfor image_path in test_image_paths:\n    img_array = preprocess_image(image_path)\n    prediction = model.predict(img_array)\n    predicted_class = \"dog\" if prediction[0][0] > 0.5 else \"cat\"\n    \n    # Display the image and predicted class\n    img = image.load_img(image_path, target_size=(150, 150))\n    plt.imshow(img)\n    plt.axis('off')\n    plt.title(f'Predicted Class: {predicted_class}')\n    plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-03-12T08:46:32.403010Z","iopub.execute_input":"2024-03-12T08:46:32.404013Z","iopub.status.idle":"2024-03-12T08:46:41.356839Z","shell.execute_reply.started":"2024-03-12T08:46:32.403970Z","shell.execute_reply":"2024-03-12T08:46:41.355811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}