{"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":"gpu","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-05-27T11:35:42.129883Z","iopub.execute_input":"2025-05-27T11:35:42.130425Z","iopub.status.idle":"2025-05-27T11:35:42.135347Z","shell.execute_reply.started":"2025-05-27T11:35:42.130398Z","shell.execute_reply":"2025-05-27T11:35:42.134799Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom sklearn.model_selection import train_test_split\nimport zipfile\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import datasets, transforms, models\nfrom torch.utils.data import DataLoader, Dataset","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T11:35:44.243761Z","iopub.execute_input":"2025-05-27T11:35:44.244057Z","iopub.status.idle":"2025-05-27T11:35:52.328342Z","shell.execute_reply.started":"2025-05-27T11:35:44.244034Z","shell.execute_reply":"2025-05-27T11:35:52.327803Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\n# Unzip the data\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats/train.zip', 'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working/train')\n\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats/test1.zip', 'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working/test')\n\ntrain_dir = '/kaggle/working/train/train'\ntest_dir = '/kaggle/working/test/test1'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T11:35:52.329380Z","iopub.execute_input":"2025-05-27T11:35:52.329780Z","iopub.status.idle":"2025-05-27T11:36:05.609548Z","shell.execute_reply.started":"2025-05-27T11:35:52.329758Z","shell.execute_reply":"2025-05-27T11:36:05.608965Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"base_dir = '/kaggle/working/train/train'\n\ndef show_random_images(base_dir, num_images=5):\n    files = os.listdir(base_dir)\n    sample_files = random.sample(files, num_images)\n\n    plt.figure(figsize=(15, 5))\n    for idx, f in enumerate(sample_files):\n        img = Image.open(os.path.join(base_dir, f))\n        plt.subplot(1, num_images, idx + 1)\n        plt.imshow(img)\n        plt.title(f)\n        plt.axis('off')\n    plt.tight_layout()\n    plt.show()\n\nshow_random_images(base_dir)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T11:36:05.610221Z","iopub.execute_input":"2025-05-27T11:36:05.610402Z","iopub.status.idle":"2025-05-27T11:36:06.244783Z","shell.execute_reply.started":"2025-05-27T11:36:05.610387Z","shell.execute_reply":"2025-05-27T11:36:06.244038Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nall_files = os.listdir(train_dir)\nfile_paths = [os.path.join(train_dir, fname) for fname in all_files]\nlabels = [1 if 'dog' in fname else 0 for fname in all_files]\n\ntrain_paths, val_paths, train_labels, val_labels = train_test_split(\n    file_paths, labels, test_size=0.2, random_state=42\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T11:36:06.246581Z","iopub.execute_input":"2025-05-27T11:36:06.247047Z","iopub.status.idle":"2025-05-27T11:36:06.292081Z","shell.execute_reply.started":"2025-05-27T11:36:06.247023Z","shell.execute_reply":"2025-05-27T11:36:06.291177Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torchvision import transforms\nfrom torch.utils.data import Dataset\n\nclass CatDogDataset(Dataset):\n    def __init__(self, file_paths, labels=None, transform=None):\n        self.file_paths = file_paths\n        self.labels = labels\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.file_paths)\n\n    def __getitem__(self, idx):\n        img_path = self.file_paths[idx]\n        image = Image.open(img_path).convert('RGB')\n        if self.transform:\n            image = self.transform(image)\n        if self.labels is not None:\n            label = self.labels[idx]\n            return image, label\n        else:\n            return image, os.path.basename(img_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T11:36:29.664430Z","iopub.execute_input":"2025-05-27T11:36:29.665142Z","iopub.status.idle":"2025-05-27T11:36:29.670314Z","shell.execute_reply.started":"2025-05-27T11:36:29.665117Z","shell.execute_reply":"2025-05-27T11:36:29.669712Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"transform = transforms.Compose([\n    transforms.Resize((224, 224)),\n    transforms.ToTensor(),\n    transforms.Normalize([0.485, 0.456, 0.406],\n                         [0.229, 0.224, 0.225])\n])\n\ntrain_dataset = CatDogDataset(train_paths, train_labels, transform)\nval_dataset = CatDogDataset(val_paths, val_labels, transform)\ntest_file_paths = [os.path.join(test_dir, f) for f in os.listdir(test_dir)]\ntest_dataset = CatDogDataset(test_file_paths, labels=None, transform=transform)\n\nfrom torch.utils.data import DataLoader\n\ntrain_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\nval_loader = DataLoader(val_dataset, batch_size=32)\ntest_loader = DataLoader(test_dataset, batch_size=32)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T12:04:07.507391Z","iopub.execute_input":"2025-05-27T12:04:07.507695Z","iopub.status.idle":"2025-05-27T12:04:07.529762Z","shell.execute_reply.started":"2025-05-27T12:04:07.507656Z","shell.execute_reply":"2025-05-27T12:04:07.529057Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Custom CNN with 2-output classifier\nclass CatDogCNN(nn.Module):\n    def __init__(self):\n        super(CatDogCNN, self).__init__()\n        self.features = nn.Sequential(\n            nn.Conv2d(3, 32, kernel_size=3, padding=1),\n            nn.ReLU(),\n            nn.MaxPool2d(2, 2),\n            nn.Conv2d(32, 64, kernel_size=3, padding=1),\n            nn.ReLU(),\n            nn.MaxPool2d(2, 2),\n            nn.Conv2d(64, 128, kernel_size=3, padding=1),\n            nn.ReLU(),\n            nn.MaxPool2d(2, 2)\n        )\n        self.classifier = nn.Sequential(\n            nn.Flatten(),\n            nn.Linear(100352, 512),\n            nn.ReLU(),\n            nn.Dropout(0.3),\n            nn.Linear(512, 2)  # 2 output neurons for cat and dog\n        )\n\n    def forward(self, x):\n        x = self.features(x)\n        x = self.classifier(x)\n        return x\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T12:04:08.402720Z","iopub.execute_input":"2025-05-27T12:04:08.402963Z","iopub.status.idle":"2025-05-27T12:04:08.409156Z","shell.execute_reply.started":"2025-05-27T12:04:08.402946Z","shell.execute_reply":"2025-05-27T12:04:08.408370Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torchvision import models\n\nclass FineTunedResNet(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.base_model = models.resnet18(pretrained=True)\n        \n        for param in self.base_model.parameters():\n            param.requires_grad = False\n        \n        in_features = self.base_model.fc.in_features\n        self.base_model.fc = nn.Sequential(\n            nn.Linear(in_features, 256),\n            nn.ReLU(),\n            nn.Dropout(0.3),\n            nn.Linear(256, 2)  # <-- 2 classes: cat and dog\n        )\n\n    def forward(self, x):\n        return self.base_model(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T12:04:12.711131Z","iopub.execute_input":"2025-05-27T12:04:12.711843Z","iopub.status.idle":"2025-05-27T12:04:12.716601Z","shell.execute_reply.started":"2025-05-27T12:04:12.711820Z","shell.execute_reply":"2025-05-27T12:04:12.715932Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = CatDogCNN().to(device)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T11:39:46.721410Z","iopub.execute_input":"2025-05-27T11:39:46.722103Z","iopub.status.idle":"2025-05-27T11:39:47.225244Z","shell.execute_reply.started":"2025-05-27T11:39:46.722077Z","shell.execute_reply":"2025-05-27T11:39:47.224697Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Training\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = FineTunedResNet().to(device)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#model.load_state_dict(torch.load(weights_path, map_location='gpu'))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def count_parameters(model):\n    return sum(p.numel() for p in model.parameters() if p.requires_grad)\nprint(f\"Model has {count_parameters(model):,} number of trainable parameters.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T12:04:16.519242Z","iopub.execute_input":"2025-05-27T12:04:16.519515Z","iopub.status.idle":"2025-05-27T12:04:16.524450Z","shell.execute_reply.started":"2025-05-27T12:04:16.519494Z","shell.execute_reply":"2025-05-27T12:04:16.523715Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"criterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T12:04:19.166418Z","iopub.execute_input":"2025-05-27T12:04:19.166706Z","iopub.status.idle":"2025-05-27T12:04:19.171597Z","shell.execute_reply.started":"2025-05-27T12:04:19.166655Z","shell.execute_reply":"2025-05-27T12:04:19.170958Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"epochs = 5\ntrain_losses, val_losses = [], []\ntrain_accuracies, val_accuracies = [], []","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T12:04:20.541723Z","iopub.execute_input":"2025-05-27T12:04:20.541981Z","iopub.status.idle":"2025-05-27T12:04:20.545918Z","shell.execute_reply.started":"2025-05-27T12:04:20.541964Z","shell.execute_reply":"2025-05-27T12:04:20.545099Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def train_model(model, train_loader, val_loader, criterion, optimizer, device, epochs):\n    train_losses, val_losses = [], []\n    train_accuracies, val_accuracies = [], []\n\n    for epoch in range(epochs):\n        model.train()\n        running_loss, correct = 0.0, 0\n        train_loop = tqdm(train_loader, desc=f\"Epoch {epoch+1}/{epochs} [Train]\", leave=False)\n        for images, labels in train_loop:\n            images, labels = images.to(device), labels.to(device)\n            outputs = model(images)\n            loss = criterion(outputs, labels)\n            optimizer.zero_grad()\n            loss.backward()\n            optimizer.step()\n\n            running_loss += loss.item() * images.size(0)\n            correct += (outputs.argmax(1) == labels).sum().item()\n            train_loop.set_postfix(loss=loss.item())\n\n        train_loss = running_loss / len(train_loader.dataset)\n        train_acc = correct / len(train_loader.dataset)\n\n        model.eval()\n        val_loss, val_correct = 0.0, 0\n        val_loop = tqdm(val_loader, desc=f\"Epoch {epoch+1}/{epochs} [Val]\", leave=False)\n        with torch.no_grad():\n            for images, labels in val_loop:\n                images, labels = images.to(device), labels.to(device)\n                outputs = model(images)\n                loss = criterion(outputs, labels)\n                val_loss += loss.item() * images.size(0)\n                val_correct += (outputs.argmax(1) == labels).sum().item()\n                val_loop.set_postfix(val_loss=loss.item())\n\n        val_loss /= len(val_loader.dataset)\n        val_acc = val_correct / len(val_loader.dataset)\n\n        train_losses.append(train_loss)\n        val_losses.append(val_loss)\n        train_accuracies.append(train_acc)\n        val_accuracies.append(val_acc)\n\n        print(f\"Epoch {epoch+1}/{epochs} => Train Loss: {train_loss:.4f}, Acc: {train_acc:.4f} | Val Loss: {val_loss:.4f}, Acc: {val_acc:.4f}\")\n\n    return train_losses, val_losses, train_accuracies, val_accuracies","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T12:04:20.854846Z","iopub.execute_input":"2025-05-27T12:04:20.855134Z","iopub.status.idle":"2025-05-27T12:04:20.863386Z","shell.execute_reply.started":"2025-05-27T12:04:20.855112Z","shell.execute_reply":"2025-05-27T12:04:20.862764Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_losses, val_losses, train_accuracies, val_accuracies = train_model(\n    model, train_loader, val_loader, criterion, optimizer, device, epochs=5\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T11:39:54.323912Z","iopub.execute_input":"2025-05-27T11:39:54.324182Z","iopub.status.idle":"2025-05-27T11:48:13.166055Z","shell.execute_reply.started":"2025-05-27T11:39:54.324163Z","shell.execute_reply":"2025-05-27T11:48:13.165336Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_losses, val_losses, train_accuracies, val_accuracies = train_model(\n    model, train_loader, val_loader, criterion, optimizer, device, epochs=5\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T12:04:24.353044Z","iopub.execute_input":"2025-05-27T12:04:24.353325Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plot\nplt.figure(figsize=(10, 4))\nplt.subplot(1, 2, 1)\nplt.plot(train_losses, label='Train Loss')\nplt.plot(val_losses, label='Val Loss')\nplt.legend()\nplt.title(\"Loss\")\n\nplt.subplot(1, 2, 2)\nplt.plot(train_accuracies, label='Train Acc')\nplt.plot(val_accuracies, label='Val Acc')\nplt.legend()\nplt.title(\"Accuracy\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T11:50:17.817718Z","iopub.execute_input":"2025-05-27T11:50:17.818012Z","iopub.status.idle":"2025-05-27T11:50:18.081342Z","shell.execute_reply.started":"2025-05-27T11:50:17.817991Z","shell.execute_reply":"2025-05-27T11:50:18.080610Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plot\nplt.figure(figsize=(10, 4))\nplt.subplot(1, 2, 1)\nplt.plot(train_losses, label='Train Loss')\nplt.plot(val_losses, label='Val Loss')\nplt.legend()\nplt.title(\"Loss\")\n\nplt.subplot(1, 2, 2)\nplt.plot(train_accuracies, label='Train Acc')\nplt.plot(val_accuracies, label='Val Acc')\nplt.legend()\nplt.title(\"Accuracy\")\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def plot_top_misclassified(model, dataloader, class_names=['cat', 'dog'], device='cuda', top_n=5):\n    model.eval()\n    misclassified = []\n\n    with torch.no_grad():\n        for images, labels in dataloader:\n            images = images.to(device)\n            labels = labels.to(device)\n            outputs = model(images)\n            preds = torch.argmax(outputs, dim=1)\n\n            mis_idx = preds != labels\n            for i in range(images.size(0)):\n                if mis_idx[i]:\n                    misclassified.append((images[i].cpu(), preds[i].item(), labels[i].item()))\n\n    # Separate misclassified cats and dogs\n    misclassified_cats = [x for x in misclassified if x[2] == 0][:top_n]\n    misclassified_dogs = [x for x in misclassified if x[2] == 1][:top_n]\n\n    def show_images(examples, title):\n        fig, axes = plt.subplots(1, len(examples), figsize=(4 * len(examples), 4))\n        fig.suptitle(title, fontsize=16)\n        if len(examples) == 1:\n            axes = [axes]\n        for ax, (img_tensor, pred, true) in zip(axes, examples):\n            img = img_tensor.permute(1, 2, 0).numpy()\n            img = (img * np.array([0.229, 0.224, 0.225])) + np.array([0.485, 0.456, 0.406])\n            img = np.clip(img, 0, 1)\n            ax.imshow(img)\n            ax.set_title(f'Pred: {class_names[pred]}\\nTrue: {class_names[true]}', fontsize=12)\n            ax.axis('off')\n        plt.tight_layout()\n        plt.show()\n\n    show_images(misclassified_cats, 'Top Misclassified Cats')\n    show_images(misclassified_dogs, 'Top Misclassified Dogs')","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class_names = ['cat', 'dog']\nplot_top_misclassified(model, val_loader, class_names, device)\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"torch.save(model.state_dict(), '/kaggle/working/cnn_cat_dog_model_weights.pth')\ntorch.save(model, '/kaggle/working/cnn_cat_dog_full_model.pth')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T11:50:28.585867Z","iopub.execute_input":"2025-05-27T11:50:28.586139Z","iopub.status.idle":"2025-05-27T11:50:29.474618Z","shell.execute_reply.started":"2025-05-27T11:50:28.586118Z","shell.execute_reply":"2025-05-27T11:50:29.473637Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"torch.save(model.state_dict(), '/kaggle/working/resnet_cat_dog_model_weights.pth')\ntorch.save(model, '/kaggle/working/resnet_cat_dog_full_model.pth')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-26T22:27:28.118042Z","iopub.execute_input":"2025-05-26T22:27:28.118318Z","iopub.status.idle":"2025-05-26T22:27:28.340793Z","shell.execute_reply.started":"2025-05-26T22:27:28.118297Z","shell.execute_reply":"2025-05-26T22:27:28.340017Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"torch.save(model.state_dict(), \"cat_dog_resnet18.pth\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-26T22:48:01.004776Z","iopub.execute_input":"2025-05-26T22:48:01.005058Z","iopub.status.idle":"2025-05-26T22:48:01.085758Z","shell.execute_reply.started":"2025-05-26T22:48:01.005041Z","shell.execute_reply":"2025-05-26T22:48:01.085109Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}