{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3649,"databundleVersionId":46718,"sourceType":"competition"}],"dockerImageVersionId":31090,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoader\n\n# Data path (usually /kaggle/input/cifar-10 or similar)\ndata_dir = '/kaggle/input/cifar-10/'\n\n# Basic transform (baad mein advanced aug lagayenge)\ntransform = transforms.Compose([\n    transforms.ToTensor()\n])\n\n# Dataset objects\ntrainset = datasets.CIFAR10(root=data_dir, train=True, download=False, transform=transform)\ntestset = datasets.CIFAR10(root=data_dir, train=False, download=False, transform=transform)\n\n# DataLoader\ntrainloader = DataLoader(trainset, batch_size=64, shuffle=True)\ntestloader = DataLoader(testset, batch_size=64, shuffle=False)\n\n# Ek batch dekhne ke liye\nimages, labels = next(iter(trainloader))\nprint('Batch shape:', images.shape)\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-10-06T14:57:41.272727Z","iopub.execute_input":"2025-10-06T14:57:41.273036Z","iopub.status.idle":"2025-10-06T14:57:41.289469Z","shell.execute_reply.started":"2025-10-06T14:57:41.273016Z","shell.execute_reply":"2025-10-06T14:57:41.288436Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\n\n# Paths\ndata_dir = '/kaggle/input/cifar-10'\ntrain_csv = os.path.join(data_dir, 'trainLabels.csv')\ntrain_dir = os.path.join(data_dir, 'train')\ntest_dir = os.path.join(data_dir, 'test')\n\n# Read CSV for train labels\ntrain_df = pd.read_csv(train_csv)\n\n# Basic transform (baad mein advanced)\ntransform = transforms.Compose([\n    transforms.ToTensor()\n])\n\n# Custom Dataset class\nclass Cifar10Dataset(Dataset):\n    def __init__(self, df, img_dir, transform=None):\n        self.df = df\n        self.img_dir = img_dir\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        img_name = self.df.iloc[idx, 0] + '.png'\n        img_path = os.path.join(self.img_dir, img_name)\n        image = Image.open(img_path)\n        label = self.df.iloc[idx, 1]\n        # Convert label to integer 0-9\n        label = class_to_idx[label]\n        if self.transform:\n            image = self.transform(image)\n        return image, label\n\n# Label mapping\nclasses = sorted(train_df['label'].unique())\nclass_to_idx = {cls: idx for idx, cls in enumerate(classes)}\n\n# Datasets and loaders\ntrain_dataset = Cifar10Dataset(train_df, train_dir, transform)\ntrain_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\n\n# Test loader (labels nahi hotay test ke liye)\ntest_imgs = sorted(os.listdir(test_dir))\nprint('Sample train batch:')\nimages, labels = next(iter(train_loader))\nprint(images.shape, labels.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:02:56.606097Z","iopub.execute_input":"2025-10-06T15:02:56.606875Z","iopub.status.idle":"2025-10-06T15:02:56.63966Z","shell.execute_reply.started":"2025-10-06T15:02:56.606848Z","shell.execute_reply":"2025-10-06T15:02:56.638663Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_dir = '/kaggle/input/cifar-10-object-recognition-in-images'\ntrain_csv = os.path.join(data_dir, 'trainLabels.csv')\ntrain_dir = os.path.join(data_dir, 'train')\ntest_dir = os.path.join(data_dir, 'test')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:03:14.797914Z","iopub.execute_input":"2025-10-06T15:03:14.798669Z","iopub.status.idle":"2025-10-06T15:03:14.802464Z","shell.execute_reply.started":"2025-10-06T15:03:14.798644Z","shell.execute_reply":"2025-10-06T15:03:14.801544Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    print(dirname)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:03:23.50481Z","iopub.execute_input":"2025-10-06T15:03:23.505456Z","iopub.status.idle":"2025-10-06T15:03:23.512546Z","shell.execute_reply.started":"2025-10-06T15:03:23.505431Z","shell.execute_reply":"2025-10-06T15:03:23.51177Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_dir = '/kaggle/input/cifar-10'\ntrain_csv = os.path.join(data_dir, 'trainLabels.csv')\ntrain_dir = os.path.join(data_dir, 'train')\ntest_dir = os.path.join(data_dir, 'test')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:04:48.436749Z","iopub.execute_input":"2025-10-06T15:04:48.437439Z","iopub.status.idle":"2025-10-06T15:04:48.441623Z","shell.execute_reply.started":"2025-10-06T15:04:48.437417Z","shell.execute_reply":"2025-10-06T15:04:48.440556Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:04:52.508402Z","iopub.execute_input":"2025-10-06T15:04:52.508988Z","iopub.status.idle":"2025-10-06T15:04:52.512933Z","shell.execute_reply.started":"2025-10-06T15:04:52.508963Z","shell.execute_reply":"2025-10-06T15:04:52.511949Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_dir = '/kaggle/input/cifar-10'\ntrain_csv = os.path.join(data_dir, 'trainLabels.csv')\ntrain_dir = os.path.join(data_dir, 'train')\ntest_dir = os.path.join(data_dir, 'test')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:06:03.789203Z","iopub.execute_input":"2025-10-06T15:06:03.790048Z","iopub.status.idle":"2025-10-06T15:06:03.794638Z","shell.execute_reply.started":"2025-10-06T15:06:03.790018Z","shell.execute_reply":"2025-10-06T15:06:03.793739Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Read train labels CSV\ntrain_df = pd.read_csv(train_csv)\n\n# Label mapping\nclasses = sorted(train_df['label'].unique())\nclass_to_idx = {cls: idx for idx, cls in enumerate(classes)}\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:06:10.204767Z","iopub.execute_input":"2025-10-06T15:06:10.20535Z","iopub.status.idle":"2025-10-06T15:06:10.222961Z","shell.execute_reply.started":"2025-10-06T15:06:10.205328Z","shell.execute_reply":"2025-10-06T15:06:10.222201Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class Cifar10Dataset(Dataset):\n    def __init__(self, df, img_dir, transform=None):\n        self.df = df\n        self.img_dir = img_dir\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        img_name = self.df.iloc[idx, 0] + '.png'\n        img_path = os.path.join(self.img_dir, img_name)\n        image = Image.open(img_path)\n        label = self.df.iloc[idx, 1]\n        label = class_to_idx[label]   # string -> integer\n        if self.transform:\n            image = self.transform(image)\n        return image, label\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:06:49.989227Z","iopub.execute_input":"2025-10-06T15:06:49.98954Z","iopub.status.idle":"2025-10-06T15:06:49.995284Z","shell.execute_reply.started":"2025-10-06T15:06:49.989509Z","shell.execute_reply":"2025-10-06T15:06:49.994519Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Basic transform (baad mein advanced lagayenge)\ntransform = transforms.Compose([\n    transforms.ToTensor()\n])\n\n# Create dataset and dataloader\ntrain_dataset = Cifar10Dataset(train_df, train_dir, transform)\ntrain_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:10:59.765885Z","iopub.execute_input":"2025-10-06T15:10:59.766655Z","iopub.status.idle":"2025-10-06T15:10:59.77079Z","shell.execute_reply.started":"2025-10-06T15:10:59.76663Z","shell.execute_reply":"2025-10-06T15:10:59.769853Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images, labels = next(iter(train_loader))\nprint('Batch shape:', images.shape, labels.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:11:02.563065Z","iopub.execute_input":"2025-10-06T15:11:02.563699Z","iopub.status.idle":"2025-10-06T15:11:02.588563Z","shell.execute_reply.started":"2025-10-06T15:11:02.563671Z","shell.execute_reply":"2025-10-06T15:11:02.587595Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(train_df.head())\nprint(train_df.columns)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:11:08.124373Z","iopub.execute_input":"2025-10-06T15:11:08.124978Z","iopub.status.idle":"2025-10-06T15:11:08.132385Z","shell.execute_reply.started":"2025-10-06T15:11:08.124951Z","shell.execute_reply":"2025-10-06T15:11:08.131247Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class Cifar10Dataset(Dataset):\n    def __init__(self, df, img_dir, transform=None):\n        self.df = df\n        self.img_dir = img_dir\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        img_id = str(self.df.iloc[idx, 0])   # id is int, convert to str\n        img_name = img_id + '.png'           # filename e.g. 1.png\n        img_path = os.path.join(self.img_dir, img_name)\n        image = Image.open(img_path)\n        label = self.df.iloc[idx, 1]\n        label = class_to_idx[label]   # frog -> 0, truck -> 1, ...\n        if self.transform:\n            image = self.transform(image)\n        return image, label\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:15:48.080595Z","iopub.execute_input":"2025-10-06T15:15:48.081404Z","iopub.status.idle":"2025-10-06T15:15:48.087082Z","shell.execute_reply.started":"2025-10-06T15:15:48.081377Z","shell.execute_reply":"2025-10-06T15:15:48.086025Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"transform = transforms.Compose([\n    transforms.ToTensor()\n])\n\ntrain_dataset = Cifar10Dataset(train_df, train_dir, transform)\ntrain_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:15:52.046198Z","iopub.execute_input":"2025-10-06T15:15:52.046477Z","iopub.status.idle":"2025-10-06T15:15:52.051129Z","shell.execute_reply.started":"2025-10-06T15:15:52.046455Z","shell.execute_reply":"2025-10-06T15:15:52.050312Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images, labels = next(iter(train_loader))\nprint('Batch shape:', images.shape, labels.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:15:55.761698Z","iopub.execute_input":"2025-10-06T15:15:55.762476Z","iopub.status.idle":"2025-10-06T15:15:55.786643Z","shell.execute_reply.started":"2025-10-06T15:15:55.76245Z","shell.execute_reply":"2025-10-06T15:15:55.78542Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(train_df['id'].tail())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:18:37.787371Z","iopub.execute_input":"2025-10-06T15:18:37.788048Z","iopub.status.idle":"2025-10-06T15:18:37.792634Z","shell.execute_reply.started":"2025-10-06T15:18:37.788023Z","shell.execute_reply":"2025-10-06T15:18:37.79177Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimg_path = os.path.join(train_dir, str(train_df['id'].iloc[-1]) + '.png')\nprint(img_path, os.path.exists(img_path))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:18:42.176301Z","iopub.execute_input":"2025-10-06T15:18:42.176628Z","iopub.status.idle":"2025-10-06T15:18:42.181468Z","shell.execute_reply.started":"2025-10-06T15:18:42.176604Z","shell.execute_reply":"2025-10-06T15:18:42.180683Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\ndef has_image(row):\n    img_path = os.path.join(train_dir, str(row['id']) + '.png')\n    return os.path.exists(img_path)\n\n# Filter only those rows where image actually exists!\ntrain_df = train_df[train_df.apply(has_image, axis=1)].reset_index(drop=True)\nprint('Total images:', len(train_df))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:19:03.127076Z","iopub.execute_input":"2025-10-06T15:19:03.12737Z","iopub.status.idle":"2025-10-06T15:19:03.135784Z","shell.execute_reply.started":"2025-10-06T15:19:03.127347Z","shell.execute_reply":"2025-10-06T15:19:03.134952Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(train_dir)[:10])  # First 10 files dikhao\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:21:39.851971Z","iopub.execute_input":"2025-10-06T15:21:39.852252Z","iopub.status.idle":"2025-10-06T15:21:39.866753Z","shell.execute_reply.started":"2025-10-06T15:21:39.852235Z","shell.execute_reply":"2025-10-06T15:21:39.865674Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nfor dirname, dirnames, filenames in os.walk('/kaggle/input/cifar-10'):\n    print('DIR:', dirname)\n    print('DIRNAMES:', dirnames)\n    print('FILENAMES:', filenames[:10])  # first 10 files only\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:21:35.671533Z","iopub.execute_input":"2025-10-06T15:21:35.671813Z","iopub.status.idle":"2025-10-06T15:21:35.67802Z","shell.execute_reply.started":"2025-10-06T15:21:35.671793Z","shell.execute_reply":"2025-10-06T15:21:35.677326Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport py7zr\n\n# Train images extract karo\nwith py7zr.SevenZipFile('/kaggle/input/cifar-10/train.7z', mode='r') as z:\n    z.extractall(path='/kaggle/working/train')\n\n# Test images extract karo\nwith py7zr.SevenZipFile('/kaggle/input/cifar-10/test.7z', mode='r') as z:\n    z.extractall(path='/kaggle/working/test')\n\nprint('Train extract:', os.listdir('/kaggle/working/train')[:5])\nprint('Test extract:', os.listdir('/kaggle/working/test')[:5])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:22:05.463109Z","iopub.execute_input":"2025-10-06T15:22:05.463911Z","iopub.status.idle":"2025-10-06T15:24:47.253355Z","shell.execute_reply.started":"2025-10-06T15:22:05.463881Z","shell.execute_reply":"2025-10-06T15:24:47.252561Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install py7zr\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:25:28.297472Z","iopub.execute_input":"2025-10-06T15:25:28.297792Z","iopub.status.idle":"2025-10-06T15:25:31.698748Z","shell.execute_reply.started":"2025-10-06T15:25:28.297772Z","shell.execute_reply":"2025-10-06T15:25:31.697988Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import py7zr\nimport os\n\n# Train images extract karo\nwith py7zr.SevenZipFile('/kaggle/input/cifar-10/train.7z', mode='r') as z:\n    z.extractall(path='/kaggle/working/train')\n\n# Test images extract karo\nwith py7zr.SevenZipFile('/kaggle/input/cifar-10/test.7z', mode='r') as z:\n    z.extractall(path='/kaggle/working/test')\n\nprint('Train extract:', os.listdir('/kaggle/working/train')[:5])\nprint('Test extract:', os.listdir('/kaggle/working/test')[:5])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:25:50.444701Z","iopub.execute_input":"2025-10-06T15:25:50.444971Z","iopub.status.idle":"2025-10-06T15:28:30.260351Z","shell.execute_reply.started":"2025-10-06T15:25:50.444946Z","shell.execute_reply":"2025-10-06T15:28:30.259399Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(\"TRAIN inner folders/files:\", os.listdir('/kaggle/working/train'))\nprint(\"TEST inner folders/files:\", os.listdir('/kaggle/working/test'))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:29:52.642679Z","iopub.execute_input":"2025-10-06T15:29:52.643254Z","iopub.status.idle":"2025-10-06T15:29:52.648391Z","shell.execute_reply.started":"2025-10-06T15:29:52.643231Z","shell.execute_reply":"2025-10-06T15:29:52.647453Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_dir = '/kaggle/working/train/train'\ntest_dir = '/kaggle/working/test/test'\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:29:57.114225Z","iopub.execute_input":"2025-10-06T15:29:57.114581Z","iopub.status.idle":"2025-10-06T15:29:57.118436Z","shell.execute_reply.started":"2025-10-06T15:29:57.114546Z","shell.execute_reply":"2025-10-06T15:29:57.117621Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(train_dir)[:10])  # Yeh 1.png, 2.png, ... print karega\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:30:03.806885Z","iopub.execute_input":"2025-10-06T15:30:03.807188Z","iopub.status.idle":"2025-10-06T15:30:03.83771Z","shell.execute_reply.started":"2025-10-06T15:30:03.807164Z","shell.execute_reply":"2025-10-06T15:30:03.836852Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_dir = '/kaggle/working/train/train'\ntest_dir = '/kaggle/working/test/test'\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:30:11.432165Z","iopub.execute_input":"2025-10-06T15:30:11.432465Z","iopub.status.idle":"2025-10-06T15:30:11.436359Z","shell.execute_reply.started":"2025-10-06T15:30:11.432441Z","shell.execute_reply":"2025-10-06T15:30:11.435416Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:33:15.545312Z","iopub.execute_input":"2025-10-06T15:33:15.545882Z","iopub.status.idle":"2025-10-06T15:33:15.550014Z","shell.execute_reply.started":"2025-10-06T15:33:15.545856Z","shell.execute_reply":"2025-10-06T15:33:15.549188Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_csv = '/kaggle/input/cifar-10/trainLabels.csv'\ntrain_df = pd.read_csv(train_csv)\n\n# Label mapping\nclasses = sorted(train_df['label'].unique())\nclass_to_idx = {cls: idx for idx, cls in enumerate(classes)}\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:33:19.473431Z","iopub.execute_input":"2025-10-06T15:33:19.473724Z","iopub.status.idle":"2025-10-06T15:33:19.494747Z","shell.execute_reply.started":"2025-10-06T15:33:19.473703Z","shell.execute_reply":"2025-10-06T15:33:19.494075Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class Cifar10Dataset(Dataset):\n    def __init__(self, df, img_dir, transform=None):\n        self.df = df\n        self.img_dir = img_dir\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        img_id = str(self.df.iloc[idx, 0])\n        img_name = img_id + '.png'\n        img_path = os.path.join(self.img_dir, img_name)\n        image = Image.open(img_path)\n        label = self.df.iloc[idx, 1]\n        label = class_to_idx[label]\n        if self.transform:\n            image = self.transform(image)\n        return image, label\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:33:36.682216Z","iopub.execute_input":"2025-10-06T15:33:36.683104Z","iopub.status.idle":"2025-10-06T15:33:36.688558Z","shell.execute_reply.started":"2025-10-06T15:33:36.683069Z","shell.execute_reply":"2025-10-06T15:33:36.687722Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"transform = transforms.Compose([\n    transforms.ToTensor()\n])\ntrain_dataset = Cifar10Dataset(train_df, train_dir, transform)\ntrain_loader = DataLoader(train_dataset, batch_size=8, shuffle=True)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:34:54.97928Z","iopub.execute_input":"2025-10-06T15:34:54.979642Z","iopub.status.idle":"2025-10-06T15:34:54.984867Z","shell.execute_reply.started":"2025-10-06T15:34:54.979617Z","shell.execute_reply":"2025-10-06T15:34:54.983954Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images, labels = next(iter(train_loader))\nprint('Batch shape:', images.shape, labels.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:34:58.167142Z","iopub.execute_input":"2025-10-06T15:34:58.167426Z","iopub.status.idle":"2025-10-06T15:34:58.181346Z","shell.execute_reply.started":"2025-10-06T15:34:58.167405Z","shell.execute_reply":"2025-10-06T15:34:58.180406Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass SimpleConvNet(nn.Module):\n    def __init__(self, num_classes=10):\n        super(SimpleConvNet, self).__init__()\n        self.conv1 = nn.Conv2d(3, 32, 3, padding=1)\n        self.conv2 = nn.Conv2d(32, 64, 3, padding=1)\n        self.pool = nn.MaxPool2d(2, 2)\n        self.fc1 = nn.Linear(64 * 8 * 8, 128)\n        self.fc2 = nn.Linear(128, num_classes)\n\n    def forward(self, x):\n        x = self.pool(F.relu(self.conv1(x)))\n        x = self.pool(F.relu(self.conv2(x)))\n        x = x.view(x.size(0), -1)\n        x = F.relu(self.fc1(x))\n        x = self.fc2(x)\n        return x\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:35:06.77125Z","iopub.execute_input":"2025-10-06T15:35:06.771572Z","iopub.status.idle":"2025-10-06T15:35:06.778994Z","shell.execute_reply.started":"2025-10-06T15:35:06.771538Z","shell.execute_reply":"2025-10-06T15:35:06.778119Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = SimpleConvNet(num_classes=10)\nprint(model)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:35:46.175713Z","iopub.execute_input":"2025-10-06T15:35:46.176297Z","iopub.status.idle":"2025-10-06T15:35:46.186674Z","shell.execute_reply.started":"2025-10-06T15:35:46.176273Z","shell.execute_reply":"2025-10-06T15:35:46.185813Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = model.to(device)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:35:52.435137Z","iopub.execute_input":"2025-10-06T15:35:52.435412Z","iopub.status.idle":"2025-10-06T15:35:52.440959Z","shell.execute_reply.started":"2025-10-06T15:35:52.435392Z","shell.execute_reply":"2025-10-06T15:35:52.440242Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.optim as optim\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)  # ya AdamW bhi use ho sakta hai\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:36:10.626407Z","iopub.execute_input":"2025-10-06T15:36:10.627098Z","iopub.status.idle":"2025-10-06T15:36:10.631425Z","shell.execute_reply.started":"2025-10-06T15:36:10.627072Z","shell.execute_reply":"2025-10-06T15:36:10.630604Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=10)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:36:40.762083Z","iopub.execute_input":"2025-10-06T15:36:40.762637Z","iopub.status.idle":"2025-10-06T15:36:40.766437Z","shell.execute_reply.started":"2025-10-06T15:36:40.762612Z","shell.execute_reply":"2025-10-06T15:36:40.765632Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"num_epochs = 1  # Pehle 1 epoch test ke liye rakho\n\nfor epoch in range(num_epochs):\n    model.train()\n    running_loss = 0.0\n    for images, labels in train_loader:\n        images = images.to(device)\n        labels = labels.to(device)\n        \n        optimizer.zero_grad()\n        outputs = model(images)\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\n        \n        running_loss += loss.item() * images.size(0)\n    scheduler.step()\n    epoch_loss = running_loss / len(train_loader.dataset)\n    print(f'Epoch {epoch+1}/{num_epochs}, Loss: {epoch_loss:.4f}')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:37:46.567745Z","iopub.execute_input":"2025-10-06T15:37:46.568039Z","iopub.status.idle":"2025-10-06T15:38:21.316534Z","shell.execute_reply.started":"2025-10-06T15:37:46.568017Z","shell.execute_reply":"2025-10-06T15:38:21.315679Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport torch\n\nclass Cutout(object):\n    \"\"\"Randomly mask out square regions in an image.\"\"\"\n    def __init__(self, n_holes, length):\n        self.n_holes = n_holes  # Number of cutout regions\n        self.length = length    # Length of each square region\n\n    def __call__(self, img):\n        h = img.size(1)\n        w = img.size(2)\n\n        mask = np.ones((h, w), np.float32)\n\n        for n in range(self.n_holes):\n            y = np.random.randint(h)\n            x = np.random.randint(w)\n\n            y1 = np.clip(y - self.length // 2, 0, h)\n            y2 = np.clip(y + self.length // 2, 0, h)\n            x1 = np.clip(x - self.length // 2, 0, w)\n            x2 = np.clip(x + self.length // 2, 0, w)\n\n            mask[y1:y2, x1:x2] = 0.\n\n        mask = torch.from_numpy(mask)\n        mask = mask.expand_as(img)\n        img = img * mask\n        return img\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:39:08.558224Z","iopub.execute_input":"2025-10-06T15:39:08.558541Z","iopub.status.idle":"2025-10-06T15:39:08.565167Z","shell.execute_reply.started":"2025-10-06T15:39:08.558519Z","shell.execute_reply":"2025-10-06T15:39:08.564281Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torchvision import transforms\n\ntransform = transforms.Compose([\n    transforms.ToTensor(),\n    Cutout(n_holes=1, length=16),  # You can adjust length/n_holes for more/less cutout\n    # Baqi transforms (e.g. normalization) bhi yahan add kar sakte hain\n])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:40:30.339681Z","iopub.execute_input":"2025-10-06T15:40:30.339997Z","iopub.status.idle":"2025-10-06T15:40:30.344298Z","shell.execute_reply.started":"2025-10-06T15:40:30.339974Z","shell.execute_reply":"2025-10-06T15:40:30.343452Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import math\n\ndef get_cosine_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, num_cycles=0.5, last_epoch=-1):\n    def lr_lambda(current_step):\n        if current_step < num_warmup_steps:\n            return float(current_step) / float(max(1, num_warmup_steps))\n        # Cosine decay\n        progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))\n        return max(0.0, 0.5 * (1.0 + math.cos(math.pi * num_cycles * 2.0 * progress)))\n    return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda, last_epoch)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:40:35.475374Z","iopub.execute_input":"2025-10-06T15:40:35.476086Z","iopub.status.idle":"2025-10-06T15:40:35.481247Z","shell.execute_reply.started":"2025-10-06T15:40:35.476062Z","shell.execute_reply":"2025-10-06T15:40:35.480467Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"num_epochs = 1\nnum_training_steps = num_epochs * len(train_loader)\nnum_warmup_steps = 5 * len(train_loader)\n\nscheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:40:43.56316Z","iopub.execute_input":"2025-10-06T15:40:43.563442Z","iopub.status.idle":"2025-10-06T15:40:43.567536Z","shell.execute_reply.started":"2025-10-06T15:40:43.563421Z","shell.execute_reply":"2025-10-06T15:40:43.566723Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for epoch in range(num_epochs):\n    print(\"Epoch:\", epoch+1)\n    for batch_idx, (images, labels) in enumerate(train_loader):\n        print(\"Batch:\", batch_idx+1)\n        break   # Sirf ek batch test ke liye, taake ruk jaye\n    break       # Sirf ek epoch test ke liye, taake ruk jaye\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:42:44.09097Z","iopub.execute_input":"2025-10-06T15:42:44.091405Z","iopub.status.idle":"2025-10-06T15:42:44.107864Z","shell.execute_reply.started":"2025-10-06T15:42:44.091377Z","shell.execute_reply":"2025-10-06T15:42:44.106761Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:42:50.272722Z","iopub.execute_input":"2025-10-06T15:42:50.273038Z","iopub.status.idle":"2025-10-06T15:42:50.277878Z","shell.execute_reply.started":"2025-10-06T15:42:50.273017Z","shell.execute_reply":"2025-10-06T15:42:50.276884Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"num_epochs = 1      # (Agar test kar rahe ho to 1, warna 5-10 bhi rakh sakte ho)\nfor epoch in range(num_epochs):\n    model.train()\n    running_loss = 0.0\n    for batch_idx, (images, labels) in enumerate(train_loader):\n        images, labels = images.to(device), labels.to(device)\n        optimizer.zero_grad()\n        outputs = model(images)\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\n        scheduler.step()\n        running_loss += loss.item()\n        if batch_idx % 10 == 0:   # Har 10 batches baad print karo\n            print(f\"Epoch [{epoch+1}/{num_epochs}], Batch [{batch_idx+1}], Loss: {loss.item():.4f}\")\n    print(f\"Epoch [{epoch+1}] Avg Loss: {running_loss/len(train_loader):.4f}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:43:36.018322Z","iopub.execute_input":"2025-10-06T15:43:36.018643Z","iopub.status.idle":"2025-10-06T15:44:10.183916Z","shell.execute_reply.started":"2025-10-06T15:43:36.018618Z","shell.execute_reply":"2025-10-06T15:44:10.183123Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.eval()  # Model ko evaluation mode mein le aao\n\ncorrect = 0\ntotal = 0\n\nwith torch.no_grad():  # No gradient needed for eval\n    for images, labels in test_loader:    # test_loader zaroor define ho\n        images, labels = images.to(device), labels.to(device)\n        outputs = model(images)\n        _, predicted = torch.max(outputs, 1)\n        total += labels.size(0)\n        correct += (predicted == labels).sum().item()\n\naccuracy = 100 * correct / total\nprint(f'Test Accuracy: {accuracy:.2f}%')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:47:12.271073Z","iopub.execute_input":"2025-10-06T15:47:12.271382Z","iopub.status.idle":"2025-10-06T15:47:12.291288Z","shell.execute_reply.started":"2025-10-06T15:47:12.27136Z","shell.execute_reply":"2025-10-06T15:47:12.289976Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Ye code run karo (adjust karo agar folder name ya dataframe ka naam alag ho)\ntest_dataset = CIFAR10Dataset(test_df, test_img_dir, transform=transform)\ntest_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:48:36.943155Z","iopub.execute_input":"2025-10-06T15:48:36.94406Z","iopub.status.idle":"2025-10-06T15:48:36.957067Z","shell.execute_reply.started":"2025-10-06T15:48:36.944033Z","shell.execute_reply":"2025-10-06T15:48:36.956079Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Example: test_df, test_dir, transform (jese aapke paas hain)\ntest_dataset = Cifar10Dataset(test_df, test_dir, transform)\ntest_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:49:26.230763Z","iopub.execute_input":"2025-10-06T15:49:26.231076Z","iopub.status.idle":"2025-10-06T15:49:26.244216Z","shell.execute_reply.started":"2025-10-06T15:49:26.231051Z","shell.execute_reply":"2025-10-06T15:49:26.243069Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Example: test_df, test_dir, transform (jese aapke paas hain)\ntest_dataset = Cifar10Dataset(test_df, test_dir, transform)\ntest_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T15:49:30.040387Z","iopub.execute_input":"2025-10-06T15:49:30.041175Z","iopub.status.idle":"2025-10-06T15:49:30.054028Z","shell.execute_reply.started":"2025-10-06T15:49:30.041145Z","shell.execute_reply":"2025-10-06T15:49:30.052885Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_dataset = Cifar10Dataset(test_df, test_dir, transform)\ntest_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T14:50:07.838259Z","iopub.execute_input":"2025-10-06T14:50:07.83912Z","iopub.status.idle":"2025-10-06T14:50:07.851906Z","shell.execute_reply.started":"2025-10-06T14:50:07.83909Z","shell.execute_reply":"2025-10-06T14:50:07.850987Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_dataset = Cifar10Dataset(submission_df, test_dir, transform)\ntest_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T14:52:36.574281Z","iopub.execute_input":"2025-10-06T14:52:36.575099Z","iopub.status.idle":"2025-10-06T14:52:36.58774Z","shell.execute_reply.started":"2025-10-06T14:52:36.575074Z","shell.execute_reply":"2025-10-06T14:52:36.586712Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\n\ntest_dir = '/kaggle/working/test/test'\ntest_files = os.listdir(test_dir)\ntest_ids = [f.replace('.png', '') for f in test_files]   # Remove .png\ntest_df = pd.DataFrame({'id': test_ids})\nprint(test_df.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T16:12:23.408744Z","iopub.execute_input":"2025-10-06T16:12:23.409467Z","iopub.status.idle":"2025-10-06T16:12:23.610864Z","shell.execute_reply.started":"2025-10-06T16:12:23.409443Z","shell.execute_reply":"2025-10-06T16:12:23.610057Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.utils.data import Dataset, DataLoader\nfrom PIL import Image\nimport os\n\n# Custom Dataset class for test images\nclass TestCifar10Dataset(Dataset):\n    def __init__(self, df, img_dir, transform=None):\n        self.df = df\n        self.img_dir = img_dir\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        img_id = str(self.df.iloc[idx, 0])\n        img_name = img_id + '.png'\n        img_path = os.path.join(self.img_dir, img_name)\n        image = Image.open(img_path)\n        if self.transform:\n            image = self.transform(image)\n        return image, img_id\n\n# Ab test_dataset aur test_loader banao\ntest_dir = '/kaggle/working/test/test'\ntest_dataset = TestCifar10Dataset(test_df, test_dir, transform=transform)\ntest_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n\n# Ek batch nikal ke check karo:\nimages, ids = next(iter(test_loader))\nprint('Batch images shape:', images.shape)\nprint('Batch ids:', ids[:5])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T16:13:56.498142Z","iopub.execute_input":"2025-10-06T16:13:56.498449Z","iopub.status.idle":"2025-10-06T16:13:56.557524Z","shell.execute_reply.started":"2025-10-06T16:13:56.498427Z","shell.execute_reply":"2025-10-06T16:13:56.55671Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\n\nmodel.eval()  # Evaluation mode\nall_preds = []\nall_ids = []\n\nwith torch.no_grad():\n    for images, ids in test_loader:\n        images = images.to(device)\n        outputs = model(images)\n        preds = torch.argmax(outputs, dim=1).cpu().numpy()\n        all_preds.extend(preds)\n        all_ids.extend(ids)\n\nprint('Sample predictions:', list(zip(all_ids[:5], all_preds[:5])))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T16:14:53.165034Z","iopub.execute_input":"2025-10-06T16:14:53.165323Z","iopub.status.idle":"2025-10-06T16:17:31.986246Z","shell.execute_reply.started":"2025-10-06T16:14:53.165302Z","shell.execute_reply":"2025-10-06T16:17:31.9853Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\n\nsubmission = pd.DataFrame({\n    'id': all_ids,\n    'label': all_preds\n})\n\nsubmission.to_csv('submission.csv', index=False)\nprint(submission.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T16:19:06.570606Z","iopub.execute_input":"2025-10-06T16:19:06.570936Z","iopub.status.idle":"2025-10-06T16:19:07.366Z","shell.execute_reply.started":"2025-10-06T16:19:06.570912Z","shell.execute_reply":"2025-10-06T16:19:07.365158Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label_names = [\n    \"airplane\",      # 0\n    \"automobile\",    # 1\n    \"bird\",          # 2\n    \"cat\",           # 3\n    \"deer\",          # 4\n    \"dog\",           # 5\n    \"frog\",          # 6\n    \"horse\",         # 7\n    \"ship\",          # 8\n    \"truck\"          # 9\n]\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T16:25:21.652903Z","iopub.execute_input":"2025-10-06T16:25:21.653708Z","iopub.status.idle":"2025-10-06T16:25:21.657877Z","shell.execute_reply.started":"2025-10-06T16:25:21.653673Z","shell.execute_reply":"2025-10-06T16:25:21.657217Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"all_preds_text = [label_names[i] for i in all_preds]\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T16:25:29.484017Z","iopub.execute_input":"2025-10-06T16:25:29.484655Z","iopub.status.idle":"2025-10-06T16:25:29.502226Z","shell.execute_reply.started":"2025-10-06T16:25:29.484627Z","shell.execute_reply":"2025-10-06T16:25:29.501551Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission = pd.DataFrame({\n    'id': all_ids,           # Tumhare image ids\n    'label': all_preds_text  # Ab number nahi, name hain\n})\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T16:25:37.771257Z","iopub.execute_input":"2025-10-06T16:25:37.771823Z","iopub.status.idle":"2025-10-06T16:25:37.812839Z","shell.execute_reply.started":"2025-10-06T16:25:37.7718Z","shell.execute_reply":"2025-10-06T16:25:37.812069Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.to_csv('submission.csv', index=False)\nprint(submission.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-06T16:25:57.379841Z","iopub.execute_input":"2025-10-06T16:25:57.380119Z","iopub.status.idle":"2025-10-06T16:25:57.607797Z","shell.execute_reply.started":"2025-10-06T16:25:57.380097Z","shell.execute_reply":"2025-10-06T16:25:57.607019Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}