{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceType":"competition","sourceId":3004,"databundleVersionId":861823}],"dockerImageVersionId":31287,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import models","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-03-02T17:23:17.476873Z","iopub.execute_input":"2026-03-02T17:23:17.477205Z","iopub.status.idle":"2026-03-02T17:23:25.428632Z","shell.execute_reply.started":"2026-03-02T17:23:17.477171Z","shell.execute_reply":"2026-03-02T17:23:25.427885Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df = pd.read_csv(\"/kaggle/input/competitions/digit-recognizer/train.csv\")\ntest_df = pd.read_csv(\"/kaggle/input/competitions/digit-recognizer/test.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-02T17:23:25.430459Z","iopub.execute_input":"2026-03-02T17:23:25.430905Z","iopub.status.idle":"2026-03-02T17:23:29.607469Z","shell.execute_reply.started":"2026-03-02T17:23:25.430873Z","shell.execute_reply":"2026-03-02T17:23:29.606877Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-02T17:26:10.170969Z","iopub.execute_input":"2026-03-02T17:26:10.171650Z","iopub.status.idle":"2026-03-02T17:26:10.192956Z","shell.execute_reply.started":"2026-03-02T17:26:10.171607Z","shell.execute_reply":"2026-03-02T17:26:10.192096Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class EasyDataset(Dataset):\n    def __init__(self, df, is_test=False):\n        self.df = df\n        self.is_test = is_test\n        # Если тест - берем все, если трейн - все кроме 'label'\n        self.pixels = df.values if is_test else df.drop('label', axis=1).values\n        self.labels = None if is_test else df['label'].values\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        # Решейп из строки в картинку (1 канал, 28x28) + Нормализация\n        img = torch.tensor(self.pixels[idx].reshape(1, 28, 28), dtype=torch.float32) / 255.0\n        \n        if self.is_test:\n            return img\n        return img, self.labels[idx]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-02T17:23:29.608258Z","iopub.execute_input":"2026-03-02T17:23:29.608453Z","iopub.status.idle":"2026-03-02T17:23:29.614015Z","shell.execute_reply.started":"2026-03-02T17:23:29.608434Z","shell.execute_reply":"2026-03-02T17:23:29.613291Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Dataloaders\ntrain_loader = DataLoader(EasyDataset(train_df, is_test=False), batch_size=64, shuffle=True)\ntest_loader = DataLoader(EasyDataset(test_df, is_test=True), batch_size=64, shuffle=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-02T17:23:29.614920Z","iopub.execute_input":"2026-03-02T17:23:29.615147Z","iopub.status.idle":"2026-03-02T17:23:29.717174Z","shell.execute_reply.started":"2026-03-02T17:23:29.615127Z","shell.execute_reply":"2026-03-02T17:23:29.716428Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 2. МОДЕЛЬ (ResNet18 без интернета)\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nmodel = models.resnet18(weights=None) # Важно: weights=None","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-02T17:23:29.718082Z","iopub.execute_input":"2026-03-02T17:23:29.718343Z","iopub.status.idle":"2026-03-02T17:23:29.953550Z","shell.execute_reply.started":"2026-03-02T17:23:29.718319Z","shell.execute_reply":"2026-03-02T17:23:29.952772Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Адаптация под задачу (Ч/Б вход -> 10 классов выход)\nmodel.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)\nmodel.fc = nn.Linear(model.fc.in_features, 10) \nmodel = model.to(device)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-02T17:23:29.954487Z","iopub.execute_input":"2026-03-02T17:23:29.954790Z","iopub.status.idle":"2026-03-02T17:23:30.128050Z","shell.execute_reply.started":"2026-03-02T17:23:29.954756Z","shell.execute_reply":"2026-03-02T17:23:30.127196Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 3. ОБУЧЕНИЕ\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)\ncriterion = nn.CrossEntropyLoss()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-02T17:23:30.130185Z","iopub.execute_input":"2026-03-02T17:23:30.130430Z","iopub.status.idle":"2026-03-02T17:23:30.136114Z","shell.execute_reply.started":"2026-03-02T17:23:30.130408Z","shell.execute_reply":"2026-03-02T17:23:30.135329Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"Training...\")\nfor epoch in range(3): # Кол-во эпох\n    model.train()\n    for img, label in train_loader:\n        img, label = img.to(device), label.to(device)\n        \n        optimizer.zero_grad()\n        loss = criterion(model(img), label)\n        loss.backward()\n        optimizer.step()\n    print(f\"Epoch {epoch+1} finished\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-02T17:23:30.137146Z","iopub.execute_input":"2026-03-02T17:23:30.137716Z","iopub.status.idle":"2026-03-02T17:24:03.289092Z","shell.execute_reply.started":"2026-03-02T17:23:30.137682Z","shell.execute_reply":"2026-03-02T17:24:03.288385Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 4. ПРЕДСКАЗАНИЕ\nmodel.eval()\npreds = []\nwith torch.no_grad():\n    for img in test_loader:\n        img = img.to(device)\n        output = model(img)\n        preds.extend(output.argmax(dim=1).cpu().numpy()) # argmax для классификации","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-02T17:24:03.290173Z","iopub.execute_input":"2026-03-02T17:24:03.290451Z","iopub.status.idle":"2026-03-02T17:24:06.045271Z","shell.execute_reply.started":"2026-03-02T17:24:03.290416Z","shell.execute_reply":"2026-03-02T17:24:06.044654Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 5. СОХРАНЕНИЕ\nsubm = pd.DataFrame({'ImageId': [i + 1 for i in range(len(preds))], 'Label': preds})\nsubm.to_csv(\"submission.csv\", index=False)\nprint(\"Saved submission.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-02T17:26:47.531786Z","iopub.execute_input":"2026-03-02T17:26:47.532491Z","iopub.status.idle":"2026-03-02T17:26:47.577573Z","shell.execute_reply.started":"2026-03-02T17:26:47.532464Z","shell.execute_reply":"2026-03-02T17:26:47.577001Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"subm","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-02T17:26:48.804494Z","iopub.execute_input":"2026-03-02T17:26:48.805277Z","iopub.status.idle":"2026-03-02T17:26:48.812711Z","shell.execute_reply.started":"2026-03-02T17:26:48.805247Z","shell.execute_reply":"2026-03-02T17:26:48.811956Z"}},"outputs":[],"execution_count":null}]}