{"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":"# 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\n\n# Use the kagglehub client library to attach Kaggle resources like competitions, datasets, and models to your session\n# Learn more about kagglehub: https://github.com/Kaggle/kagglehub/blob/main/README.md\n\nimport kagglehub\n# kagglehub.dataset_download('<owner>/<dataset-slug>')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:03:23.013371Z","iopub.execute_input":"2026-09-24T10:03:23.013935Z","iopub.status.idle":"2026-09-24T10:03:24.20011Z","shell.execute_reply.started":"2026-09-24T10:03:23.013908Z","shell.execute_reply":"2026-09-24T10:03:24.199426Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader, Dataset\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:03:24.20156Z","iopub.execute_input":"2026-09-24T10:03:24.202048Z","iopub.status.idle":"2026-09-24T10:03:33.111035Z","shell.execute_reply.started":"2026-09-24T10:03:24.202021Z","shell.execute_reply":"2026-09-24T10:03:33.110348Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:03:33.111963Z","iopub.execute_input":"2026-09-24T10:03:33.112425Z","iopub.status.idle":"2026-09-24T10:03:33.387034Z","shell.execute_reply.started":"2026-09-24T10:03:33.11239Z","shell.execute_reply":"2026-09-24T10:03:33.385922Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(device)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:03:33.389422Z","iopub.execute_input":"2026-09-24T10:03:33.389724Z","iopub.status.idle":"2026-09-24T10:03:33.428247Z","shell.execute_reply.started":"2026-09-24T10:03:33.389701Z","shell.execute_reply":"2026-09-24T10:03:33.427358Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class CustomMNISTDataset(Dataset):\n    def __init__(self, csv_file, transform=None, is_test=False):\n        self.data_frame = pd.read_csv(csv_file)\n        self.transform = transform\n        self.is_test = is_test\n\n    def __len__(self):\n        return len(self.data_frame)\n\n    def __getitem__(self, index):\n        item = self.data_frame.iloc[index]\n\n        if self.is_test:\n            image = item.values.reshape(28, 28).astype(np.uint8)\n            label = None\n        else:\n            image = item[1:].values.reshape(28, 28).astype(np.uint8)\n            label = item.iloc[0]\n\n        image = transforms.ToPILImage()(image)\n\n        if self.transform is not None:\n            image = self.transform(image)\n\n        if self.is_test:\n            return image\n        else:\n            return image, label","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:03:33.429434Z","iopub.execute_input":"2026-09-24T10:03:33.42986Z","iopub.status.idle":"2026-09-24T10:03:33.44204Z","shell.execute_reply.started":"2026-09-24T10:03:33.429794Z","shell.execute_reply":"2026-09-24T10:03:33.441282Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"transform = transforms.Compose([\n    transforms.RandomRotation(15),\n    transforms.ToTensor(),\n    transforms.Normalize((0.5,), (0.5,))  # MNIST's standard mean/std\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:03:33.44292Z","iopub.execute_input":"2026-09-24T10:03:33.443925Z","iopub.status.idle":"2026-09-24T10:03:33.459629Z","shell.execute_reply.started":"2026-09-24T10:03:33.443894Z","shell.execute_reply":"2026-09-24T10:03:33.458803Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_dataset = CustomMNISTDataset(csv_file=\"/kaggle/input/competitions/digit-recognizer/train.csv\", transform=transform, is_test=False)\ntest_dataset = CustomMNISTDataset(csv_file=\"/kaggle/input/competitions/digit-recognizer/test.csv\", transform=transform, is_test=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:03:33.460712Z","iopub.execute_input":"2026-09-24T10:03:33.461554Z","iopub.status.idle":"2026-09-24T10:03:37.925603Z","shell.execute_reply.started":"2026-09-24T10:03:33.461529Z","shell.execute_reply":"2026-09-24T10:03:37.92497Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print('Train Size: ' + str(len(train_dataset)) + ', Test Size: ' + str(len(test_dataset)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:03:37.926618Z","iopub.execute_input":"2026-09-24T10:03:37.926961Z","iopub.status.idle":"2026-09-24T10:03:37.931519Z","shell.execute_reply.started":"2026-09-24T10:03:37.926938Z","shell.execute_reply":"2026-09-24T10:03:37.930949Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_dataset[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:03:37.932485Z","iopub.execute_input":"2026-09-24T10:03:37.933081Z","iopub.status.idle":"2026-09-24T10:03:38.065109Z","shell.execute_reply.started":"2026-09-24T10:03:37.933056Z","shell.execute_reply":"2026-09-24T10:03:38.064394Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"batch_size = 64\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=2)\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False, num_workers=2)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:03:38.067174Z","iopub.execute_input":"2026-09-24T10:03:38.067489Z","iopub.status.idle":"2026-09-24T10:03:38.07253Z","shell.execute_reply.started":"2026-09-24T10:03:38.067466Z","shell.execute_reply":"2026-09-24T10:03:38.071478Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for example_data, example_labels in train_loader:\n    example_image = example_data[0]\n    print(\"Input size:\", example_data.size())\n\n    example_image_numpy = example_image.permute(1, 2, 0).numpy()\n    plt.imshow(example_image_numpy)\n    plt.title(f\"Label: {example_labels[0]}\")\n    plt.show()\n\n    break","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:03:38.073544Z","iopub.execute_input":"2026-09-24T10:03:38.07409Z","iopub.status.idle":"2026-09-24T10:03:38.406948Z","shell.execute_reply.started":"2026-09-24T10:03:38.074043Z","shell.execute_reply":"2026-09-24T10:03:38.405927Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class SimpleCNN(nn.Module):\n    def __init__(self):\n        super(SimpleCNN, self). __init__()\n        self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, stride=1, padding=1)\n        self.relu = nn.ReLU()\n        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)\n        self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1)\n        self.conv3 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1)\n        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)\n\n        self.fc1 = nn.Linear(128 * 7 * 7, 128)\n        self.dropout = nn.Dropout(0.5)\n        self.fc2 = nn.Linear(128, 20)\n        self.fc3 = nn.Linear(20, 10)\n\n    def forward(self, x):\n        x = self.conv1(x)\n        x = self.relu(x)\n        x = self.pool(x)\n        x = self.conv2(x)\n        x = self.relu(x)\n        x = self.conv3(x)\n        x = self.pool(x)\n\n        x_size = x.size(1) * x.size(2) * x.size(3)\n\n        x = x.view(-1, x_size)\n        x = self.fc1(x)\n        x = self.relu(x)\n        x = self.fc2(x)\n        x = self.fc3(x)\n\n        return x","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:05:02.961951Z","iopub.execute_input":"2026-09-24T10:05:02.962367Z","iopub.status.idle":"2026-09-24T10:05:02.96999Z","shell.execute_reply.started":"2026-09-24T10:05:02.962339Z","shell.execute_reply":"2026-09-24T10:05:02.969154Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = SimpleCNN().to(device)\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(), lr = 0.01, momentum=0.9)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:08:08.803767Z","iopub.execute_input":"2026-09-24T10:08:08.804222Z","iopub.status.idle":"2026-09-24T10:08:08.81841Z","shell.execute_reply.started":"2026-09-24T10:08:08.804194Z","shell.execute_reply":"2026-09-24T10:08:08.817629Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"num_epochs = 100\nrunning_loss = 0.0\n\nfor epoch in range(num_epochs):\n    for i, data in enumerate(train_loader, 0):\n        inputs, labels = data\n        inputs, labels = inputs.to(device), labels.to(device)\n\n        optimizer.zero_grad()\n\n        outputs = model(inputs.float())\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\n\n        running_loss += loss.item()\n\n        if i % 100 == 99:\n            print(f\"[{epoch + 1}, {i + 1}] Loss: {running_loss / 100:.3f}\")\n            running_loss = 0.0\n\nprint(\"Training finished\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T10:50:22.202135Z","iopub.execute_input":"2026-09-24T10:50:22.202752Z","iopub.status.idle":"2026-09-24T11:10:44.338446Z","shell.execute_reply.started":"2026-09-24T10:50:22.20272Z","shell.execute_reply":"2026-09-24T11:10:44.337546Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.eval()\npredictions = []\n\nwith torch.no_grad():\n    for data in test_loader:\n        data = data.to(device)\n\n        outputs = model(data)\n        _, predicted = torch.max(outputs, 1)          \n        predictions.extend(predicted.cpu().tolist())  \n\nsubmission = pd.DataFrame({\n    \"ImageId\": range(1, len(predictions) + 1),        \n    \"Label\": predictions\n})\n\nsubmission.to_csv(\"predictions_final.csv\", index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-24T11:20:37.092061Z","iopub.execute_input":"2026-09-24T11:20:37.092392Z","iopub.status.idle":"2026-09-24T11:20:43.683375Z","shell.execute_reply.started":"2026-09-24T11:20:37.092368Z","shell.execute_reply":"2026-09-24T11:20:43.682594Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}