{"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":"none","dataSources":[{"sourceId":3649,"databundleVersionId":46718,"sourceType":"competition"}],"dockerImageVersionId":31192,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-12-16T17:13:01.392200Z","iopub.execute_input":"2025-12-16T17:13:01.392714Z","iopub.status.idle":"2025-12-16T17:13:03.454843Z","shell.execute_reply.started":"2025-12-16T17:13:01.392691Z","shell.execute_reply":"2025-12-16T17:13:03.453639Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!apt-get install -y p7zip-full","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T17:22:53.539340Z","iopub.execute_input":"2025-12-16T17:22:53.540256Z","iopub.status.idle":"2025-12-16T17:22:57.072241Z","shell.execute_reply.started":"2025-12-16T17:22:53.540224Z","shell.execute_reply":"2025-12-16T17:22:57.071308Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!7z x  /kaggle/input/cifar-10/train.7z -o/kaggle/working/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T17:24:33.496743Z","iopub.execute_input":"2025-12-16T17:24:33.497698Z","iopub.status.idle":"2025-12-16T17:31:44.593933Z","shell.execute_reply.started":"2025-12-16T17:24:33.497663Z","shell.execute_reply":"2025-12-16T17:31:44.593072Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nfrom torch.utils.data import Dataset , DataLoader\nfrom torchvision import transforms\nfrom PIL import Image\nimport os ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T17:50:49.774749Z","iopub.execute_input":"2025-12-16T17:50:49.775524Z","iopub.status.idle":"2025-12-16T17:50:49.779149Z","shell.execute_reply.started":"2025-12-16T17:50:49.775498Z","shell.execute_reply":"2025-12-16T17:50:49.778440Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"CLASS_NAMES = ['airplane', 'automobile', 'bird', 'cat', 'deer', \n               'dog', 'frog', 'horse', 'ship', 'truck']\nLABEL_TO_INDEX = {name: i for i, name in enumerate(CLASS_NAMES)}\n\nclass CIFAR10CustomDataset(Dataset):\n    def __init__(self, csv_file, img_dir, transform=None):\n        self.labels_df = pd.read_csv(csv_file)\n        self.img_dir = img_dir\n        self.transform = transform\n        self.label_map = LABEL_TO_INDEX\n\n    def __len__(self):\n        return len(self.labels_df)\n\n    def __getitem__(self, idx):\n        img_id = self.labels_df.iloc[idx, 0]\n        label_str = self.labels_df.iloc[idx, 1]\n        label_index = self.label_map[label_str]\n        label_tensor = torch.tensor(label_index , dtype = torch.long)\n\n        img_path = os.path.join(self.img_dir, f\"{img_id}.png\")\n        image = Image.open(img_path).convert(\"RGB\")\n\n        if self.transform:\n            image = self.transform(image)\n\n        return image, label_tensor","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T19:51:18.834502Z","iopub.execute_input":"2025-12-16T19:51:18.834841Z","iopub.status.idle":"2025-12-16T19:51:18.841834Z","shell.execute_reply.started":"2025-12-16T19:51:18.834801Z","shell.execute_reply":"2025-12-16T19:51:18.840957Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"transform = transforms.Compose([transforms.ToTensor()])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T19:51:21.505432Z","iopub.execute_input":"2025-12-16T19:51:21.505733Z","iopub.status.idle":"2025-12-16T19:51:21.509970Z","shell.execute_reply.started":"2025-12-16T19:51:21.505710Z","shell.execute_reply":"2025-12-16T19:51:21.509213Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dataset = CIFAR10CustomDataset(\n    csv_file=\"/kaggle/input/cifar-10/trainLabels.csv\",\n    img_dir=\"/kaggle/working/train/train\",\n    transform=transform\n)\n\nloader = DataLoader(dataset,batch_size=8,shuffle=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T19:51:23.466352Z","iopub.execute_input":"2025-12-16T19:51:23.467133Z","iopub.status.idle":"2025-12-16T19:51:23.488446Z","shell.execute_reply.started":"2025-12-16T19:51:23.467106Z","shell.execute_reply":"2025-12-16T19:51:23.487749Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom PIL import Image\n\nimages, labels = next(iter(loader))\n\nplt.figure(figsize=(10,4))\nfor i in range(8):\n    img = np.transpose(images[i].numpy(), (1,2,0))\n    plt.subplot(2,4,i+1)\n    plt.imshow(img)\n    plt.title(labels[i])\n    plt.axis(\"off\")\n\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T19:51:25.840122Z","iopub.execute_input":"2025-12-16T19:51:25.840643Z","iopub.status.idle":"2025-12-16T19:51:26.223611Z","shell.execute_reply.started":"2025-12-16T19:51:25.840618Z","shell.execute_reply":"2025-12-16T19:51:26.222874Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torchvision.transforms import functional as F","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T19:51:28.770891Z","iopub.execute_input":"2025-12-16T19:51:28.771190Z","iopub.status.idle":"2025-12-16T19:51:28.775387Z","shell.execute_reply.started":"2025-12-16T19:51:28.771170Z","shell.execute_reply":"2025-12-16T19:51:28.774396Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_pil = F.to_pil_image(images[0])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T19:51:31.250914Z","iopub.execute_input":"2025-12-16T19:51:31.251225Z","iopub.status.idle":"2025-12-16T19:51:31.256365Z","shell.execute_reply.started":"2025-12-16T19:51:31.251200Z","shell.execute_reply":"2025-12-16T19:51:31.255499Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ops = {\n    'original' : img_pil ,\n    'Resized' : transforms.Resize((16 , 16))(img_pil) , \n    'Center Crop' : transforms.CenterCrop(16)(img_pil) ,\n    'Rotated' : transforms.RandomRotation(45)(img_pil) ,\n    'Grayscale' : transforms.Grayscale(num_output_channels = 1)(img_pil)\n}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T19:51:33.178636Z","iopub.execute_input":"2025-12-16T19:51:33.178975Z","iopub.status.idle":"2025-12-16T19:51:33.185051Z","shell.execute_reply.started":"2025-12-16T19:51:33.178949Z","shell.execute_reply":"2025-12-16T19:51:33.184325Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(10,4))\n \nfor i, (name, im) in enumerate(ops.items()):\n    plt.subplot(2, 3, i+1)\n \n    arr = np.array(im)\n \n    if name == \"Grayscale\":\n        plt.imshow(arr, cmap=\"gray\")\n    else:\n        plt.imshow(arr)\n \n    plt.title(name)\n    plt.axis(\"off\")\n \nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T19:51:35.026526Z","iopub.execute_input":"2025-12-16T19:51:35.027366Z","iopub.status.idle":"2025-12-16T19:51:35.275719Z","shell.execute_reply.started":"2025-12-16T19:51:35.027338Z","shell.execute_reply":"2025-12-16T19:51:35.275028Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Computer Vision (h , w , c)\n# pyTorch (c ,h ,w)","metadata":{}},{"cell_type":"code","source":"from skimage.feature import hog\nfrom skimage.color import rgb2gray\n\n\nsample = images[0].numpy().transpose(1 ,2, 0)\n\ngray = rgb2gray(sample)\n\nhog_features , hog_image = hog(gray , visualize = True)\n\nplt.subplot(1 ,2,1)\nplt.imshow(gray , cmap = 'gray')\nplt.title(\"Original Iamge\")\nplt.subplot(1 ,2, 2)\nplt.imshow(hog_image , cmap = 'gray' )\nplt.title(\"HOG Iamge\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T19:51:38.557442Z","iopub.execute_input":"2025-12-16T19:51:38.557741Z","iopub.status.idle":"2025-12-16T19:51:38.826864Z","shell.execute_reply.started":"2025-12-16T19:51:38.557719Z","shell.execute_reply":"2025-12-16T19:51:38.826135Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.nn as nn\nimport torch\n\n\nclass SimpleCNN(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.net = nn.Sequential(\n            nn.Conv2d(3, 32, 3, padding=1),\n            nn.ReLU(),\n            nn.MaxPool2d(2),   # 16x16\n \n            nn.Conv2d(32, 64, 3, padding=1),\n            nn.ReLU(),\n            nn.MaxPool2d(2),   # 8x8\n \n            nn.Flatten(),\n            nn.Linear(64*8*8, 256),\n            nn.ReLU(),\n            nn.Linear(256, 10)\n        )\n       \n    def forward(self, x):\n        return self.net(x)\n \nmodel = SimpleCNN()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T19:51:42.521495Z","iopub.execute_input":"2025-12-16T19:51:42.522134Z","iopub.status.idle":"2025-12-16T19:51:42.537719Z","shell.execute_reply.started":"2025-12-16T19:51:42.522106Z","shell.execute_reply":"2025-12-16T19:51:42.536948Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.utils.data import DataLoader\n\ntrain_loader = DataLoader(dataset, batch_size=64, shuffle=True)\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n\ndef train_cnn(epochs=3):\n    for epoch in range(epochs):\n        total, correct, total_loss = 0, 0, 0\n        \n        for imgs, labels in train_loader:\n            optimizer.zero_grad()\n            outputs = model(imgs)\n\n            \n            loss = criterion(outputs, labels)\n            loss.backward()\n            optimizer.step()\n\n            total_loss += loss.item()\n            _, preds = outputs.max(1)\n            correct += preds.eq(labels).sum().item()\n            total += labels.size(0)\n\n        print(f\"Epoch {epoch+1}: Loss={total_loss:.3f}, Acc={correct/total:.3f}\")\n\ntrain_cnn()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-16T19:51:45.161608Z","iopub.execute_input":"2025-12-16T19:51:45.162291Z","iopub.status.idle":"2025-12-16T19:55:07.547080Z","shell.execute_reply.started":"2025-12-16T19:51:45.162263Z","shell.execute_reply":"2025-12-16T19:55:07.546146Z"}},"outputs":[],"execution_count":null}]}