{"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":31011,"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-04-24T09:22:59.148316Z","iopub.execute_input":"2025-04-24T09:22:59.148497Z","iopub.status.idle":"2025-04-24T09:23:02.204508Z","shell.execute_reply.started":"2025-04-24T09:22:59.148481Z","shell.execute_reply":"2025-04-24T09:23:02.203796Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import zipfile\n\n#extracting the ZIP file\nzip_path = '/kaggle/input/dogs-vs-cats/train.zip'\nextract_dir = '/kaggle/working/'\n\nwith zipfile.ZipFile(zip_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_dir)\n    \n#extracting the ZIP file\nzip_path = '/kaggle/input/dogs-vs-cats/test1.zip'\nextract_dir = '/kaggle/working/'\n\nwith zipfile.ZipFile(zip_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_dir)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T16:52:27.057062Z","iopub.execute_input":"2025-04-24T16:52:27.057314Z","iopub.status.idle":"2025-04-24T16:52:39.367330Z","shell.execute_reply.started":"2025-04-24T16:52:27.057295Z","shell.execute_reply":"2025-04-24T16:52:39.366462Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision import transforms\nimport os\nimport cv2\nfrom PIL import Image\nimport torch.nn.functional as F","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T16:52:39.368599Z","iopub.execute_input":"2025-04-24T16:52:39.368860Z","iopub.status.idle":"2025-04-24T16:52:49.128918Z","shell.execute_reply.started":"2025-04-24T16:52:39.368838Z","shell.execute_reply":"2025-04-24T16:52:49.128166Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMG_SIZE = 128\n\ntransform = transforms.Compose([\n    transforms.Resize((IMG_SIZE, IMG_SIZE)),\n    transforms.ToTensor(),\n    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n])\n\nclass DogCatData(Dataset):\n    def __init__(self, img_dir, IMG_SIZE = 32, transform = None):\n        self.img_dir = img_dir\n        self.file_names = sorted(os.listdir(img_dir))\n        self.transform = transform\n    def __getitem__(self, idx):\n        file_name = self.file_names[idx]\n        img = cv2.imread(os.path.join(self.img_dir, file_name))\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n        # 1 = dog, 0 = cat\n        label = 0 if file_name.startswith(\"cat\") else 1\n        \n        img = Image.fromarray(img)  # 🔥 THIS LINE FIXES THE ERROR\n\n        transformed_img = self.transform(img)\n\n\n\n        return transformed_img, label\n        \n    def __len__(self):\n        return len(self.file_names)\n        \n        ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T16:52:49.129738Z","iopub.execute_input":"2025-04-24T16:52:49.130080Z","iopub.status.idle":"2025-04-24T16:52:49.136082Z","shell.execute_reply.started":"2025-04-24T16:52:49.130056Z","shell.execute_reply":"2025-04-24T16:52:49.135427Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"working_dir = \"/kaggle/working/train/\"\n\ntrain_data = DogCatData(working_dir, IMG_SIZE, transform)\ntrain_loader = DataLoader(train_data, shuffle = True, batch_size = 4)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T16:52:49.138158Z","iopub.execute_input":"2025-04-24T16:52:49.138502Z","iopub.status.idle":"2025-04-24T16:52:49.270091Z","shell.execute_reply.started":"2025-04-24T16:52:49.138478Z","shell.execute_reply":"2025-04-24T16:52:49.269354Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class DogCatModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.conv1 = nn.Conv2d(3, 32, kernel_size = (3,3), padding = 1) \n        self.conv2 = nn.Conv2d(32, 64, kernel_size = (3,3), padding = 1) \n        self.fc1 = nn.Linear(128 * 128 * 64, 128)\n        self.fc2 = nn.Linear(128, 2)\n\n    def forward(self, x):\n        x = F.relu(self.conv1(x))\n        x = F.relu(self.conv2(x))\n        x = x.view(x.size(0), -1)  # Flatten\n        x = F.relu(self.fc1(x))\n        x = self.fc2(x)\n        return x","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T17:01:58.240584Z","iopub.execute_input":"2025-04-24T17:01:58.241315Z","iopub.status.idle":"2025-04-24T17:01:58.246245Z","shell.execute_reply.started":"2025-04-24T17:01:58.241293Z","shell.execute_reply":"2025-04-24T17:01:58.245513Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = DogCatModel().to(device)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T17:05:05.682615Z","iopub.execute_input":"2025-04-24T17:05:05.682932Z","iopub.status.idle":"2025-04-24T17:05:07.301278Z","shell.execute_reply.started":"2025-04-24T17:05:05.682906Z","shell.execute_reply":"2025-04-24T17:05:07.300688Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"epoch = 5\nloss_fn = nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(model.parameters(), lr = 0.01)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T17:07:29.363842Z","iopub.execute_input":"2025-04-24T17:07:29.364591Z","iopub.status.idle":"2025-04-24T17:07:29.368392Z","shell.execute_reply.started":"2025-04-24T17:07:29.364565Z","shell.execute_reply":"2025-04-24T17:07:29.367608Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in range(epoch):\n    model.train()\n    total_loss = 0.0\n    j = 0\n    for images, labels in train_loader:\n        images = images.to(device)\n        labels = labels.to(device)\n        \n        optimizer.zero_grad()\n        y_pred = model(images)\n        \n        loss = loss_fn(y_pred, labels)\n        loss.backward()\n        optimizer.step()\n\n        total_loss += loss\n        if j%1000 == 0:\n            print(j, \"loss:\", loss)\n        j+=1\n    print(f\"Epoch: {i} Total loss: {total_loss}\")\n        ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T17:20:19.439673Z","iopub.execute_input":"2025-04-24T17:20:19.440329Z","iopub.status.idle":"2025-04-24T17:29:41.914493Z","shell.execute_reply.started":"2025-04-24T17:20:19.440303Z","shell.execute_reply":"2025-04-24T17:29:41.913694Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ntorch.save(model.state_dict(), \"model.pth\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T17:30:32.657706Z","iopub.execute_input":"2025-04-24T17:30:32.658278Z","iopub.status.idle":"2025-04-24T17:30:33.737995Z","shell.execute_reply.started":"2025-04-24T17:30:32.658256Z","shell.execute_reply":"2025-04-24T17:30:33.737222Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def sort_int(n):\n    n = n.split(\".\")[0]\n    return int(n)\n\n\nclass DogCatDataTest(Dataset):\n    def __init__(self, img_dir, IMG_SIZE = 32, transform = None):\n        self.img_dir = img_dir\n        self.file_names = sorted(os.listdir(img_dir), key=sort_int)\n        self.transform = transform\n    def __getitem__(self, idx):\n        file_name = self.file_names[idx]\n        img = cv2.imread(os.path.join(self.img_dir, file_name))\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n        img = Image.fromarray(img)  # 🔥 THIS LINE FIXES THE ERROR\n        transformed_img = self.transform(img)\n        return file_name, transformed_img\n        \n    def __len__(self):\n        return len(self.file_names)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T18:00:32.198417Z","iopub.execute_input":"2025-04-24T18:00:32.198943Z","iopub.status.idle":"2025-04-24T18:00:32.204346Z","shell.execute_reply.started":"2025-04-24T18:00:32.198921Z","shell.execute_reply":"2025-04-24T18:00:32.203740Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"working_dir = \"/kaggle/working/test1/\"\n\ntest_data = DogCatDataTest(working_dir, IMG_SIZE, transform)\ntest_loader = DataLoader(test_data, batch_size = 4)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T18:00:33.266731Z","iopub.execute_input":"2025-04-24T18:00:33.267023Z","iopub.status.idle":"2025-04-24T18:00:33.283691Z","shell.execute_reply.started":"2025-04-24T18:00:33.267003Z","shell.execute_reply":"2025-04-24T18:00:33.282995Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"name = []\nvalue = []\nl = 0\nfor file_name, images in test_loader:\n    l+=1\n    images = images.to(device)\n    \n    y_pred = model(images)\n\n    predicted = torch.argmax(y_pred, dim=1)\n\n    predicted_np = predicted.cpu().numpy()\n\n    for temp in range(len(predicted_np)):\n        name.append(int(file_name[temp].split(\".\")[0]))\n        value.append(predicted_np[temp])\n    \n    \n    if l%500 == 0:\n        print(l)\n    \nprint(len(li))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T18:07:31.865330Z","iopub.execute_input":"2025-04-24T18:07:31.865575Z","iopub.status.idle":"2025-04-24T18:08:29.560781Z","shell.execute_reply.started":"2025-04-24T18:07:31.865560Z","shell.execute_reply":"2025-04-24T18:08:29.560008Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from matplotlib import pyplot as plt\nloc = \"/kaggle/working/test1/\"\nfile_name = \"1000.jpg\"\nimg = cv2.imread(os.path.join(loc, file_name))\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\nplt.imshow(img)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T17:46:07.601877Z","iopub.execute_input":"2025-04-24T17:46:07.602480Z","iopub.status.idle":"2025-04-24T17:46:07.768585Z","shell.execute_reply.started":"2025-04-24T17:46:07.602455Z","shell.execute_reply":"2025-04-24T17:46:07.767807Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(test_loader)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T17:50:49.639581Z","iopub.execute_input":"2025-04-24T17:50:49.639847Z","iopub.status.idle":"2025-04-24T17:50:49.644608Z","shell.execute_reply.started":"2025-04-24T17:50:49.639828Z","shell.execute_reply":"2025-04-24T17:50:49.644012Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"name_arr = np.array(name)\nvalue_arr = np.array(value)\n\ndf = pd.DataFrame({\"id\" : name_arr, \"label\" : value_arr})\ndf.to_csv(\"foo.csv\", index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T18:09:19.379147Z","iopub.execute_input":"2025-04-24T18:09:19.379695Z","iopub.status.idle":"2025-04-24T18:09:19.414132Z","shell.execute_reply.started":"2025-04-24T18:09:19.379673Z","shell.execute_reply":"2025-04-24T18:09:19.413407Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"name[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-24T18:09:25.719615Z","iopub.execute_input":"2025-04-24T18:09:25.719875Z","iopub.status.idle":"2025-04-24T18:09:25.724650Z","shell.execute_reply.started":"2025-04-24T18:09:25.719856Z","shell.execute_reply":"2025-04-24T18:09:25.723911Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}