{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# import required libraries\nimport os\nimport zipfile\nimport random\nimport shutil\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow import keras","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip -l \"/kaggle/input/dogs-vs-cats/train.zip\"","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:17:11.852238Z","iopub.execute_input":"2023-06-04T18:17:11.852943Z","iopub.status.idle":"2023-06-04T18:17:13.419900Z","shell.execute_reply.started":"2023-06-04T18:17:11.852909Z","shell.execute_reply":"2023-06-04T18:17:13.418851Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Path to the ZIP file\nzip_file_path = \"/kaggle/input/dogs-vs-cats/train.zip\"\n\n# Path to the destination folder\ndestination_folder = \"/kaggle/working/\"","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:17:53.656376Z","iopub.execute_input":"2023-06-04T18:17:53.656748Z","iopub.status.idle":"2023-06-04T18:17:53.662609Z","shell.execute_reply.started":"2023-06-04T18:17:53.656713Z","shell.execute_reply":"2023-06-04T18:17:53.661400Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create the destination folder if it doesn't exist\nos.makedirs(destination_folder, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:17:57.861369Z","iopub.execute_input":"2023-06-04T18:17:57.861732Z","iopub.status.idle":"2023-06-04T18:17:57.866891Z","shell.execute_reply.started":"2023-06-04T18:17:57.861704Z","shell.execute_reply":"2023-06-04T18:17:57.865732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Open the ZIP file\nwith zipfile.ZipFile(zip_file_path, 'r') as zip_ref:\n    # Extract all files in the ZIP to the destination folder\n    zip_ref.extractall(destination_folder)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:18:03.032140Z","iopub.execute_input":"2023-06-04T18:18:03.032500Z","iopub.status.idle":"2023-06-04T18:18:13.328027Z","shell.execute_reply.started":"2023-06-04T18:18:03.032472Z","shell.execute_reply":"2023-06-04T18:18:13.327122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create subfolders for cat and dog images\ncat_folder = os.path.join(destination_folder, 'train', 'cat')\ndog_folder = os.path.join(destination_folder, 'train', 'dog')\n\nos.makedirs(cat_folder, exist_ok=True)\nos.makedirs(dog_folder, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:18:16.791308Z","iopub.execute_input":"2023-06-04T18:18:16.791714Z","iopub.status.idle":"2023-06-04T18:18:16.797861Z","shell.execute_reply.started":"2023-06-04T18:18:16.791682Z","shell.execute_reply":"2023-06-04T18:18:16.796763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Move the images to the appropriate subfolders\nimage_folder = os.path.join(destination_folder, 'train')\n\nfor filename in os.listdir(image_folder):\n    if filename.startswith('cat.'):\n        src = os.path.join(image_folder, filename)\n        dst = os.path.join(cat_folder, filename)\n        os.rename(src, dst)\n    elif filename.startswith('dog.'):\n        src = os.path.join(image_folder, filename)\n        dst = os.path.join(dog_folder, filename)\n        os.rename(src, dst)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:18:21.881122Z","iopub.execute_input":"2023-06-04T18:18:21.881500Z","iopub.status.idle":"2023-06-04T18:18:22.584802Z","shell.execute_reply.started":"2023-06-04T18:18:21.881470Z","shell.execute_reply":"2023-06-04T18:18:22.583729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Path to the destination folder for the test set\ntest_folder = \"/kaggle/working/test\"\n\n# Create the test folder if it doesn't exist\nos.makedirs(test_folder, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:18:38.497754Z","iopub.execute_input":"2023-06-04T18:18:38.498146Z","iopub.status.idle":"2023-06-04T18:18:38.503477Z","shell.execute_reply.started":"2023-06-04T18:18:38.498113Z","shell.execute_reply":"2023-06-04T18:18:38.502460Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create subfolders for cat and dog images in the test folder\ncat_test_folder = os.path.join(test_folder, 'cat')\ndog_test_folder = os.path.join(test_folder, 'dog')\n\nos.makedirs(cat_test_folder, exist_ok=True)\nos.makedirs(dog_test_folder, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:18:42.251608Z","iopub.execute_input":"2023-06-04T18:18:42.251965Z","iopub.status.idle":"2023-06-04T18:18:42.257951Z","shell.execute_reply.started":"2023-06-04T18:18:42.251936Z","shell.execute_reply":"2023-06-04T18:18:42.256837Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the list of cat and dog image files\ncat_files = [filename for filename in os.listdir(os.path.join(image_folder, 'cat'))]\ndog_files = [filename for filename in os.listdir(os.path.join(image_folder, 'dog'))]","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:18:46.080660Z","iopub.execute_input":"2023-06-04T18:18:46.081031Z","iopub.status.idle":"2023-06-04T18:18:46.103682Z","shell.execute_reply.started":"2023-06-04T18:18:46.081002Z","shell.execute_reply":"2023-06-04T18:18:46.102795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Calculate the number of images to move to the test set (20%)\nnum_images_to_move = int(len(cat_files) * 0.20)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:18:49.583550Z","iopub.execute_input":"2023-06-04T18:18:49.583920Z","iopub.status.idle":"2023-06-04T18:18:49.589087Z","shell.execute_reply.started":"2023-06-04T18:18:49.583884Z","shell.execute_reply":"2023-06-04T18:18:49.587964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Randomly select the images to move from the cat and dog folders\nrandom_cat_files = random.sample(cat_files, num_images_to_move)\nrandom_dog_files = random.sample(dog_files, num_images_to_move)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:18:52.368657Z","iopub.execute_input":"2023-06-04T18:18:52.369012Z","iopub.status.idle":"2023-06-04T18:18:52.379093Z","shell.execute_reply.started":"2023-06-04T18:18:52.368981Z","shell.execute_reply":"2023-06-04T18:18:52.377834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Move the randomly selected images to the test set folders\nfor filename in random_cat_files:\n    src = os.path.join(image_folder, 'cat', filename)\n    dst = os.path.join(cat_test_folder, filename)\n    shutil.move(src, dst)\n\nfor filename in random_dog_files:\n    src = os.path.join(image_folder, 'dog', filename)\n    dst = os.path.join(dog_test_folder, filename)\n    shutil.move(src, dst)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:18:55.317698Z","iopub.execute_input":"2023-06-04T18:18:55.318461Z","iopub.status.idle":"2023-06-04T18:18:55.495179Z","shell.execute_reply.started":"2023-06-04T18:18:55.318408Z","shell.execute_reply":"2023-06-04T18:18:55.494230Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the train data into a dataset object\ntrain_dataset, validation_dataset = keras.utils.image_dataset_from_directory(image_folder,\n                                                         labels=\"inferred\",\n                                                         label_mode=\"binary\",\n                                                         batch_size=32,\n                                                         image_size=(256, 256),\n                                                         shuffle=True,\n                                                         seed=123,\n                                                         validation_split=0.20, subset=\"both\")","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:18:58.470374Z","iopub.execute_input":"2023-06-04T18:18:58.470729Z","iopub.status.idle":"2023-06-04T18:19:04.071558Z","shell.execute_reply.started":"2023-06-04T18:18:58.470702Z","shell.execute_reply":"2023-06-04T18:19:04.070522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Display an image from the dataset object\nclass_names = ['Cat', 'Dog']\nplt.figure(figsize=(10, 10))\nfor images, labels in train_dataset.take(1):\n    for i in range(2):\n        ax = plt.subplot(3, 3, i + 1)\n        plt.imshow(images[i].numpy().astype(\"uint8\"))\n        plt.title(class_names[int(labels[i])])\n        plt.axis(\"off\")","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:19:07.201227Z","iopub.execute_input":"2023-06-04T18:19:07.201593Z","iopub.status.idle":"2023-06-04T18:19:08.132523Z","shell.execute_reply.started":"2023-06-04T18:19:07.201562Z","shell.execute_reply":"2023-06-04T18:19:08.131647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the test data into a dataset object\ntest_dataset = keras.utils.image_dataset_from_directory(test_folder,\n                                                         labels=\"inferred\",\n                                                         label_mode=\"binary\",\n                                                         batch_size=32,\n                                                         image_size=(256, 256),\n                                                         shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:19:12.752195Z","iopub.execute_input":"2023-06-04T18:19:12.752548Z","iopub.status.idle":"2023-06-04T18:19:13.074590Z","shell.execute_reply.started":"2023-06-04T18:19:12.752519Z","shell.execute_reply":"2023-06-04T18:19:13.073650Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create the model using Keras functional API\n\ninputs = keras.Input(shape=(None, None, 3))\n\n# Center-crop images to 150x150\nx = keras.layers.CenterCrop(height=150, width=150)(inputs)\n\n# Rescale images to [0, 1]\nx = keras.layers.Rescaling(scale=1.0 / 255)(x)\n\n# Apply some convolution and pooling layers\nx = keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation=\"relu\")(x)\nx = keras.layers.MaxPooling2D(pool_size=(2, 2))(x)\nx = keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation=\"relu\")(x)\nx = keras.layers.MaxPooling2D(pool_size=(2, 2))(x)\nx = keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation=\"relu\")(x)\n\n# Apply global average pooling to get flat feature vectors\nx = keras.layers.GlobalAveragePooling2D()(x)\n\n# Add a dense classifier on top\nx = keras.layers.Dense(8, activation=\"relu\")(x)\noutputs = keras.layers.Dense(1, activation=\"sigmoid\")(x)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:19:16.720010Z","iopub.execute_input":"2023-06-04T18:19:16.720401Z","iopub.status.idle":"2023-06-04T18:19:16.925090Z","shell.execute_reply.started":"2023-06-04T18:19:16.720362Z","shell.execute_reply":"2023-06-04T18:19:16.924108Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = keras.Model(inputs=inputs, outputs=outputs)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:19:20.565184Z","iopub.execute_input":"2023-06-04T18:19:20.565542Z","iopub.status.idle":"2023-06-04T18:19:20.579636Z","shell.execute_reply.started":"2023-06-04T18:19:20.565512Z","shell.execute_reply":"2023-06-04T18:19:20.578475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:19:23.880094Z","iopub.execute_input":"2023-06-04T18:19:23.880737Z","iopub.status.idle":"2023-06-04T18:19:23.910367Z","shell.execute_reply.started":"2023-06-04T18:19:23.880705Z","shell.execute_reply":"2023-06-04T18:19:23.909645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compile model\nmodel.compile(optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n              loss=keras.losses.BinaryCrossentropy(), metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:19:28.933906Z","iopub.execute_input":"2023-06-04T18:19:28.934272Z","iopub.status.idle":"2023-06-04T18:19:28.955613Z","shell.execute_reply.started":"2023-06-04T18:19:28.934241Z","shell.execute_reply":"2023-06-04T18:19:28.954750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train model\nmodel.fit(train_dataset, epochs=10, validation_data=[validation_dataset])","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:19:32.087057Z","iopub.execute_input":"2023-06-04T18:19:32.087449Z","iopub.status.idle":"2023-06-04T18:26:42.630817Z","shell.execute_reply.started":"2023-06-04T18:19:32.087411Z","shell.execute_reply":"2023-06-04T18:26:42.629592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate model\nmodel.evaluate(test_dataset)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:26:48.247870Z","iopub.execute_input":"2023-06-04T18:26:48.248256Z","iopub.status.idle":"2023-06-04T18:26:58.512282Z","shell.execute_reply.started":"2023-06-04T18:26:48.248226Z","shell.execute_reply":"2023-06-04T18:26:58.511164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Choose random sample and display it\nsample = []\nlabel = 1\nclass_names = ['Cat', 'Dog']\nplt.figure(figsize=(10, 10))\nfor images, labels in train_dataset.take(1):\n    sample = images[0].numpy()\n    label = int(labels[0])\n    for i in range(1):\n        ax = plt.subplot(3, 3, i + 1)\n        plt.imshow(images[i].numpy().astype(\"uint8\"))\n        plt.title(class_names[int(labels[i])])\n        plt.axis(\"off\")","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:27:28.438419Z","iopub.execute_input":"2023-06-04T18:27:28.438772Z","iopub.status.idle":"2023-06-04T18:27:29.271194Z","shell.execute_reply.started":"2023-06-04T18:27:28.438745Z","shell.execute_reply":"2023-06-04T18:27:29.270315Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Add batch dimension\nsample = sample.reshape((1, 256, 256, 3))","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:27:32.621447Z","iopub.execute_input":"2023-06-04T18:27:32.621809Z","iopub.status.idle":"2023-06-04T18:27:32.626839Z","shell.execute_reply.started":"2023-06-04T18:27:32.621779Z","shell.execute_reply":"2023-06-04T18:27:32.625484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Predict using model\nresult = model.predict(sample)","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:27:35.832661Z","iopub.execute_input":"2023-06-04T18:27:35.833101Z","iopub.status.idle":"2023-06-04T18:27:35.917429Z","shell.execute_reply.started":"2023-06-04T18:27:35.833049Z","shell.execute_reply":"2023-06-04T18:27:35.916446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"Predicted --->>> {round(float(result))}\")\nprint(f\"True value --->>> {label}\")","metadata":{"execution":{"iopub.status.busy":"2023-06-04T18:27:41.288375Z","iopub.execute_input":"2023-06-04T18:27:41.288731Z","iopub.status.idle":"2023-06-04T18:27:41.293933Z","shell.execute_reply.started":"2023-06-04T18:27:41.288702Z","shell.execute_reply":"2023-06-04T18:27:41.292953Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}