{"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":"gpu","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":31192,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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-11-17T07:24:51.992541Z","iopub.execute_input":"2025-11-17T07:24:51.993306Z","iopub.status.idle":"2025-11-17T07:24:52.011992Z","shell.execute_reply.started":"2025-11-17T07:24:51.993275Z","shell.execute_reply":"2025-11-17T07:24:52.011287Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest_df = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-17T07:24:52.013334Z","iopub.execute_input":"2025-11-17T07:24:52.013594Z","iopub.status.idle":"2025-11-17T07:24:54.805693Z","shell.execute_reply.started":"2025-11-17T07:24:52.013562Z","shell.execute_reply":"2025-11-17T07:24:54.805069Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Y_train = train_df[\"label\"]\nX_train = train_df.drop(columns=[\"label\"], axis = 1) \n\ndel train_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-17T07:24:54.806386Z","iopub.execute_input":"2025-11-17T07:24:54.806576Z","iopub.status.idle":"2025-11-17T07:24:54.888856Z","shell.execute_reply.started":"2025-11-17T07:24:54.806562Z","shell.execute_reply":"2025-11-17T07:24:54.888232Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train = X_train / 255.0\ntest_df = test_df / 255.0","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-17T07:24:54.890305Z","iopub.execute_input":"2025-11-17T07:24:54.890533Z","iopub.status.idle":"2025-11-17T07:24:54.979554Z","shell.execute_reply.started":"2025-11-17T07:24:54.890516Z","shell.execute_reply":"2025-11-17T07:24:54.978929Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train = X_train.values.reshape(-1, 1, 28, 28)\ntest_df = test_df.values.reshape(-1, 1, 28, 28)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-17T07:24:54.980259Z","iopub.execute_input":"2025-11-17T07:24:54.980467Z","iopub.status.idle":"2025-11-17T07:24:54.984405Z","shell.execute_reply.started":"2025-11-17T07:24:54.980452Z","shell.execute_reply":"2025-11-17T07:24:54.983805Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nX_train, X_val, Y_train, Y_val = train_test_split(X_train.tolist(), Y_train.tolist(), test_size=0.1, random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-17T07:24:54.984988Z","iopub.execute_input":"2025-11-17T07:24:54.985170Z","iopub.status.idle":"2025-11-17T07:25:00.256412Z","shell.execute_reply.started":"2025-11-17T07:24:54.985155Z","shell.execute_reply":"2025-11-17T07:25:00.255481Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import math\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-17T07:25:00.257214Z","iopub.execute_input":"2025-11-17T07:25:00.257447Z","iopub.status.idle":"2025-11-17T07:25:00.261949Z","shell.execute_reply.started":"2025-11-17T07:25:00.257429Z","shell.execute_reply":"2025-11-17T07:25:00.261108Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.utils.data import Dataset, DataLoader\n\n\nbatch_size = 64\n\nclass MNISTDataset(Dataset):\n    def __init__(self, x, y):\n        self.x = x\n        self.y = y\n\n    def __len__(self):\n        return len(self.x)\n\n    def __getitem__(self, idx):\n        return torch.tensor(self.x[idx], dtype=torch.float).to(device), torch.tensor(self.y[idx]).to(device)\n\n\ntrain_dataset = MNISTDataset(X_train, Y_train)\nvalid_dataset = MNISTDataset(X_val, Y_val)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-17T07:25:00.262801Z","iopub.execute_input":"2025-11-17T07:25:00.263083Z","iopub.status.idle":"2025-11-17T07:25:00.279438Z","shell.execute_reply.started":"2025-11-17T07:25:00.263060Z","shell.execute_reply":"2025-11-17T07:25:00.278586Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def train(model, dataloader, optimizer, criterion):\n    model.train()\n\n    train_loss = 0.0\n    train_acc = 0.0\n    \n    for x, y in dataloader:        \n        pred = model(x)\n        loss = criterion(pred, y)\n        \n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n        train_loss += loss.item()\n        train_acc += (y == pred.argmax(1)).float().sum().item()\n\n    return train_loss, train_acc\n\ndef valid(model, dataloader, optimizer, criterion):\n    model.eval()\n\n    valid_loss = 0.0\n    valid_acc = 0.0\n    \n    for x, y in dataloader:\n        pred = model(x)\n        loss = criterion(pred, y)\n        valid_loss += loss.item()\n        valid_acc += (y == pred.argmax(1)).float().sum().item()\n\n    return valid_loss, valid_acc\n\ndef fit(model, train_dataset, valid_dataset, epochs=10):\n    train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n    valid_dataloader = DataLoader(valid_dataset, batch_size=batch_size, shuffle=False)\n    \n    optimizer = optim.RMSprop(model.parameters(), lr=3e-4)\n    criterion = nn.CrossEntropyLoss()\n    \n    for epoch in range(1, epochs + 1):\n        train_loss, train_acc = train(model, train_dataloader, optimizer, criterion)\n        valid_loss, valid_acc = valid(model, valid_dataloader, optimizer, criterion)\n\n        train_loss /= len(train_dataset)\n        train_acc /= len(train_dataset)\n        \n        valid_loss /= len(valid_dataset)\n        valid_acc /= len(valid_dataset)\n        \n        print(f\"{epoch=}; {train_loss=:2f}; {train_acc=:2f}%; {valid_loss=:2f}; {valid_acc=:2f}%; \")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-17T07:25:00.280068Z","iopub.execute_input":"2025-11-17T07:25:00.280306Z","iopub.status.idle":"2025-11-17T07:25:00.299522Z","shell.execute_reply.started":"2025-11-17T07:25:00.280281Z","shell.execute_reply":"2025-11-17T07:25:00.298917Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class Attention(nn.Module):\n    def __init__(self, d_model):\n        super().__init__()\n\n        self.d_model = d_model\n        \n        self.q = nn.Linear(d_model, d_model)\n        self.k = nn.Linear(d_model, d_model)\n        self.v = nn.Linear(d_model, d_model)\n\n    def forward(self, x):\n        Q = self.q(x)\n        K = self.k(x)\n        V = self.v(x)\n\n        QK = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_model)\n        score = torch.matmul(F.softmax(QK, dim=-1), V)\n        return score\n\n\nclass Residual(nn.Module):\n    def __init__(self, module):\n        self.module = module\n\n    def forward(self, x):\n        return self.module(x) + x\n\n\nclass Model(nn.Module):\n    def __init__(self, d_model):\n        super().__init__()\n\n        self.conv = nn.Sequential(\n            nn.Conv2d(1, 4, 5, padding=2),\n            nn.ReLU(),\n            nn.MaxPool2d(2),\n            nn.BatchNorm2d(4),\n            nn.Conv2d(4, 8, 3, padding=1),\n            nn.ReLU(),\n            nn.BatchNorm2d(8),\n            nn.MaxPool2d(2),\n        )\n        \n        self.attn = nn.Sequential(\n            Attention(d_model // 4),\n            nn.Dropout2d(0.5),\n        )\n        \n        self.norm = nn.RMSNorm(d_model**2 // 2)\n        self.linear = nn.Sequential(\n            nn.Linear(d_model**2 // 2, 128),\n            nn.RMSNorm(128),\n            nn.Dropout(0.6),\n            nn.Linear(128, 10),\n            nn.Softmax(dim=-1)\n        )\n\n    def forward(self, x):\n        x = self.conv(x)\n        x = self.attn(x) + x\n        x = x.view(x.size(0), -1)\n        x = self.norm(x)\n        return self.linear(x)\n\n\nmodel = Model(28).to(device)\nprint(f\"Model: {sum([p.numel() for p in model.parameters()]):,}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-17T07:25:00.301586Z","iopub.execute_input":"2025-11-17T07:25:00.301842Z","iopub.status.idle":"2025-11-17T07:25:00.323076Z","shell.execute_reply.started":"2025-11-17T07:25:00.301823Z","shell.execute_reply":"2025-11-17T07:25:00.322314Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fit(model, train_dataset, valid_dataset, 15)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-17T07:25:00.323964Z","iopub.execute_input":"2025-11-17T07:25:00.324656Z","iopub.status.idle":"2025-11-17T07:26:41.602678Z","shell.execute_reply.started":"2025-11-17T07:25:00.324630Z","shell.execute_reply":"2025-11-17T07:26:41.602059Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.eval()\n\ntest = torch.tensor(test_df, dtype=torch.float).to(device)\nresults = model(test)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-17T07:26:41.603513Z","iopub.execute_input":"2025-11-17T07:26:41.603747Z","iopub.status.idle":"2025-11-17T07:26:41.678740Z","shell.execute_reply.started":"2025-11-17T07:26:41.603711Z","shell.execute_reply":"2025-11-17T07:26:41.678133Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"results = pd.Series(results.argmax(-1).cpu(), name=\"Label\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-17T07:26:41.679463Z","iopub.execute_input":"2025-11-17T07:26:41.679720Z","iopub.status.idle":"2025-11-17T07:26:41.718452Z","shell.execute_reply.started":"2025-11-17T07:26:41.679692Z","shell.execute_reply":"2025-11-17T07:26:41.717653Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001), name = \"ImageId\"), results], axis=1)\n\nsubmission.to_csv(\"submission.csv\",index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-17T07:26:41.719200Z","iopub.execute_input":"2025-11-17T07:26:41.719510Z","iopub.status.idle":"2025-11-17T07:26:41.742669Z","shell.execute_reply.started":"2025-11-17T07:26:41.719493Z","shell.execute_reply":"2025-11-17T07:26:41.742145Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}