{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":3649,"databundleVersionId":46718,"sourceType":"competition"},{"sourceId":10835220,"sourceType":"datasetVersion","datasetId":6728610}],"dockerImageVersionId":30887,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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-02-10T04:16:39.772394Z","iopub.execute_input":"2025-02-10T04:16:39.772719Z","iopub.status.idle":"2025-02-10T04:16:40.147908Z","shell.execute_reply.started":"2025-02-10T04:16:39.77269Z","shell.execute_reply":"2025-02-10T04:16:40.147158Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd # for reading csv file\n\n#train and test images are .7z archives, we need to unpack them\n!pip install py7zr\n\nfrom py7zr import unpack_7zarchive\n# py7zr: A Python library to handle .7z archive files.\nimport shutil\n\n#Before using, we need to register unpack format\n# The shutil.unpack_archive() function does not support .7z archives by default.\n# We register the .7z format with shutil so that it can use py7zr internally to extract .7z files\nshutil.register_unpack_format('7zip', ['.7z'], unpack_7zarchive)\n# '7zip' → A custom name for the format (can be anything).\n# ['.7z'] → Specifies that this handler will be used for .7z files.\n# unpack_7zarchive → The function that will handle the extraction.\n# Now, shutil.unpack_archive() will recognize .7z files just like .zip or .tar.gz files.\n\n#unpack train images in /kaggle/working or /kaggle/temp\n# Extracts the contents of train.7z.\n# Saves the extracted files in /kaggle/temp/.\nshutil.unpack_archive('/kaggle/input/cifar-10/train.7z', '/kaggle/temp/')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T00:15:04.734638Z","iopub.execute_input":"2025-02-24T00:15:04.734945Z","iopub.status.idle":"2025-02-24T00:15:08.085079Z","shell.execute_reply.started":"2025-02-24T00:15:04.734922Z","shell.execute_reply":"2025-02-24T00:15:08.08369Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nif torch.cuda.is_available():\n    print(\"on GPU\")\n    device=torch.device(type=\"cuda\", index=0)\nelse:\n    print(\"on CPU\")\n    device=torch.device(type=\"cpu\", index=0)  \n\n# index=0 is used to specify which GPU (in this case, the first one)\n# to use in PyTorch when multiple CUDA-capable GPUs are present on the\n# system. If only one GPU exists, it will refer to that one, and if no \n# GPUs are available, the code defaults to using the CPU.\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T00:15:20.698599Z","iopub.execute_input":"2025-02-24T00:15:20.698899Z","iopub.status.idle":"2025-02-24T00:15:20.704375Z","shell.execute_reply.started":"2025-02-24T00:15:20.698876Z","shell.execute_reply":"2025-02-24T00:15:20.703253Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_label=pd.read_csv(\"/kaggle/input/cifar-10/trainLabels.csv\",header='infer')\nclasses = train_label['label'].unique()\nprint(classes)\n\nname2num={}\ni=0\nfor name in classes:\n    name2num[name]=i\n    i = i + 1\n    print(f'{name}:{name2num[name]}')\nprint(\"------------------\")\n\nnum2name={}\nfor i in range(len(classes)):\n    num2name[i]=classes[i]\n    print(f'{i}:{num2name[i]}')\nprint(\"------------------\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T00:15:22.451682Z","iopub.execute_input":"2025-02-24T00:15:22.451993Z","iopub.status.idle":"2025-02-24T00:15:22.480113Z","shell.execute_reply.started":"2025-02-24T00:15:22.451965Z","shell.execute_reply":"2025-02-24T00:15:22.479289Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"WHY \"antialiasing\" : \n\nIn the context of PyTorch, \"antialiasing\" usually refers to techniques used to reduce the visual artifacts that can occur when rendering images or when processing images in neural networks, particularly convolutional neural networks (CNNs).\n\nAntialiasing techniques can smooth out the edges of images or signals to prevent aliasing effects, which result in jagged or distorted visuals. In PyTorch, you might encounter antialiasing in the context of image transformations, such as resizing or downsampling, where methods are applied to ensure that the resulting image remains clear and retains detail without introducing distortions.\n\nFor example, when using functions such as torch.nn.functional.interpolate for resizing images, you can specify modes that incorporate antialiasing. Antialiasing can be particularly important in tasks such as image classification, style transfer, or generative tasks, where the quality of the input images significantly affects the performance of the model.","metadata":{}},{"cell_type":"markdown","source":"##Why read_image  :\n-- CIFAR-10 Dataset\n- Format: CIFAR-10 is stored in a binary format (.bin files) or compressed archives (.tar.gz or .7z).\n- Data Type: It contains color images (RGB, 32×32 pixels).\n- Requirement: Since images are stored in raw binary form, we need to explicitly read and decode them before processing.\n- Solution: We use functions like read_image() to read and decode the raw data.\n- 🔹 MNIST Dataset\n- Format: MNIST is stored in NumPy-like format (.idx files), which is a structured format for storing arrays.\n- Data Type: It contains grayscale images (28×28 pixels).\n- Requirement: Libraries like torchvision or tensorflow.keras.datasets can directly load the dataset into NumPy arrays or tensors.\n- Solution: We don't need read_image() because these frameworks automatically handle the data loading.\n","metadata":{}},{"cell_type":"code","source":"from torch.utils.data import Dataset # require custom dataset.\nfrom torch.utils.data import DataLoader\nimport os\nfrom torchvision.io import read_image # to read image file\n#  it will also going to convert image into tensor (c, h, w)\n# but it will not apply normalization(apply only 2 case)\nfrom torchvision.transforms import ToTensor, Normalize, Resize, Compose\n# compose for applying multiplre tranform.\n\nclass TrainDataset(Dataset):\n    def __init__(self, imgpath, labelpath):\n        super().__init__()\n        self.imgpath=imgpath\n        self.labelpath=labelpath\n        self.labels=pd.read_csv(labelpath, header='infer')\n        self.transform=Compose([Resize((224,224), antialias=True), Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])])\n        # here we want to apply z-score normalization, create pipeline by compose.\n    \n    def __len__(self):\n        return self.labels.shape[0]\n    \n    def __getitem__(self,idx):\n        finalpath=os.path.join(self.imgpath,str(idx+1))+'.png'\n        img=read_image(finalpath)/255 # shape(3,32,32) then /255\n        img=self.transform(img) # shape (3,224,224)\n        label=self.labels.iloc[idx,1]\n        label=name2num[label]\n        return img,label\n\ntraindataset=TrainDataset('/kaggle/temp/train','/kaggle/input/cifar-10/trainLabels.csv')        \n        \nbatch_size=64    \ntraindataloader=DataLoader(dataset=traindataset, batch_size=batch_size)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T01:40:40.432582Z","iopub.execute_input":"2025-02-24T01:40:40.432866Z","iopub.status.idle":"2025-02-24T01:40:40.453634Z","shell.execute_reply.started":"2025-02-24T01:40:40.432844Z","shell.execute_reply":"2025-02-24T01:40:40.452879Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.nn as nn\nfrom torchvision.models import mobilenet_v3_large, MobileNet_V3_Large_Weights\n# mobilenet_v3_large(architecture): Loads the MobileNetV3-Large architecture.\n# MobileNet_V3_Large_Weights(parameters): Provides pre-trained weights for MobileNetV3-Large.class \nclass Cifar10Net(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.pretrainednet=mobilenet_v3_large(weights=MobileNet_V3_Large_Weights.DEFAULT)\n        # Loads MobileNetV3-Large with pre-trained weights (DEFAULT loads the best available weights).\n        # MobileNetV3 is a lightweight convolutional neural network (CNN) optimized for mobile and embedded vision applications.\n        self.pretrainednet.classifier=nn.Sequential(\n        # The original classifier layer of MobileNetV3-Large is replaced to match CIFAR-10 classification\n            nn.Linear(in_features=960, out_features=1280, \n                   bias=True),nn.Hardswish(), \n            # nn.Hardswish(): Activation function (similar to ReLU but smoother).\n            nn.Dropout(p=0.2, inplace=True), \n            nn.Linear(in_features=1280, out_features=10, \n                      bias=True)\n        )\n        \n    def forward(self,x):\n        # shape of x (64, 3, 224, 224)\n        x=self.pretrainednet(x)\n        return x # return(64,10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T00:21:41.760143Z","iopub.execute_input":"2025-02-24T00:21:41.760461Z","iopub.status.idle":"2025-02-24T00:21:41.765868Z","shell.execute_reply.started":"2025-02-24T00:21:41.760436Z","shell.execute_reply":"2025-02-24T00:21:41.765144Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def train_one_epoch(dataloader, model,loss_fn, optimizer):\n    model.train()\n    track_loss=0\n    num_correct=0\n    num_param=0\n    \n    for i, (imgs, labels) in enumerate(dataloader):\n        imgs=imgs.to(device)\n        labels=labels.to(device)\n        pred=model(imgs)\n                    \n        loss=loss_fn(pred,labels)\n        track_loss+=loss.item()\n        num_correct+=(torch.argmax(pred,dim=1)==labels).type(torch.float).sum().item()\n        \n        running_loss=round(track_loss/(i+(imgs.shape[0]/batch_size)),2)\n        running_acc=round((num_correct/((i*batch_size+imgs.shape[0])))*100,2)\n        \n        loss.backward()\n        optimizer.step()\n        optimizer.zero_grad()\n\n        if i%100==0:\n            print(\"Batch:\", i+1, \"/\",len(dataloader), \"Running Loss:\",running_loss, \"Running Accuracy:\",running_acc)\n            \n    epoch_loss=running_loss\n    epoch_acc=running_acc\n    return epoch_loss, epoch_acc","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T00:21:43.986203Z","iopub.execute_input":"2025-02-24T00:21:43.986528Z","iopub.status.idle":"2025-02-24T00:21:43.992428Z","shell.execute_reply.started":"2025-02-24T00:21:43.986501Z","shell.execute_reply":"2025-02-24T00:21:43.991631Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model=Cifar10Net()\nmodel=model.to(device)\n\nfor param in model.pretrainednet.features.parameters():\n    param.requires_grad=False # means they will not take part in backprop.\n# model.pretrainednet.features refers to the feature extraction layers of MobileNetV3.\n# The classifier layer (model.pretrainednet.classifier) remains trainable, so the network learns to classify CIFAR-10 images\n\nloss_fn=nn.CrossEntropyLoss()\nlr=0.001\noptimizer=torch.optim.Adam(params=model.parameters(), lr=lr)\nn_epochs=15\n\nfor i in range(n_epochs):\n    print(\"Epoch No:\",i+1)\n    train_epoch_loss, train_epoch_acc=train_one_epoch(traindataloader,model,loss_fn,optimizer)\n    print(\"Training:\", \"Epoch Loss:\", train_epoch_loss, \"Epoch Accuracy:\", train_epoch_acc)\n    print(\"--------------------------------------------------\")\n\nfor param in model.pretrainednet.features.parameters():\n    param.requires_grad=True\n# This unfreezes all feature extraction layers of MobileNetV3.\n\nfor i in range(n_epochs):\n    print(\"Epoch No:\",i+1)\n    train_epoch_loss, train_epoch_acc=train_one_epoch(traindataloader,model,loss_fn,optimizer)\n    print(\"Training:\", \"Epoch Loss:\", train_epoch_loss, \"Epoch Accuracy:\", train_epoch_acc)\n    print(\"--------------------------------------------------\")\n\n# First, we train only the classifier → avoids disrupting pretrained features.\n# ✔ Then, we fine-tune the entire network → adapts features specifically for CIFAR-10.\n# ✔ This technique is called Transfer Learning with Fine-Tuning.","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T00:21:46.933454Z","iopub.execute_input":"2025-02-24T00:21:46.933786Z","iopub.status.idle":"2025-02-24T01:19:31.879116Z","shell.execute_reply.started":"2025-02-24T00:21:46.933757Z","shell.execute_reply":"2025-02-24T01:19:31.878309Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Save the trained model\ntorch.save(model.state_dict(), \"cifar10_Mobilenet_Large.pth\")\nprint(\"Model saved successfully!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T01:21:10.611067Z","iopub.execute_input":"2025-02-24T01:21:10.611384Z","iopub.status.idle":"2025-02-24T01:21:10.668961Z","shell.execute_reply.started":"2025-02-24T01:21:10.61136Z","shell.execute_reply":"2025-02-24T01:21:10.668245Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision.models import resnet18, ResNet18_Weights\n\n# Device Configuration\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# Define the CIFAR-10 model using ResNet-18\nclass Cifar10Net(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.pretrainednet = resnet18(weights=ResNet18_Weights.DEFAULT)  # Load ResNet-18 with pretrained weights\n        \n        # Modify the final fully connected (fc) layer for CIFAR-10 classification\n        in_features = self.pretrainednet.fc.in_features  # Get the input size of the last fc layer\n        self.pretrainednet.fc = nn.Sequential(\n            nn.Linear(in_features, 512),  # Added an intermediate layer for better learning\n            nn.ReLU(),\n            nn.Dropout(0.2),\n            nn.Linear(512, 10)  # Final output layer (10 classes for CIFAR-10)\n        )\n        \n    def forward(self, x):\n        return self.pretrainednet(x)\n\n# Training function\ndef train_one_epoch(dataloader, model, loss_fn, optimizer):\n    model.train()  # Ensure model is in training mode\n    track_loss, num_correct = 0, 0\n    \n    for i, (imgs, labels) in enumerate(dataloader):\n        imgs, labels = imgs.to(device), labels.to(device)\n        pred = model(imgs)\n        \n        loss = loss_fn(pred, labels)\n        track_loss += loss.item()\n        num_correct += (torch.argmax(pred, dim=1) == labels).type(torch.float).sum().item()\n        \n        running_loss = round(track_loss / (i + (imgs.shape[0] / batch_size)), 2)\n        running_acc = round((num_correct / ((i * batch_size + imgs.shape[0]))) * 100, 2)\n        \n        loss.backward()\n        optimizer.step()\n        optimizer.zero_grad()\n\n        if i % 100 == 0:\n            print(f\"Batch {i+1}/{len(dataloader)} - Loss: {running_loss}, Accuracy: {running_acc}%\")\n    \n    return running_loss, running_acc\n\n# Load model & move to device\nmodel = Cifar10Net().to(device)\n\n# ✅ Freeze feature extractor, train only classifier\nfor param in model.pretrainednet.parameters():\n    param.requires_grad = False\n\nfor param in model.pretrainednet.fc.parameters():\n    param.requires_grad = True  # Ensure classifier layers are trainable\n\n# ✅ Debug: Check trainable parameters\nfor name, param in model.named_parameters():\n    print(f\"{name} requires_grad: {param.requires_grad}\")\n\n# ✅ Optimizer only updates trainable parameters\noptimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=0.001)\nloss_fn = nn.CrossEntropyLoss()\nn_epochs = 15\n\n# Train only the classifier first\nprint(\"\\n🔹 Training Only Classifier...\\n\")\nfor i in range(n_epochs):\n    train_loss, train_acc = train_one_epoch(traindataloader, model, loss_fn, optimizer)\n    print(f\"Epoch {i+1}: Loss = {train_loss}, Accuracy = {train_acc}%\")\n    print(\"-\" * 50)\n\n# Save the trained classifier model\ntorch.save(model.state_dict(), \"cifar10_resnet18_classifier.pth\")\nprint(\"✅ Classifier model saved successfully!\\n\")\n\n# ✅ Unfreeze the whole model before fine-tuning\nfor param in model.pretrainednet.parameters():\n    param.requires_grad = True  \n\n# ✅ Debug: Check trainable parameters again\nfor name, param in model.named_parameters():\n    print(f\"{name} requires_grad: {param.requires_grad}\")\n\n# ✅ Reinitialize optimizer for fine-tuning\noptimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=0.0001)\n\n# Fine-Tuning on the entire model\nprint(\"\\n🔹 Fine-Tuning the Entire Model...\\n\")\nfor i in range(n_epochs):\n    train_loss, train_acc = train_one_epoch(traindataloader, model, loss_fn, optimizer)\n    print(f\"Fine-Tuning Epoch {i+1}: Loss = {train_loss}, Accuracy = {train_acc}%\")\n    print(\"-\" * 50)\n\n# Save the fine-tuned model\ntorch.save(model.state_dict(), \"cifar10_resnet18_finetuned.pth\")\nprint(\"✅ Fine-tuned model saved successfully!\\n\")\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T01:42:11.28215Z","iopub.execute_input":"2025-02-24T01:42:11.282497Z","iopub.status.idle":"2025-02-24T02:23:22.707377Z","shell.execute_reply.started":"2025-02-24T01:42:11.282465Z","shell.execute_reply":"2025-02-24T02:23:22.70643Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Save the trained model\ntorch.save(model.state_dict(), \"cifar10_resnet18.pth\")\nprint(\"Model saved successfully!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T02:25:11.29467Z","iopub.execute_input":"2025-02-24T02:25:11.295009Z","iopub.status.idle":"2025-02-24T02:25:11.366583Z","shell.execute_reply.started":"2025-02-24T02:25:11.294979Z","shell.execute_reply":"2025-02-24T02:25:11.365862Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#unpacking test images, there are 3 lacs images. This will take some time\nshutil.unpack_archive('/kaggle/input/cifar-10/test.7z', '/kaggle/temp/')\n\n#unregister unpack format, we are done with it\nshutil.unregister_unpack_format('7zip')#, ['.7z'], unpack_7zarchive)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T01:21:25.14662Z","iopub.execute_input":"2025-02-24T01:21:25.147032Z","iopub.status.idle":"2025-02-24T01:23:39.090106Z","shell.execute_reply.started":"2025-02-24T01:21:25.146997Z","shell.execute_reply":"2025-02-24T01:23:39.089415Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class TestDataset(Dataset):\n    def __init__(self, imgpath):\n        super().__init__()\n        self.imgpath=imgpath\n        _,_,self.files=next(os.walk(self.imgpath))\n        self.length=len(self.files)\n        self.transform=Compose([Resize((224,224), antialias=True), Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])])        \n    \n    def __len__(self):\n        return self.length\n    \n    def __getitem__(self,idx):\n        finalpath=os.path.join(self.imgpath,str(idx+1))+'.png'\n        img=read_image(finalpath)/255.0\n        img=self.transform(img)\n        return img\n\ntestdataset=TestDataset('/kaggle/temp/test/')\ntestdataloader=DataLoader(dataset=testdataset, batch_size=batch_size)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T01:23:58.163063Z","iopub.execute_input":"2025-02-24T01:23:58.163362Z","iopub.status.idle":"2025-02-24T01:23:58.408489Z","shell.execute_reply.started":"2025-02-24T01:23:58.163319Z","shell.execute_reply":"2025-02-24T01:23:58.407606Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def eval(dataloader, model,loss_fn, path):\n    model.eval()\n    data=pd.read_csv(path)\n    with torch.no_grad():\n        for i, imgs in enumerate(dataloader): # dataloader(64,3,224,224)\n            finalbatchpred=np.zeros(imgs.shape[0],dtype='object')\n            # will be size of 64 with all 0 and datatype object, so we can \n            # store anything as at last we have to store string.\n            imgs=imgs.to(device)\n            pred=model(imgs)\n            \n            pred=torch.argmax(pred,dim=1).type(torch.int).cpu()\n            for j,p in enumerate(pred):\n                finalbatchpred[j]=num2name[p.item()]\n            data.iloc[i*batch_size:i*batch_size+batch_size ,1]=finalbatchpred\n    \n    data.to_csv('submission_1.csv', index=False)\n    data.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T01:24:02.880915Z","iopub.execute_input":"2025-02-24T01:24:02.881215Z","iopub.status.idle":"2025-02-24T01:24:02.886471Z","shell.execute_reply.started":"2025-02-24T01:24:02.881189Z","shell.execute_reply":"2025-02-24T01:24:02.88564Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"eval(testdataloader, model,loss_fn, '/kaggle/input/cifar-10/sampleSubmission.csv')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T01:24:39.769493Z","iopub.execute_input":"2025-02-24T01:24:39.76981Z","iopub.status.idle":"2025-02-24T01:32:55.465227Z","shell.execute_reply.started":"2025-02-24T01:24:39.769774Z","shell.execute_reply":"2025-02-24T01:32:55.464563Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# For Resnet 18\n\ndef eval(dataloader, model,loss_fn, path):\n    model.eval()\n    data=pd.read_csv(path)\n    with torch.no_grad():\n        for i, imgs in enumerate(dataloader): # dataloader(64,3,224,224)\n            finalbatchpred=np.zeros(imgs.shape[0],dtype='object')\n            # will be size of 64 with all 0 and datatype object, so we can \n            # store anything as at last we have to store string.\n            imgs=imgs.to(device)\n            pred=model(imgs)\n            \n            pred=torch.argmax(pred,dim=1).type(torch.int).cpu()\n            for j,p in enumerate(pred):\n                finalbatchpred[j]=num2name[p.item()]\n            data.iloc[i*batch_size:i*batch_size+batch_size ,1]=finalbatchpred\n    \n    data.to_csv('submission_2.csv', index=False)\n    data.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T02:25:49.356892Z","iopub.execute_input":"2025-02-24T02:25:49.357169Z","iopub.status.idle":"2025-02-24T02:25:49.362607Z","shell.execute_reply.started":"2025-02-24T02:25:49.357147Z","shell.execute_reply":"2025-02-24T02:25:49.361679Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"eval(testdataloader, model,loss_fn, '/kaggle/input/cifar-10/sampleSubmission.csv')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-24T02:26:50.816226Z","iopub.execute_input":"2025-02-24T02:26:50.816564Z","iopub.status.idle":"2025-02-24T02:34:52.890764Z","shell.execute_reply.started":"2025-02-24T02:26:50.81653Z","shell.execute_reply":"2025-02-24T02:34:52.890078Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}