{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":31040,"isInternetEnabled":true,"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 torch\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.optim as optim\nimport torch.nn as nn\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nfrom matplotlib import pyplot as plt\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-06-24T10:49:21.105033Z","iopub.execute_input":"2025-06-24T10:49:21.105290Z","iopub.status.idle":"2025-06-24T10:49:27.421054Z","shell.execute_reply.started":"2025-06-24T10:49:21.105268Z","shell.execute_reply":"2025-06-24T10:49:27.420123Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ndata_test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T10:49:27.421918Z","iopub.execute_input":"2025-06-24T10:49:27.422321Z","iopub.status.idle":"2025-06-24T10:49:33.237583Z","shell.execute_reply.started":"2025-06-24T10:49:27.422296Z","shell.execute_reply":"2025-06-24T10:49:33.236646Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images_x = data.iloc[:, 1:].values / 255\nimages_y = data.iloc[:, 0].values\nimages_x = torch.tensor(images_x, dtype = torch.float32).view(-1,1,28,28)\nimages_y = torch.tensor(images_y, dtype = torch.float32)\nimages_y = images_y.type(torch.LongTensor)\n\nclass ComfortableData(Dataset):\n    def __init__(self, x, y):\n        self.x = x\n        self.y = y\n    def __getitem__(self, idd):\n        return self.x[idd], self.y[idd]\n    def __len__(self):\n        return len(self.x)\n\ncomfort_data = ComfortableData(images_x, images_y)\ndata_for_train = DataLoader(comfort_data, batch_size = 128, shuffle=True)\n\nimport torch.nn.functional as F\nclass CNNModel(nn.Module):\n    def __init__(self):\n        super(CNNModel, self).__init__()\n        self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1)   # 28x28 → 28x28\n        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)  # 28x28 → 28x28\n        self.pool = nn.MaxPool2d(2, 2)                            # 28x28 → 14x14\n        self.dropout = nn.Dropout(0.25)\n\n        self.fc1 = nn.Linear(64 * 14 * 14, 128)\n        self.fc2 = nn.Linear(128, 10)\n\n    def forward(self, x):\n        x = F.relu(self.conv1(x))      # (B, 32, 28, 28)\n        x = F.relu(self.conv2(x))      # (B, 64, 28, 28)\n        x = self.pool(x)               # (B, 64, 14, 14)\n        x = self.dropout(x)\n        x = x.view(-1, 64 * 14 * 14)   # Flatten\n        x = F.relu(self.fc1(x))\n        x = self.dropout(x)\n        x = self.fc2(x)                # Output logits (B, 10)\n        return x\n\n\nmodel = CNNModel()\ncr = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.01)\ncounter = 0\ncorrects = 0\nepochs = 10\nfor i in range(epochs):\n    cost = 0\n    for image, answer in data_for_train:\n        optimizer.zero_grad()\n        predictions = model(image)\n        error = cr(predictions, answer)\n        error.backward()\n        optimizer.step()\n        cost += error.item()\n        if i == epochs - 1:\n            for j in range(len(answer)):\n                # print(torch.argmax(predictions[j]).item(), answer[j].item())\n                if torch.argmax(predictions[j]).item() == answer[j].item():\n                    corrects += 1\n            # if counter < 1:\n            #     for j in range(len(answer)):\n            #         print(torch.argmax(predictions[j]).item())\n            #         img = image[j].view(28, 28)\n            #         plt.imshow(img, cmap='Blues')\n            #         plt.show()\n            #         counter += 1\n    \n    if i % 1 == 0:\n        print(cost/len(data_for_train))\nprint(\"accuracy:\", corrects, len(data_for_train)*128, corrects / (len(data_for_train)*128))\n\n        \n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T11:05:34.987764Z","iopub.execute_input":"2025-06-24T11:05:34.988176Z","iopub.status.idle":"2025-06-24T11:15:09.377467Z","shell.execute_reply.started":"2025-06-24T11:05:34.988152Z","shell.execute_reply":"2025-06-24T11:15:09.376588Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class ComfortableData1(Dataset):\n    def __init__(self, x):\n        self.x = x\n    def __getitem__(self, idd):\n        return self.x[idd]\n    def __len__(self):\n        return len(self.x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T11:15:26.081075Z","iopub.execute_input":"2025-06-24T11:15:26.081376Z","iopub.status.idle":"2025-06-24T11:15:26.086913Z","shell.execute_reply.started":"2025-06-24T11:15:26.081355Z","shell.execute_reply":"2025-06-24T11:15:26.085684Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images_x = data_test.iloc[:, :].values / 255\nimages_x = torch.tensor(images_x, dtype = torch.float32).view(-1,1,28,28)\n\n\ncomfort_data = ComfortableData1(images_x)\ndata_for_test = DataLoader(comfort_data, batch_size = 128, shuffle=False)\n\ncorrects = 0\npreds = []\nfor image in data_for_test:\n    optimizer.zero_grad()\n    predictions = model(image)\n    for j in range(len(image)):\n        # print(torch.argmax(predictions[j]).item(), answer[j].item())\n        preds.append(torch.argmax(predictions[j]).item())\n\n\n        \n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T11:17:55.241609Z","iopub.execute_input":"2025-06-24T11:17:55.242017Z","iopub.status.idle":"2025-06-24T11:18:10.886104Z","shell.execute_reply.started":"2025-06-24T11:17:55.241989Z","shell.execute_reply":"2025-06-24T11:18:10.885218Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample =  pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv')\nsubmission = pd.DataFrame({\n    'ImageId': sample['ImageId'],\n    'Label': preds\n})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T11:25:04.409284Z","iopub.execute_input":"2025-06-24T11:25:04.410001Z","iopub.status.idle":"2025-06-24T11:25:04.439358Z","shell.execute_reply.started":"2025-06-24T11:25:04.409965Z","shell.execute_reply":"2025-06-24T11:25:04.438310Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T11:25:05.860767Z","iopub.execute_input":"2025-06-24T11:25:05.861080Z","iopub.status.idle":"2025-06-24T11:25:05.871828Z","shell.execute_reply.started":"2025-06-24T11:25:05.861057Z","shell.execute_reply":"2025-06-24T11:25:05.870659Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.to_csv('submission.csv',index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T11:25:38.604260Z","iopub.execute_input":"2025-06-24T11:25:38.604609Z","iopub.status.idle":"2025-06-24T11:25:38.636217Z","shell.execute_reply.started":"2025-06-24T11:25:38.604587Z","shell.execute_reply":"2025-06-24T11:25:38.634829Z"}},"outputs":[],"execution_count":null}]}