{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","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":30262,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Importing all necessary libraries\n\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.utils.data import DataLoader, Dataset\nfrom torch.utils.data import SubsetRandomSampler\n\nfrom PIL import Image\nimport cv2\n\nimport torchvision\nfrom torchvision import datasets\nfrom torchvision.transforms import ToTensor\nfrom torchvision.io import read_image\nfrom torchvision.transforms import Resize\nfrom torchvision.transforms import Compose\n\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2025-12-20T20:25:27.611639Z","iopub.execute_input":"2025-12-20T20:25:27.612045Z","iopub.status.idle":"2025-12-20T20:25:32.784222Z","shell.execute_reply.started":"2025-12-20T20:25:27.611957Z","shell.execute_reply":"2025-12-20T20:25:32.783169Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Unzipping all training images\n!unzip /kaggle/input/dogs-vs-cats/train.zip","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T20:25:32.787067Z","iopub.execute_input":"2025-12-20T20:25:32.787895Z","iopub.status.idle":"2025-12-20T20:25:45.469323Z","shell.execute_reply.started":"2025-12-20T20:25:32.787843Z","shell.execute_reply":"2025-12-20T20:25:45.468367Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Checking total Images in training data\nfiles = os.listdir(\"./train\")\nlen(files)","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:25:45.470584Z","iopub.execute_input":"2025-12-20T20:25:45.470884Z","iopub.status.idle":"2025-12-20T20:25:45.491424Z","shell.execute_reply.started":"2025-12-20T20:25:45.470843Z","shell.execute_reply":"2025-12-20T20:25:45.490655Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Reading image using PIL\nim_PIL = np.array(Image.open(\"./train/cat.0.jpg\"))\nim_PIL","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:25:45.492387Z","iopub.execute_input":"2025-12-20T20:25:45.492641Z","iopub.status.idle":"2025-12-20T20:25:45.517833Z","shell.execute_reply.started":"2025-12-20T20:25:45.492619Z","shell.execute_reply":"2025-12-20T20:25:45.516991Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Transforming Image np array into tensor using ToTensor\ntra = Compose([ToTensor()])\ntra_im_PIL = tra(im_PIL)\nprint(f\"Mean of Image channels: {tra_im_PIL.mean([1,2])}\")\nprint(f\"Std of Image channels: {tra_im_PIL.std([1,2])}\")\ntra_im_PIL","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:25:45.518935Z","iopub.execute_input":"2025-12-20T20:25:45.519282Z","iopub.status.idle":"2025-12-20T20:25:45.544101Z","shell.execute_reply.started":"2025-12-20T20:25:45.519259Z","shell.execute_reply":"2025-12-20T20:25:45.543142Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plotting Image \n\nplt.figure(figsize=(10,5))\nplt.subplot(1,2,1)\nplt.imshow(im_PIL)\nplt.title(\"Image before transformation\")\nplt.subplot(1,2,2)\nplt.imshow(tra_im_PIL.permute(1,2,0))\nplt.title(\"Image after transformation\")","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:25:45.545368Z","iopub.execute_input":"2025-12-20T20:25:45.545759Z","iopub.status.idle":"2025-12-20T20:25:46.009755Z","shell.execute_reply.started":"2025-12-20T20:25:45.545727Z","shell.execute_reply":"2025-12-20T20:25:46.008828Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Creating labels for images using dataframes\n\nLabels = pd.DataFrame(columns=[\"File_name\",\"Label\"])\nLabels[\"Label\"] = Labels[\"Label\"].astype(dtype=float)","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:25:46.012481Z","iopub.execute_input":"2025-12-20T20:25:46.012769Z","iopub.status.idle":"2025-12-20T20:25:46.031140Z","shell.execute_reply.started":"2025-12-20T20:25:46.012744Z","shell.execute_reply":"2025-12-20T20:25:46.029948Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Assigning labels to the images\ni=0\nfor  dirname, _, filenames in os.walk(\"./train\"):\n    for filename in filenames:\n        if filename.find(\"cat\") != -1:\n            Labels.loc[i,\"File_name\"] = filename\n            Labels.loc[i,\"Label\"] = 0\n        else:\n            Labels.loc[i,\"File_name\"] = filename\n            Labels.loc[i,\"Label\"] = 1\n        i += 1","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:25:46.032470Z","iopub.execute_input":"2025-12-20T20:25:46.032824Z","iopub.status.idle":"2025-12-20T20:26:17.845758Z","shell.execute_reply.started":"2025-12-20T20:25:46.032789Z","shell.execute_reply":"2025-12-20T20:26:17.844660Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# checking label file\nLabels.head()","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:26:17.846994Z","iopub.execute_input":"2025-12-20T20:26:17.847618Z","iopub.status.idle":"2025-12-20T20:26:17.862703Z","shell.execute_reply.started":"2025-12-20T20:26:17.847591Z","shell.execute_reply":"2025-12-20T20:26:17.861846Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# getting channels, Width and Height from the Images\n\nch = torch.zeros(Labels[\"File_name\"].shape[0])\nW = torch.zeros(Labels[\"File_name\"].shape[0])\nH = torch.zeros(Labels[\"File_name\"].shape[0])\ni=0\n\nfor fname in Labels[\"File_name\"]:\n    im = read_image(\"./train/\"+fname)\n    ch[i] = im.shape[0]\n    W[i] = im.shape[1]\n    H[i] = im.shape[2]\n    i += 1 ","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:26:17.863845Z","iopub.execute_input":"2025-12-20T20:26:17.864165Z","iopub.status.idle":"2025-12-20T20:27:03.379539Z","shell.execute_reply.started":"2025-12-20T20:26:17.864140Z","shell.execute_reply":"2025-12-20T20:27:03.378705Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# checking max/min of channels, width and height\n\nprint(f\"max channels: {torch.max(ch)}\")\nprint(f\"min channels: {torch.min(ch)}\")\nprint(f\"max Width: {torch.max(W)}\")\nprint(f\"min Width: {torch.min(W)}\")\nprint(f\"max Height: {torch.max(H)}\")\nprint(f\"min Height: {torch.min(H)}\\n\")\n\nprint(f\"min idx Width: {torch.argmin(W)}\")\nprint(f\"max idx Width: {torch.argmax(W)}\")\nprint(f\"min idx Height: {torch.argmin(H)}\")\nprint(f\"max idx Height: {torch.argmax(H)}\")","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:03.380618Z","iopub.execute_input":"2025-12-20T20:27:03.380854Z","iopub.status.idle":"2025-12-20T20:27:03.389990Z","shell.execute_reply.started":"2025-12-20T20:27:03.380833Z","shell.execute_reply":"2025-12-20T20:27:03.389064Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# getting indexes of images under width and height of 100\n\nminW = W<100\nminW_idx = minW.nonzero()\n\nminH = H<100\nminH_idx = minH.nonzero()","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:03.391366Z","iopub.execute_input":"2025-12-20T20:27:03.391762Z","iopub.status.idle":"2025-12-20T20:27:03.400793Z","shell.execute_reply.started":"2025-12-20T20:27:03.391725Z","shell.execute_reply":"2025-12-20T20:27:03.400067Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plotting Images with width less than 100\n\nresize = Resize((240,240))\nplt.figure(figsize = (15,15))\nfor i in range(15):\n    plt.subplot(5,3,i+1)\n    plt.imshow(resize(read_image(\"./train/\"+Labels.iloc[int(minW_idx[i]),0])).permute(1,2,0))","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:03.401862Z","iopub.execute_input":"2025-12-20T20:27:03.402147Z","iopub.status.idle":"2025-12-20T20:27:05.166178Z","shell.execute_reply.started":"2025-12-20T20:27:03.402125Z","shell.execute_reply":"2025-12-20T20:27:05.165173Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# checking mean and median of height and width of images\n\nprint(f\"Width mean: {W.mean()} and Height: {W.median()}\")\nprint(f\"Width mean: {H.mean()} and Height: {H.median()}\")","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:05.167346Z","iopub.execute_input":"2025-12-20T20:27:05.167617Z","iopub.status.idle":"2025-12-20T20:27:05.176183Z","shell.execute_reply.started":"2025-12-20T20:27:05.167592Z","shell.execute_reply":"2025-12-20T20:27:05.175047Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plotting height and Width of images\nplt.figure(figsize = (20,10))\nplt.scatter(W,H)","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:05.177334Z","iopub.execute_input":"2025-12-20T20:27:05.177639Z","iopub.status.idle":"2025-12-20T20:27:05.888045Z","shell.execute_reply.started":"2025-12-20T20:27:05.177610Z","shell.execute_reply":"2025-12-20T20:27:05.887174Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Data Traformation for Images using Compose\nData_transform = Compose([ToTensor(), Resize(size = (240,240))])","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:05.889586Z","iopub.execute_input":"2025-12-20T20:27:05.889854Z","iopub.status.idle":"2025-12-20T20:27:05.894209Z","shell.execute_reply.started":"2025-12-20T20:27:05.889828Z","shell.execute_reply":"2025-12-20T20:27:05.893027Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Creating Custom Dataset class for image and labels\n\nclass CvD_Data(Dataset):\n    def __init__(self, Label_file, Imgs_dir, transform_Img=None, transform_label=None):\n        self.Labels = Label_file\n        self.Imgs_dir = Imgs_dir\n        self.transform_Img = transform_Img\n        self.transform_label = transform_label\n    \n    def __len__(self):\n        return len(self.Labels)\n    \n    def __getitem__(self,idx):\n        \n        img_path = os.path.join(self.Imgs_dir, self.Labels.iloc[idx,0])\n        image = np.array(Image.open(img_path))\n        \n        label = self.Labels.iloc[idx,1]\n    \n        if self.transform_Img:\n            image = self.transform_Img(image)\n            \n        if self.transform_label:\n            label = torch.tensor(label, dtype=torch.float32)\n\n        return image, label\n            ","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:05.895391Z","iopub.execute_input":"2025-12-20T20:27:05.895674Z","iopub.status.idle":"2025-12-20T20:27:05.904534Z","shell.execute_reply.started":"2025-12-20T20:27:05.895649Z","shell.execute_reply":"2025-12-20T20:27:05.903802Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# creating Dataset object from training data \nDatasetCD = CvD_Data(Labels, \"./train\", Data_transform, ToTensor())","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:05.905517Z","iopub.execute_input":"2025-12-20T20:27:05.905771Z","iopub.status.idle":"2025-12-20T20:27:05.921273Z","shell.execute_reply.started":"2025-12-20T20:27:05.905748Z","shell.execute_reply":"2025-12-20T20:27:05.920262Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Splitting data into training and validation sets\n\nvalidation_split = 0.2\nrandom_seed= 42\n\ndataset_size = len(DatasetCD)\nindices = list(range(dataset_size))\nsplit = int(np.floor(validation_split * dataset_size))\n\nnp.random.seed(random_seed)\nnp.random.shuffle(indices)\n\ntrain_indices, val_indices = indices[split:], indices[:split]\n\n# Creating PT data samplers and loaders:\ntrain_sampler = SubsetRandomSampler(train_indices)\nvalid_sampler = SubsetRandomSampler(val_indices)\n\ntrain_loader = torch.utils.data.DataLoader(DatasetCD, batch_size=100, \n                                           sampler=train_sampler)\nvalidation_loader = torch.utils.data.DataLoader(DatasetCD, batch_size=100,\n                                                sampler=valid_sampler)","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:05.922254Z","iopub.execute_input":"2025-12-20T20:27:05.922493Z","iopub.status.idle":"2025-12-20T20:27:05.936153Z","shell.execute_reply.started":"2025-12-20T20:27:05.922472Z","shell.execute_reply":"2025-12-20T20:27:05.935308Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Creating a sample iterable for train_loader\nex_iter = iter(train_loader)\ndemo_imgs, demo_lbls = ex_iter.next()","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:05.937211Z","iopub.execute_input":"2025-12-20T20:27:05.937502Z","iopub.status.idle":"2025-12-20T20:27:06.391273Z","shell.execute_reply.started":"2025-12-20T20:27:05.937479Z","shell.execute_reply":"2025-12-20T20:27:06.390111Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(f\"Images shape: {demo_imgs.shape}\\nLabels shape: {demo_lbls.shape}\")\nprint(f\"Images dtype: {demo_imgs.dtype}\\nLabels dtype: {demo_lbls.dtype}\")","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:06.392921Z","iopub.execute_input":"2025-12-20T20:27:06.393232Z","iopub.status.idle":"2025-12-20T20:27:06.399854Z","shell.execute_reply.started":"2025-12-20T20:27:06.393207Z","shell.execute_reply":"2025-12-20T20:27:06.398921Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plotting sample training Images\nplt.figure(figsize=(10,10))\nfor i in range(9):\n  plt.subplot(3,3,i+1)\n  plt.imshow(demo_imgs[i].permute(1,2,0))\n  plt.title(demo_lbls[i].item())","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:06.405310Z","iopub.execute_input":"2025-12-20T20:27:06.405619Z","iopub.status.idle":"2025-12-20T20:27:07.466679Z","shell.execute_reply.started":"2025-12-20T20:27:06.405598Z","shell.execute_reply":"2025-12-20T20:27:07.465710Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# setting device to cuda if gpu is available\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ndevice","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:07.467754Z","iopub.execute_input":"2025-12-20T20:27:07.468052Z","iopub.status.idle":"2025-12-20T20:27:07.549085Z","shell.execute_reply.started":"2025-12-20T20:27:07.468020Z","shell.execute_reply":"2025-12-20T20:27:07.548151Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Creating our custom convolutional model\n\nclass CatsVDogs(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.convL1 = nn.Conv2d(3,6,5)\n        self.MaxPool = nn.MaxPool2d(2,2)\n        self.convL2 = nn.Conv2d(6,6,5)\n        self.convL3 = nn.Conv2d(6,12,3,2)\n        self.convL4 = nn.Conv2d(12,12,2,2)\n        self.fc1 = nn.Linear(12*7*7,256)\n        self.fc2 = nn.Linear(256,64)\n        self.fc3 = nn.Linear(64,1)\n    \n    def forward(self, X):\n        x = self.MaxPool(F.relu(self.convL1(X)))\n        x = self.MaxPool(F.relu(self.convL2(x)))\n        x = F.relu(self.convL3(x))\n        x = self.MaxPool(F.relu(self.convL4(x)))\n        x = x.view(-1,12*7*7)\n        x = F.relu(self.fc1(x))\n        x = F.relu(self.fc2(x))\n        x = torch.sigmoid(self.fc3(x))\n    \n        return x\n               ","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:07.550461Z","iopub.execute_input":"2025-12-20T20:27:07.551276Z","iopub.status.idle":"2025-12-20T20:27:07.561336Z","shell.execute_reply.started":"2025-12-20T20:27:07.551235Z","shell.execute_reply":"2025-12-20T20:27:07.560644Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_custom = CatsVDogs().to(device)\nprint(model_custom)","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:07.562467Z","iopub.execute_input":"2025-12-20T20:27:07.563055Z","iopub.status.idle":"2025-12-20T20:27:12.366447Z","shell.execute_reply.started":"2025-12-20T20:27:07.563021Z","shell.execute_reply":"2025-12-20T20:27:12.365209Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Total Parameters in custom model\n\ntotal_param = 0\nfor i in model_custom.parameters():\n    total_param = total_param + i.flatten().shape[0]\nprint(f\"Total Parameters in pretrained model: {total_param}\")","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:12.367750Z","iopub.execute_input":"2025-12-20T20:27:12.368413Z","iopub.status.idle":"2025-12-20T20:27:12.378271Z","shell.execute_reply.started":"2025-12-20T20:27:12.368306Z","shell.execute_reply":"2025-12-20T20:27:12.377401Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# setting loss and optimizer for custom model\nLoss_Custom = nn.BCELoss()\nOptim_Custom = torch.optim.Adam(model_custom.parameters(), lr=0.001)\n\nn_steps = len(train_loader)\nepochs = 3","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:12.379401Z","iopub.execute_input":"2025-12-20T20:27:12.381668Z","iopub.status.idle":"2025-12-20T20:27:12.386716Z","shell.execute_reply.started":"2025-12-20T20:27:12.381630Z","shell.execute_reply":"2025-12-20T20:27:12.385762Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Training Custom model \n\nfor epoch in range(epochs):\n    for i, (Imgs, Labels) in enumerate(train_loader):\n        \n        Imgs = Imgs.float()\n        Labels = Labels.view(-1,1)\n        \n        Imgs = Imgs.to(device)\n        Labels = Labels.to(device)\n        \n        Predicts = model_custom(Imgs)\n        loss = Loss_Custom(Predicts, Labels)\n        \n        \n        Optim_Custom.zero_grad()\n        loss.backward()\n        Optim_Custom.step()\n        \n        if (i+1) % 50 == 0 :\n            with torch.no_grad():\n                count = 0\n                for j in range(len(Labels)):\n                    if Predicts[j]>=0.5:\n                        Predicts[j] = 1\n                    else:\n                        Predicts[j] = 0\n                    if Predicts[j] == Labels[j]:\n                        count += 1    \n                acc = count/len(Labels)\n                acc = acc * 100\n                \n            print(f\"epoch: {epoch+1}/{epochs}, step: {i+1}/{n_steps}, loss: {loss.item():.4f}, Accuracy: {acc:.2f}\")","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:27:12.387940Z","iopub.execute_input":"2025-12-20T20:27:12.388299Z","iopub.status.idle":"2025-12-20T20:31:19.652784Z","shell.execute_reply.started":"2025-12-20T20:27:12.388253Z","shell.execute_reply":"2025-12-20T20:31:19.651737Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Testing Custom model on validation set\n\ncorrect = 0\nfor i, (Imgs, Labels) in enumerate(validation_loader):\n            \n    Imgs = Imgs.float()\n    Labels = Labels.view(-1,1)\n        \n    Imgs = Imgs.to(device)\n    Labels = Labels.to(device)\n    \n    model_custom.eval() \n        \n    with torch.no_grad():\n        Predicts = model_custom(Imgs)\n        \n        for j in range(len(Labels)):\n            if Predicts[j] >=0.5:\n                Predicts[j] = 1\n            else:\n                Predicts[j] = 0\n            \n            if Predicts[j] == Labels[j]:\n                correct += 1    \n                \nAcc_cust = correct/(len(validation_loader)*100)\nAcc_cust = Acc_cust*100\nprint(f\"Accuracy of Custom model over Validation set is: {Acc_cust:.2f}\")","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:31:19.654949Z","iopub.execute_input":"2025-12-20T20:31:19.655230Z","iopub.status.idle":"2025-12-20T20:31:40.812545Z","shell.execute_reply.started":"2025-12-20T20:31:19.655205Z","shell.execute_reply":"2025-12-20T20:31:40.811409Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Since our Custom model is doing slightly better than random guessing we will use pretrained model \n# using Shufflenet v2 x1.0 pretrained model\n\nshuffle_net_v2x1 = torchvision.models.shufflenet_v2_x1_0(pretrained=True, progress=True)\nprint(shuffle_net_v2x1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T20:31:40.813737Z","iopub.execute_input":"2025-12-20T20:31:40.814031Z","iopub.status.idle":"2025-12-20T20:31:41.133103Z","shell.execute_reply.started":"2025-12-20T20:31:40.814005Z","shell.execute_reply":"2025-12-20T20:31:41.132089Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# changing final fc layer to 1 since our problem is binary classification\n\nshuffle_net_v2x1.fc = nn.Linear(shuffle_net_v2x1.fc.in_features, 1)\nprint(shuffle_net_v2x1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T20:31:41.134421Z","iopub.execute_input":"2025-12-20T20:31:41.134801Z","iopub.status.idle":"2025-12-20T20:31:41.141643Z","shell.execute_reply.started":"2025-12-20T20:31:41.134765Z","shell.execute_reply":"2025-12-20T20:31:41.140757Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# creating shufflenet model \nmodel = shuffle_net_v2x1.to(device)","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:31:41.143491Z","iopub.execute_input":"2025-12-20T20:31:41.144061Z","iopub.status.idle":"2025-12-20T20:31:41.164159Z","shell.execute_reply.started":"2025-12-20T20:31:41.144026Z","shell.execute_reply":"2025-12-20T20:31:41.163392Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Total Parameters in Shuffle net pretrained model\n\ntotal_param = 0\nfor i in model.parameters():\n    total_param = total_param + i.flatten().shape[0]\nprint(f\"Total Parameters in pretrained model: {total_param}\")","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:31:41.165091Z","iopub.execute_input":"2025-12-20T20:31:41.165332Z","iopub.status.idle":"2025-12-20T20:31:41.171894Z","shell.execute_reply.started":"2025-12-20T20:31:41.165310Z","shell.execute_reply":"2025-12-20T20:31:41.170996Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# setting loss and optimizer for model\nLoss = nn.BCEWithLogitsLoss()\nOptim = torch.optim.Adam(model.parameters(), lr=0.001)\n\nn_steps = len(train_loader)\nepochs = 5","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:31:41.172999Z","iopub.execute_input":"2025-12-20T20:31:41.173272Z","iopub.status.idle":"2025-12-20T20:31:41.184731Z","shell.execute_reply.started":"2025-12-20T20:31:41.173250Z","shell.execute_reply":"2025-12-20T20:31:41.183810Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Training Shuffle net Pretrained model\n\nfor epoch in range(epochs):\n    for i, (imgs, labels) in enumerate(train_loader):\n        \n        imgs = imgs.float()\n        labels = labels.view(-1,1)\n        \n        imgs = imgs.to(device)\n        labels = labels.to(device)\n        \n        Predicts = model(imgs)\n        loss = Loss(Predicts, labels)\n        \n        Optim.zero_grad()\n        loss.backward()\n        Optim.step()\n        \n        if (i+1) % 50 == 0 :\n            with torch.no_grad():\n                pred = torch.sigmoid(Predicts).clone()   # applying sigmoid because final layer of shuffle net is linear\n                correct = 0\n                for j in range(len(labels)):\n                    if pred[j]>=0.5:                     # predicting output 0 or 1 if value is greater or less than 0.5\n                        pred[j] = 1\n                    else:\n                        pred[j] = 0\n                    if pred[j] == labels[j]:\n                        correct += 1    \n                acc = correct/len(labels)\n                acc = acc*100\n                \n            print(f\"epoch: {epoch+1}/{epochs}, step: {i+1}/{n_steps}, loss: {loss.item():.4f}, Accuracy: {acc:.2f}\")","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:31:41.186061Z","iopub.execute_input":"2025-12-20T20:31:41.186687Z","iopub.status.idle":"2025-12-20T20:40:51.989339Z","shell.execute_reply.started":"2025-12-20T20:31:41.186662Z","shell.execute_reply":"2025-12-20T20:40:51.988345Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Testing Shuffle net Pretrained model on Validation set\n\ncorrect = 0\nfor i, (Imgs, Labels) in enumerate(validation_loader):\n            \n    Imgs = Imgs.float()\n    Labels = Labels.view(-1,1)\n        \n    Imgs = Imgs.to(device)\n    Labels = Labels.to(device)\n    \n    model.eval() \n        \n    with torch.no_grad():\n        Predicts = model(Imgs)\n        pred = torch.sigmoid(Predicts).clone()\n        \n        for j in range(len(Labels)):\n            if pred[j] >=0.5:\n                pred[j] = 1\n            else:\n                pred[j] = 0\n            \n            if pred[j] == Labels[j]:\n                correct += 1  \n\nAcc_shuffle = correct/(len(validation_loader)*100)\nAcc_shuffle = Acc_shuffle*100\n\nprint(f\"Accuracy of shuffle net model over Validation set is: {Acc_shuffle:.2f}\")","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:40:51.992266Z","iopub.execute_input":"2025-12-20T20:40:51.992532Z","iopub.status.idle":"2025-12-20T20:41:14.007363Z","shell.execute_reply.started":"2025-12-20T20:40:51.992510Z","shell.execute_reply":"2025-12-20T20:41:14.006424Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# saving custom and shufflenet model\ntorch.save(model_custom,\"./Custom_Cnn\")\ntorch.save(model, \"./ShuffleNet_v2\")","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:41:14.008614Z","iopub.execute_input":"2025-12-20T20:41:14.008930Z","iopub.status.idle":"2025-12-20T20:41:14.080050Z","shell.execute_reply.started":"2025-12-20T20:41:14.008893Z","shell.execute_reply":"2025-12-20T20:41:14.079346Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!unzip /kaggle/input/dogs-vs-cats/test1.zip","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-20T20:41:14.081008Z","iopub.execute_input":"2025-12-20T20:41:14.081240Z","iopub.status.idle":"2025-12-20T20:41:21.177619Z","shell.execute_reply.started":"2025-12-20T20:41:14.081219Z","shell.execute_reply":"2025-12-20T20:41:21.176634Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Checking total Images in training data\ntest_files = os.listdir(\"./test1\")\nlen(test_files)","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:41:21.178943Z","iopub.execute_input":"2025-12-20T20:41:21.179241Z","iopub.status.idle":"2025-12-20T20:41:21.193931Z","shell.execute_reply.started":"2025-12-20T20:41:21.179213Z","shell.execute_reply":"2025-12-20T20:41:21.193059Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Classifying Images from test set using shuffle net\n\nsampleSubmission = pd.DataFrame(columns=[\"label\"])\n\ni=0\nfor  dirname, _, filenames in os.walk(\"./test1\"):\n    for filename in filenames:\n        image = np.array(Image.open(\"./test1/\"+filename))  # Image Loading\n        image = Data_transform(image)                      # data transformation\n        \n        image = image.float()\n        image = image.view(1,3,240,240)\n        image = image.to(device)\n        model.eval()\n        with torch.no_grad():\n            Predict = model(image)\n            pred = torch.sigmoid(Predict).clone()\n            if pred >= 0.5:\n                pred = 1\n            else:\n                pred = 0\n            \n            sampleSubmission.loc[i] = pred\n        \n        i += 1","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:41:21.195228Z","iopub.execute_input":"2025-12-20T20:41:21.195592Z","iopub.status.idle":"2025-12-20T20:43:56.457260Z","shell.execute_reply.started":"2025-12-20T20:41:21.195560Z","shell.execute_reply":"2025-12-20T20:43:56.456170Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sampleSubmission[\"id\"] = sampleSubmission.index","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:43:56.458817Z","iopub.execute_input":"2025-12-20T20:43:56.459167Z","iopub.status.idle":"2025-12-20T20:43:56.465255Z","shell.execute_reply.started":"2025-12-20T20:43:56.459138Z","shell.execute_reply":"2025-12-20T20:43:56.464247Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sampleSubmission = sampleSubmission[[\"id\",\"label\"]]\nsampleSubmission.head()","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:43:56.466469Z","iopub.execute_input":"2025-12-20T20:43:56.466736Z","iopub.status.idle":"2025-12-20T20:43:56.487164Z","shell.execute_reply.started":"2025-12-20T20:43:56.466713Z","shell.execute_reply":"2025-12-20T20:43:56.486249Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sampleSubmission.to_csv(\"sampleSubmission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2025-12-20T20:43:56.488324Z","iopub.execute_input":"2025-12-20T20:43:56.488672Z","iopub.status.idle":"2025-12-20T20:43:56.519598Z","shell.execute_reply.started":"2025-12-20T20:43:56.488639Z","shell.execute_reply":"2025-12-20T20:43:56.518977Z"},"trusted":true},"outputs":[],"execution_count":null}]}