{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport pandas as pd\nimport numpy as np\nfrom PIL import Image\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom sklearn.model_selection import train_test_split\n\n# Use GPU if available\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nprint(\"Using device:\", device)\n\n# Exact Kaggle Path\nDATA_PATH = '/kaggle/input/competitions/dog-breed-identification'\nlabels_file = os.path.join(DATA_PATH, 'labels.csv')\ntrain_folder = os.path.join(DATA_PATH, 'train')\ntest_folder = os.path.join(DATA_PATH, 'test')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-31T18:57:59.775275Z","iopub.execute_input":"2026-08-31T18:57:59.775552Z","iopub.status.idle":"2026-08-31T18:57:59.782028Z","shell.execute_reply.started":"2026-08-31T18:57:59.775529Z","shell.execute_reply":"2026-08-31T18:57:59.781406Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv(labels_file)\n\ndf['image_path'] = df['id'].apply(lambda x: os.path.join(train_folder, f\"{x}.jpg\"))\n\nbreeds = sorted(df['breed'].unique())\nnum_classes = len(breeds)\n\nbreed_to_num = {breed: i for i, breed in enumerate(breeds)}\ndf['label'] = df['breed'].map(breed_to_num)\n\ntrain_df, val_df = train_test_split(df, test_size=0.2, random_state=42)\n\nprint(\"Total images:\", len(df))\nprint(\"Training images:\", len(train_df))\nprint(\"Validation images:\", len(val_df))\nprint(\"Number of breeds:\", num_classes)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-31T18:57:59.783002Z","iopub.execute_input":"2026-08-31T18:57:59.783216Z","iopub.status.idle":"2026-08-31T18:57:59.833934Z","shell.execute_reply.started":"2026-08-31T18:57:59.783191Z","shell.execute_reply":"2026-08-31T18:57:59.833258Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"simple_resize = transforms.Compose([\n    transforms.Resize((224, 224)),\n    transforms.ToTensor()\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-31T18:57:59.834817Z","iopub.execute_input":"2026-08-31T18:57:59.835309Z","iopub.status.idle":"2026-08-31T18:57:59.839725Z","shell.execute_reply.started":"2026-08-31T18:57:59.835278Z","shell.execute_reply":"2026-08-31T18:57:59.838969Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class DogDataset(Dataset):\n    def __init__(self, data, transform=None):\n        self.data = data.reset_index(drop=True)\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.data)\n\n    def __getitem__(self, index):\n        path = self.data.loc[index, 'image_path']\n        image = Image.open(path).convert('RGB')\n        label = self.data.loc[index, 'label']\n        \n        if self.transform:\n            image = self.transform(image)\n            \n        return image, label\n\ntrain_data = DogDataset(train_df, transform=simple_resize)\nval_data = DogDataset(val_df, transform=simple_resize)\n\ntrain_loader = DataLoader(train_data, batch_size=32, shuffle=True)\nval_loader = DataLoader(val_data, batch_size=32, shuffle=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-31T18:57:59.840494Z","iopub.execute_input":"2026-08-31T18:57:59.840712Z","iopub.status.idle":"2026-08-31T18:57:59.862073Z","shell.execute_reply.started":"2026-08-31T18:57:59.840687Z","shell.execute_reply":"2026-08-31T18:57:59.861186Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class SimpleDogCNN(nn.Module):\n    def __init__(self, num_classes=120):\n        super(SimpleDogCNN, self).__init__()\n        \n        self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)\n        self.bn1 = nn.BatchNorm2d(32)\n        \n        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)\n        self.bn2 = nn.BatchNorm2d(64)\n        \n        self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)\n        self.bn3 = nn.BatchNorm2d(128)\n        \n        self.conv4 = nn.Conv2d(128, 256, kernel_size=3, padding=1)\n        self.bn4 = nn.BatchNorm2d(256)\n        \n        self.pool = nn.MaxPool2d(2, 2)\n        self.relu = nn.ReLU()\n        self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))\n        \n        self.dropout = nn.Dropout(0.5)\n        self.fc1 = nn.Linear(256, 128)\n        self.fc2 = nn.Linear(128, num_classes)\n\n    def forward(self, x):\n        x = self.pool(self.relu(self.bn1(self.conv1(x))))\n        x = self.pool(self.relu(self.bn2(self.conv2(x))))\n        x = self.pool(self.relu(self.bn3(self.conv3(x))))\n        x = self.pool(self.relu(self.bn4(self.conv4(x))))\n        \n        x = self.avg_pool(x)\n        x = torch.flatten(x, 1)\n        \n        x = self.dropout(x)\n        x = self.relu(self.fc1(x))\n        x = self.dropout(x)\n        x = self.fc2(x)\n        \n        return x\n\nmodel = SimpleDogCNN(num_classes=num_classes).to(device)\nprint(\"Model ready!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-31T18:57:59.864676Z","iopub.execute_input":"2026-08-31T18:57:59.864965Z","iopub.status.idle":"2026-08-31T18:57:59.914642Z","shell.execute_reply.started":"2026-08-31T18:57:59.864942Z","shell.execute_reply":"2026-08-31T18:57:59.913805Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"criterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-31T18:57:59.915763Z","iopub.execute_input":"2026-08-31T18:57:59.915980Z","iopub.status.idle":"2026-08-31T18:57:59.920261Z","shell.execute_reply.started":"2026-08-31T18:57:59.915960Z","shell.execute_reply":"2026-08-31T18:57:59.919422Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\n\nprint(\"GPU Available:\", torch.cuda.is_available())\nif torch.cuda.is_available():\n    print(\"Device Name:\", torch.cuda.get_device_name(0))\nelse:\n    print(\"YOU ARE ON CPU!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-31T18:57:59.921124Z","iopub.execute_input":"2026-08-31T18:57:59.921420Z","iopub.status.idle":"2026-08-31T18:57:59.939391Z","shell.execute_reply.started":"2026-08-31T18:57:59.921349Z","shell.execute_reply":"2026-08-31T18:57:59.938447Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.train()\nrunning_loss = 0.0\n\nfor i, (images, labels) in enumerate(train_loader):\n    images, labels = images.to(device), 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()\n    if i % 50 == 0:\n        print(f\"Batch {i}/{len(train_loader)} completed...\")\n\nprint(\"Training finished!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-31T19:00:48.025152Z","iopub.execute_input":"2026-08-31T19:00:48.025450Z","iopub.status.idle":"2026-08-31T19:11:04.044768Z","shell.execute_reply.started":"2026-08-31T19:00:48.025425Z","shell.execute_reply":"2026-08-31T19:11:04.043574Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images = sorted([f for f in os.listdir(test_folder) if f.endswith('.jpg')])\ntest_ids = [f.split('.')[0] for f in test_images]\n\nclass SimpleTestDataset(Dataset):\n    def __init__(self, file_list, folder, transform=None):\n        self.file_list = file_list\n        self.folder = folder\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.file_list)\n\n    def __getitem__(self, idx):\n        path = os.path.join(self.folder, self.file_list[idx])\n        image = Image.open(path).convert('RGB')\n        if self.transform:\n            image = self.transform(image)\n        return image\n\ntest_data = SimpleTestDataset(test_images, test_folder, transform=simple_resize)\ntest_loader = DataLoader(test_data, batch_size=64, shuffle=False)\nprint(f\"Total test images ready: {len(test_images)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-31T19:17:42.261865Z","iopub.execute_input":"2026-08-31T19:17:42.262185Z","iopub.status.idle":"2026-08-31T19:17:42.278558Z","shell.execute_reply.started":"2026-08-31T19:17:42.262161Z","shell.execute_reply":"2026-08-31T19:17:42.277407Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.eval()\nall_probs = []\nmax_batches = 5\n\nwith torch.no_grad():\n    for i, images in enumerate(test_loader):\n        if i >= max_batches:\n            break\n        images = images.to(device)\n        outputs = model(images)\n        probs = torch.softmax(outputs, dim=1)\n        all_probs.append(probs.cpu().numpy())\n        print(f\"Batch {i+1}/{max_batches} done\")\n\nprint(\"Fast predictions completed!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-31T19:19:20.544168Z","iopub.execute_input":"2026-08-31T19:19:20.544465Z","iopub.status.idle":"2026-08-31T19:19:31.502808Z","shell.execute_reply.started":"2026-08-31T19:19:20.544442Z","shell.execute_reply":"2026-08-31T19:19:31.501940Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ntest_folder = '/kaggle/input/competitions/dog-breed-identification/test'\n\ntest_images = sorted([f for f in os.listdir(test_folder) if f.endswith('.jpg')])\ntest_ids = [f.split('.')[0] for f in test_images]\n\nnum_test = len(test_ids)\nnum_breeds = len(breeds)\nprob_value = 1.0 / num_breeds\n\npredictions = np.full((num_test, num_breeds), prob_value)\n\nsub_df = pd.DataFrame(predictions, columns=breeds)\nsub_df.insert(0, 'id', test_ids)\nsub_df.to_csv('submission.csv', index=False)\n\nprint(f\"Generated submission.csv with shape: {sub_df.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-31T19:30:49.025151Z","iopub.execute_input":"2026-08-31T19:30:49.025431Z","iopub.status.idle":"2026-08-31T19:30:50.172393Z","shell.execute_reply.started":"2026-08-31T19:30:49.025409Z","shell.execute_reply":"2026-08-31T19:30:50.171580Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-31T19:31:11.393933Z","iopub.execute_input":"2026-08-31T19:31:11.394161Z"}},"outputs":[],"execution_count":null}]}