{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","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":31041,"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-06-14T22:39:41.719250Z","iopub.execute_input":"2025-06-14T22:39:41.719529Z","iopub.status.idle":"2025-06-14T22:39:44.740574Z","shell.execute_reply.started":"2025-06-14T22:39:41.719503Z","shell.execute_reply":"2025-06-14T22:39:44.739782Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!unzip -qq /kaggle/input/dogs-vs-cats/train.zip","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:39:44.741329Z","iopub.execute_input":"2025-06-14T22:39:44.741665Z","iopub.status.idle":"2025-06-14T22:39:57.038249Z","shell.execute_reply.started":"2025-06-14T22:39:44.741645Z","shell.execute_reply":"2025-06-14T22:39:57.037176Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os, shutil, pathlib\noriginal_dir = pathlib.Path(\"train\")\nnew_base_dir = pathlib.Path(\"cats_vs_dogs_small\")\n\ndef make_subset(subset_name, start_index, end_index):\n    for category in (\"cat\", \"dog\"):\n        dir = new_base_dir / subset_name / category\n        os.makedirs(dir)\n        fnames = [f\"{category}.{i}.jpg\" for i in range(start_index, end_index)]\n        for fname in fnames:\n            shutil.copyfile(src=original_dir / fname, dst=dir / fname)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:39:57.040551Z","iopub.execute_input":"2025-06-14T22:39:57.040819Z","iopub.status.idle":"2025-06-14T22:39:57.046335Z","shell.execute_reply.started":"2025-06-14T22:39:57.040793Z","shell.execute_reply":"2025-06-14T22:39:57.045576Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"make_subset(\"train\", start_index=0, end_index=1000)\nmake_subset(\"validation\", start_index=1000, end_index=1500)\nmake_subset(\"test\", start_index=1500, end_index=2500)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:39:57.047151Z","iopub.execute_input":"2025-06-14T22:39:57.047399Z","iopub.status.idle":"2025-06-14T22:39:57.691022Z","shell.execute_reply.started":"2025-06-14T22:39:57.047375Z","shell.execute_reply":"2025-06-14T22:39:57.690439Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!apt-get install tree\n!tree -L 2 cats_vs_dogs_small","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:39:57.691850Z","iopub.execute_input":"2025-06-14T22:39:57.692064Z","iopub.status.idle":"2025-06-14T22:40:07.428212Z","shell.execute_reply.started":"2025-06-14T22:39:57.692047Z","shell.execute_reply":"2025-06-14T22:40:07.427064Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\n# Define paths\nbase_dir = '/kaggle/working/cats_vs_dogs_small/test'\ncat_dir = os.path.join(base_dir, 'cat')\ndog_dir = os.path.join(base_dir, 'dog')\n\n# Get a few filenames\ncat_images = sorted(os.listdir(cat_dir))[:5]\ndog_images = sorted(os.listdir(dog_dir))[:5]\n\n# Helper function to plot images\ndef plot_images(image_paths, title):\n    plt.figure(figsize=(15, 5))\n    for i, img_name in enumerate(image_paths):\n        img_path = os.path.join(cat_dir if title == \"Cat\" else dog_dir, img_name)\n        img = Image.open(img_path)\n        plt.subplot(1, len(image_paths), i + 1)\n        plt.imshow(img)\n        plt.axis('off')\n        plt.title(f\"{title} {i}\")\n    plt.show()\n\n# Show cats\nplot_images(cat_images, title=\"Cat\")\n\n# Show dogs\nplot_images(dog_images, title=\"Dog\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:40:07.429651Z","iopub.execute_input":"2025-06-14T22:40:07.429922Z","iopub.status.idle":"2025-06-14T22:40:08.594948Z","shell.execute_reply.started":"2025-06-14T22:40:07.429893Z","shell.execute_reply":"2025-06-14T22:40:08.594189Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow import keras\nfrom tensorflow.keras import layers\n\ninputs = keras.Input(shape=(180, 180, 3))\nx = layers.Rescaling(1./255)(inputs)\nx = layers.Conv2D(filters=32, kernel_size=3, activation=\"relu\")(x)\nx = layers.MaxPooling2D(pool_size=2)(x)\nx = layers.Conv2D(filters=64, kernel_size=3, activation=\"relu\")(x)\nx = layers.MaxPooling2D(pool_size=2)(x)\nx = layers.Conv2D(filters=128, kernel_size=3, activation=\"relu\")(x)\nx = layers.MaxPooling2D(pool_size=2)(x)\nx = layers.Conv2D(filters=256, kernel_size=3, activation=\"relu\")(x)\nx = layers.MaxPooling2D(pool_size=2)(x)\nx = layers.Conv2D(filters=256, kernel_size=3, activation=\"relu\")(x)\nx = layers.Flatten()(x)\noutputs = layers.Dense(1, activation=\"sigmoid\")(x)\nmodel = keras.Model(inputs=inputs, outputs=outputs)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:40:08.595893Z","iopub.execute_input":"2025-06-14T22:40:08.596205Z","iopub.status.idle":"2025-06-14T22:40:35.078928Z","shell.execute_reply.started":"2025-06-14T22:40:08.596175Z","shell.execute_reply":"2025-06-14T22:40:35.077998Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:40:35.079958Z","iopub.execute_input":"2025-06-14T22:40:35.080576Z","iopub.status.idle":"2025-06-14T22:40:35.106620Z","shell.execute_reply.started":"2025-06-14T22:40:35.080546Z","shell.execute_reply":"2025-06-14T22:40:35.105717Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(loss=\"binary_crossentropy\",\n    optimizer=\"rmsprop\",\n    metrics=[\"accuracy\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:40:35.109824Z","iopub.execute_input":"2025-06-14T22:40:35.110143Z","iopub.status.idle":"2025-06-14T22:40:35.140768Z","shell.execute_reply.started":"2025-06-14T22:40:35.110124Z","shell.execute_reply":"2025-06-14T22:40:35.139783Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.utils import image_dataset_from_directory\n\ntrain_dataset = image_dataset_from_directory(\n    new_base_dir / \"train\",\n    image_size=(180, 180),\n    batch_size=32)\n\nvalidation_dataset = image_dataset_from_directory(\n    new_base_dir / \"validation\",\n    image_size=(180, 180),\n    batch_size=32)\n\ntest_dataset = image_dataset_from_directory(\n    new_base_dir / \"test\",\n    image_size=(180, 180),\n    batch_size=32)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:40:35.141834Z","iopub.execute_input":"2025-06-14T22:40:35.142131Z","iopub.status.idle":"2025-06-14T22:40:36.743254Z","shell.execute_reply.started":"2025-06-14T22:40:35.142107Z","shell.execute_reply":"2025-06-14T22:40:36.742621Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for data_batch, labels_batch in train_dataset:\n    print(\"data batch shape:\", data_batch.shape)\n    print(\"labels batch shape:\", labels_batch.shape)\n    break","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:40:36.744112Z","iopub.execute_input":"2025-06-14T22:40:36.744378Z","iopub.status.idle":"2025-06-14T22:40:36.881195Z","shell.execute_reply.started":"2025-06-14T22:40:36.744343Z","shell.execute_reply":"2025-06-14T22:40:36.880442Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"callbacks = [\n    keras.callbacks.ModelCheckpoint(\n    filepath=\"convnet_from_scratch.keras\",\n    save_best_only=True,\n    monitor=\"val_loss\")\n]\nhistory = model.fit(\n    train_dataset,\n    epochs=30,\n    validation_data=validation_dataset,\n    callbacks=callbacks)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:40:36.882208Z","iopub.execute_input":"2025-06-14T22:40:36.882474Z","iopub.status.idle":"2025-06-14T22:42:10.397144Z","shell.execute_reply.started":"2025-06-14T22:40:36.882455Z","shell.execute_reply":"2025-06-14T22:42:10.396213Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\naccuracy = history.history[\"accuracy\"]\nval_accuracy = history.history[\"val_accuracy\"]\nloss = history.history[\"loss\"]\nval_loss = history.history[\"val_loss\"]\nepochs = range(1, len(accuracy) + 1)\n\nplt.plot(epochs, accuracy, \"bo\", label=\"Training accuracy\")\nplt.plot(epochs, val_accuracy, \"b\", label=\"Validation accuracy\")\nplt.title(\"Training and validation accuracy\")\nplt.legend()\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.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:42:10.398296Z","iopub.execute_input":"2025-06-14T22:42:10.398777Z","iopub.status.idle":"2025-06-14T22:42:10.801915Z","shell.execute_reply.started":"2025-06-14T22:42:10.398744Z","shell.execute_reply":"2025-06-14T22:42:10.801020Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_model = keras.models.load_model(\"convnet_from_scratch.keras\")\ntest_loss, test_acc = test_model.evaluate(test_dataset)\nprint(f\"Test accuracy: {test_acc:.3f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:42:10.802714Z","iopub.execute_input":"2025-06-14T22:42:10.802963Z","iopub.status.idle":"2025-06-14T22:42:13.640217Z","shell.execute_reply.started":"2025-06-14T22:42:10.802945Z","shell.execute_reply":"2025-06-14T22:42:13.639373Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_augmentation = keras.Sequential(\n    [\n        layers.RandomFlip(\"horizontal\"),\n        layers.RandomRotation(0.1),\n        layers.RandomZoom(0.2),\n    ]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:42:13.641042Z","iopub.execute_input":"2025-06-14T22:42:13.641266Z","iopub.status.idle":"2025-06-14T22:42:13.657735Z","shell.execute_reply.started":"2025-06-14T22:42:13.641240Z","shell.execute_reply":"2025-06-14T22:42:13.657010Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(10, 10))\nfor images, _ in train_dataset.take(1):\n    for i in range(9):\n        augmented_images = data_augmentation(images)\n        ax = plt.subplot(3, 3, i + 1)\n        plt.imshow(augmented_images[0].numpy().astype(\"uint8\"))\n        plt.axis(\"off\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:42:13.658537Z","iopub.execute_input":"2025-06-14T22:42:13.658802Z","iopub.status.idle":"2025-06-14T22:42:15.537761Z","shell.execute_reply.started":"2025-06-14T22:42:13.658783Z","shell.execute_reply":"2025-06-14T22:42:15.536864Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"inputs = keras.Input(shape=(180, 180, 3))\nx = data_augmentation(inputs)\nx = layers.Rescaling(1./255)(x)\nx = layers.Conv2D(filters=32, kernel_size=3, activation=\"relu\")(x)\nx = layers.MaxPooling2D(pool_size=2)(x)\nx = layers.Conv2D(filters=64, kernel_size=3, activation=\"relu\")(x)\nx = layers.MaxPooling2D(pool_size=2)(x)\nx = layers.Conv2D(filters=128, kernel_size=3, activation=\"relu\")(x)\nx = layers.MaxPooling2D(pool_size=2)(x)\nx = layers.Conv2D(filters=256, kernel_size=3, activation=\"relu\")(x)\nx = layers.MaxPooling2D(pool_size=2)(x)\nx = layers.Conv2D(filters=256, kernel_size=3, activation=\"relu\")(x)\nx = layers.Flatten()(x)\nx = layers.Dropout(0.5)(x)\noutputs = layers.Dense(1, activation=\"sigmoid\")(x)\nmodel = keras.Model(inputs=inputs, outputs=outputs)\nmodel.compile(loss=\"binary_crossentropy\",\noptimizer=\"rmsprop\",\nmetrics=[\"accuracy\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:42:15.538792Z","iopub.execute_input":"2025-06-14T22:42:15.539072Z","iopub.status.idle":"2025-06-14T22:42:15.614486Z","shell.execute_reply.started":"2025-06-14T22:42:15.539050Z","shell.execute_reply":"2025-06-14T22:42:15.613823Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"callbacks = [\n    keras.callbacks.ModelCheckpoint(\n    filepath=\"convnet_from_scratch_with_augmentation.keras\",\n    save_best_only=True,\n    monitor=\"val_loss\")\n]\nhistory = model.fit(\n    train_dataset,\n    epochs=100,\n    validation_data=validation_dataset,\n    callbacks=callbacks)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:42:15.615219Z","iopub.execute_input":"2025-06-14T22:42:15.615432Z","iopub.status.idle":"2025-06-14T22:47:24.693655Z","shell.execute_reply.started":"2025-06-14T22:42:15.615416Z","shell.execute_reply":"2025-06-14T22:47:24.692950Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\naccuracy = history.history[\"accuracy\"]\nval_accuracy = history.history[\"val_accuracy\"]\nloss = history.history[\"loss\"]\nval_loss = history.history[\"val_loss\"]\nepochs = range(1, len(accuracy) + 1)\n\nplt.plot(epochs, accuracy, \"bo\", label=\"Training accuracy\")\nplt.plot(epochs, val_accuracy, \"b\", label=\"Validation accuracy\")\nplt.title(\"Training and validation accuracy\")\nplt.legend()\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.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:47:24.694759Z","iopub.execute_input":"2025-06-14T22:47:24.694975Z","iopub.status.idle":"2025-06-14T22:47:25.056785Z","shell.execute_reply.started":"2025-06-14T22:47:24.694958Z","shell.execute_reply":"2025-06-14T22:47:25.055897Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_model = keras.models.load_model(\n    \"convnet_from_scratch_with_augmentation.keras\")\ntest_loss, test_acc = test_model.evaluate(test_dataset)\nprint(f\"Test accuracy: {test_acc:.3f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:47:25.057576Z","iopub.execute_input":"2025-06-14T22:47:25.057829Z","iopub.status.idle":"2025-06-14T22:47:26.838037Z","shell.execute_reply.started":"2025-06-14T22:47:25.057812Z","shell.execute_reply":"2025-06-14T22:47:26.837207Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save(\"convnet_from_scratch_with_augmentation.keras\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T22:48:27.307498Z","iopub.execute_input":"2025-06-14T22:48:27.308203Z","iopub.status.idle":"2025-06-14T22:48:27.401413Z","shell.execute_reply.started":"2025-06-14T22:48:27.308178Z","shell.execute_reply":"2025-06-14T22:48:27.400521Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow import keras\nimport numpy as np\n\nimg_path = keras.utils.get_file(\n    fname=\"cat.jpg\",\n    origin=\"https://img-datasets.s3.amazonaws.com/cat.jpg\")\n\ndef get_img_array(img_path, target_size):\n    img = keras.utils.load_img(\n        img_path, target_size=target_size)\n    array = keras.utils.img_to_array(img)\n    array = np.expand_dims(array, axis=0)\n    return array\n\nimg_tensor = get_img_array(img_path, target_size=(180, 180))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T23:39:19.403245Z","iopub.execute_input":"2025-06-14T23:39:19.403526Z","iopub.status.idle":"2025-06-14T23:39:19.412844Z","shell.execute_reply.started":"2025-06-14T23:39:19.403509Z","shell.execute_reply":"2025-06-14T23:39:19.411946Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nplt.axis(\"off\")\nplt.imshow(img_tensor[0].astype(\"uint8\"))\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T23:39:24.522302Z","iopub.execute_input":"2025-06-14T23:39:24.522658Z","iopub.status.idle":"2025-06-14T23:39:24.663375Z","shell.execute_reply.started":"2025-06-14T23:39:24.522621Z","shell.execute_reply":"2025-06-14T23:39:24.662659Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import layers\n\nlayer_outputs = []\nlayer_names = []\nfor layer in model.layers:\n    if isinstance(layer, (layers.Conv2D, layers.MaxPooling2D)):\n        layer_outputs.append(layer.output)\n        layer_names.append(layer.name)\nactivation_model = keras.Model(inputs=model.input, outputs=layer_outputs)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T23:39:33.139907Z","iopub.execute_input":"2025-06-14T23:39:33.140209Z","iopub.status.idle":"2025-06-14T23:39:33.148080Z","shell.execute_reply.started":"2025-06-14T23:39:33.140187Z","shell.execute_reply":"2025-06-14T23:39:33.146952Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"activations = activation_model.predict(img_tensor)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T23:39:40.627946Z","iopub.execute_input":"2025-06-14T23:39:40.628678Z","iopub.status.idle":"2025-06-14T23:39:40.851371Z","shell.execute_reply.started":"2025-06-14T23:39:40.628652Z","shell.execute_reply":"2025-06-14T23:39:40.850733Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nfirst_layer_activation = activations[0]\nplt.matshow(first_layer_activation[0, :, :, 6], cmap=\"viridis\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-15T00:09:12.314829Z","iopub.execute_input":"2025-06-15T00:09:12.315144Z","iopub.status.idle":"2025-06-15T00:09:12.614276Z","shell.execute_reply.started":"2025-06-15T00:09:12.315122Z","shell.execute_reply":"2025-06-15T00:09:12.613478Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images_per_row = 16\nfor layer_name, layer_activation in zip(layer_names, activations):\n    n_features = layer_activation.shape[-1]\n    size = layer_activation.shape[1]\n    n_cols = n_features // images_per_row\n    display_grid = np.zeros(((size + 1) * n_cols - 1,\n        images_per_row * (size + 1) - 1))\n    for col in range(n_cols):\n        for row in range(images_per_row):\n            channel_index = col * images_per_row + row\n            channel_image = layer_activation[0, :, :, channel_index].copy()\n            if channel_image.sum() != 0:\n                channel_image -= channel_image.mean()\n                channel_image /= channel_image.std()\n                channel_image *= 64\n                channel_image += 128\n            channel_image = np.clip(channel_image, 0, 255).astype(\"uint8\")\n            display_grid[\n            col * (size + 1): (col + 1) * size + col,\n            row * (size + 1) : (row + 1) * size + row] = channel_image\n    scale = 1. / size\n    plt.figure(figsize=(scale * display_grid.shape[1],\n    scale * display_grid.shape[0]))\n    plt.title(layer_name)\n    plt.grid(False)\n    plt.axis(\"off\")\n    plt.imshow(display_grid, aspect=\"auto\", cmap=\"viridis\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T23:39:46.701716Z","iopub.execute_input":"2025-06-14T23:39:46.702008Z","iopub.status.idle":"2025-06-14T23:39:50.281749Z","shell.execute_reply.started":"2025-06-14T23:39:46.701987Z","shell.execute_reply":"2025-06-14T23:39:50.280871Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.predict(img_tensor)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T23:40:12.081718Z","iopub.execute_input":"2025-06-14T23:40:12.082226Z","iopub.status.idle":"2025-06-14T23:40:12.176965Z","shell.execute_reply.started":"2025-06-14T23:40:12.082198Z","shell.execute_reply":"2025-06-14T23:40:12.176102Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_path1 = keras.utils.get_file(\n    fname=\"dog.jpg\",\n    origin=\"https://storage.googleapis.com/cvstock-932a9.appspot.com/57RF5GJL4PFO\")\nimg_tensor1 = get_img_array(img_path1, target_size=(180, 180))\nplt.axis(\"off\")\nplt.imshow(img_tensor1[0].astype(\"uint8\"))\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-15T00:05:05.908157Z","iopub.execute_input":"2025-06-15T00:05:05.908450Z","iopub.status.idle":"2025-06-15T00:05:06.041144Z","shell.execute_reply.started":"2025-06-15T00:05:05.908413Z","shell.execute_reply":"2025-06-15T00:05:06.040259Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"activations1 = activation_model.predict(img_tensor1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-15T00:09:43.277260Z","iopub.execute_input":"2025-06-15T00:09:43.277816Z","iopub.status.idle":"2025-06-15T00:09:43.393836Z","shell.execute_reply.started":"2025-06-15T00:09:43.277789Z","shell.execute_reply":"2025-06-15T00:09:43.392688Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nfirst_layer_activation = activations1[0]\nplt.matshow(first_layer_activation[0, :, :, 6], cmap=\"viridis\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-15T00:09:46.378363Z","iopub.execute_input":"2025-06-15T00:09:46.378780Z","iopub.status.idle":"2025-06-15T00:09:46.694364Z","shell.execute_reply.started":"2025-06-15T00:09:46.378751Z","shell.execute_reply":"2025-06-15T00:09:46.693470Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images_per_row = 16\nfor layer_name, layer_activation in zip(layer_names, activations):\n    n_features = layer_activation.shape[-1]\n    size = layer_activation.shape[1]\n    n_cols = n_features // images_per_row\n    display_grid = np.zeros(((size + 1) * n_cols - 1,\n        images_per_row * (size + 1) - 1))\n    for col in range(n_cols):\n        for row in range(images_per_row):\n            channel_index = col * images_per_row + row\n            channel_image = layer_activation[0, :, :, channel_index].copy()\n            if channel_image.sum() != 0:\n                channel_image -= channel_image.mean()\n                channel_image /= channel_image.std()\n                channel_image *= 64\n                channel_image += 128\n            channel_image = np.clip(channel_image, 0, 255).astype(\"uint8\")\n            display_grid[\n            col * (size + 1): (col + 1) * size + col,\n            row * (size + 1) : (row + 1) * size + row] = channel_image\n    scale = 1. / size\n    plt.figure(figsize=(scale * display_grid.shape[1],\n    scale * display_grid.shape[0]))\n    plt.title(layer_name)\n    plt.grid(False)\n    plt.axis(\"off\")\n    plt.imshow(display_grid, aspect=\"auto\", cmap=\"viridis\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T23:30:18.463957Z","iopub.execute_input":"2025-06-14T23:30:18.464607Z","iopub.status.idle":"2025-06-14T23:30:21.962516Z","shell.execute_reply.started":"2025-06-14T23:30:18.464568Z","shell.execute_reply":"2025-06-14T23:30:21.961441Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow import keras\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Load the best model\nmodel = keras.models.load_model(\"convnet_from_scratch_with_augmentation.keras\")\n\n# Load test dataset again if needed\ntest_dataset = image_dataset_from_directory(\n    new_base_dir / \"test\",\n    image_size=(180, 180),\n    batch_size=1  # load one image at a time for prediction\n)\n\n# Get one batch (one image and its label)\nfor image_batch, label_batch in test_dataset.take(1):\n    image = image_batch[0].numpy()\n    label = label_batch[0].numpy()\n    break\n\n# Predict\nprediction = model.predict(np.expand_dims(image, axis=0))[0][0]\npredicted_class = \"Dog\" if prediction > 0.5 else \"Cat\"\nactual_class = \"Dog\" if label == 1 else \"Cat\"\n\n# Display image with prediction\nplt.imshow(image.astype(\"uint8\"))\nplt.axis(\"off\")\nplt.title(f\"Predicted: {predicted_class} | Actual: {actual_class}\")\nplt.show()\n\n# Also show raw prediction score\nprint(f\"Raw model output: {prediction:.4f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T23:41:37.602172Z","iopub.execute_input":"2025-06-14T23:41:37.602503Z","iopub.status.idle":"2025-06-14T23:41:38.282106Z","shell.execute_reply.started":"2025-06-14T23:41:37.602480Z","shell.execute_reply":"2025-06-14T23:41:38.281359Z"}},"outputs":[],"execution_count":null}]}