{"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":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30673,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-04-04T12:49:50.555834Z","iopub.execute_input":"2024-04-04T12:49:50.556545Z","iopub.status.idle":"2024-04-04T12:49:51.927416Z","shell.execute_reply.started":"2024-04-04T12:49:50.556492Z","shell.execute_reply":"2024-04-04T12:49:51.926181Z"},"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/c/dogs-vs-cats/sampleSubmission.csv')\n\n# Now you can work with the dataset as usual\nprint(sampleSubmission.head())","metadata":{"execution":{"iopub.status.busy":"2024-04-04T12:49:55.456812Z","iopub.execute_input":"2024-04-04T12:49:55.458056Z","iopub.status.idle":"2024-04-04T12:49:55.493573Z","shell.execute_reply.started":"2024-04-04T12:49:55.457983Z","shell.execute_reply":"2024-04-04T12:49:55.492184Z"},"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/c/dogs-vs-cats/test1.zip'\ntrain_zip_path = '/kaggle/input/c/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)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-04T12:49:59.131297Z","iopub.execute_input":"2024-04-04T12:49:59.131704Z","iopub.status.idle":"2024-04-04T12:50:16.996656Z","shell.execute_reply.started":"2024-04-04T12:49:59.131673Z","shell.execute_reply":"2024-04-04T12:50:16.995558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"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/1634.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","metadata":{"execution":{"iopub.status.busy":"2024-04-04T12:50:47.110844Z","iopub.execute_input":"2024-04-04T12:50:47.111248Z","iopub.status.idle":"2024-04-04T12:50:47.362484Z","shell.execute_reply.started":"2024-04-04T12:50:47.111210Z","shell.execute_reply":"2024-04-04T12:50:47.361166Z"},"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","metadata":{"execution":{"iopub.status.busy":"2024-04-04T14:03:58.635002Z","iopub.execute_input":"2024-04-04T14:03:58.636279Z","iopub.status.idle":"2024-04-04T14:03:58.642773Z","shell.execute_reply.started":"2024-04-04T14:03:58.636239Z","shell.execute_reply":"2024-04-04T14:03:58.641568Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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","metadata":{"execution":{"iopub.status.busy":"2024-04-04T12:51:29.176266Z","iopub.execute_input":"2024-04-04T12:51:29.177237Z","iopub.status.idle":"2024-04-04T12:51:29.419528Z","shell.execute_reply.started":"2024-04-04T12:51:29.177190Z","shell.execute_reply":"2024-04-04T12:51:29.418287Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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})","metadata":{"execution":{"iopub.status.busy":"2024-04-04T14:01:06.473872Z","iopub.execute_input":"2024-04-04T14:01:06.474244Z","iopub.status.idle":"2024-04-04T14:01:06.586950Z","shell.execute_reply.started":"2024-04-04T14:01:06.474217Z","shell.execute_reply":"2024-04-04T14:01:06.585603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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')","metadata":{"execution":{"iopub.status.busy":"2024-04-04T12:51:39.845316Z","iopub.execute_input":"2024-04-04T12:51:39.845699Z","iopub.status.idle":"2024-04-04T13:58:13.199156Z","shell.execute_reply.started":"2024-04-04T12:51:39.845672Z","shell.execute_reply":"2024-04-04T13:58:13.197821Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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-04-04T13:58:21.085394Z","iopub.execute_input":"2024-04-04T13:58:21.085801Z","iopub.status.idle":"2024-04-04T14:00:02.732326Z","shell.execute_reply.started":"2024-04-04T13:58:21.085752Z","shell.execute_reply":"2024-04-04T14:00:02.730582Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Importing the necessary library\nfrom tensorflow.keras.models import load_model","metadata":{"execution":{"iopub.status.busy":"2024-04-04T14:04:20.668727Z","iopub.execute_input":"2024-04-04T14:04:20.669380Z","iopub.status.idle":"2024-04-04T14:04:20.674804Z","shell.execute_reply.started":"2024-04-04T14:04:20.669342Z","shell.execute_reply":"2024-04-04T14:04:20.673461Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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","metadata":{"execution":{"iopub.status.busy":"2024-04-04T14:04:25.407537Z","iopub.execute_input":"2024-04-04T14:04:25.407935Z","iopub.status.idle":"2024-04-04T14:04:25.898695Z","shell.execute_reply.started":"2024-04-04T14:04:25.407905Z","shell.execute_reply":"2024-04-04T14:04:25.897252Z"},"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","metadata":{"execution":{"iopub.status.busy":"2024-04-04T14:04:30.339201Z","iopub.execute_input":"2024-04-04T14:04:30.339627Z","iopub.status.idle":"2024-04-04T14:04:30.345980Z","shell.execute_reply.started":"2024-04-04T14:04:30.339593Z","shell.execute_reply":"2024-04-04T14:04:30.344479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the trained model\nmodel = load_model('/kaggle/working/cats_vs_dogs_cnn_model.h5')\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    \n]","metadata":{"execution":{"iopub.status.busy":"2024-04-04T14:04:33.524386Z","iopub.execute_input":"2024-04-04T14:04:33.525681Z","iopub.status.idle":"2024-04-04T14:04:33.934499Z","shell.execute_reply.started":"2024-04-04T14:04:33.525641Z","shell.execute_reply":"2024-04-04T14:04:33.933008Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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()","metadata":{"execution":{"iopub.status.busy":"2024-04-04T14:04:37.805473Z","iopub.execute_input":"2024-04-04T14:04:37.806143Z","iopub.status.idle":"2024-04-04T14:04:46.030339Z","shell.execute_reply.started":"2024-04-04T14:04:37.806099Z","shell.execute_reply":"2024-04-04T14:04:46.028586Z"},"trusted":true},"execution_count":null,"outputs":[]}]}