{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":3649,"databundleVersionId":46718,"sourceType":"competition"}],"dockerImageVersionId":31040,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install py7zr","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:11:08.240506Z","iopub.execute_input":"2025-06-24T06:11:08.240738Z","iopub.status.idle":"2025-06-24T06:11:08.249919Z","shell.execute_reply.started":"2025-06-24T06:11:08.240712Z","shell.execute_reply":"2025-06-24T06:11:08.249114Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import py7zr\n\n# Путь к архиву\narchive_path = '/kaggle/input/cifar-10/train.7z'\n\n# Папка для распаковки\nextract_to = '/kaggle/working/'\n\n# Распаковка архива\nwith py7zr.SevenZipFile(archive_path, mode='r') as z:\n    z.extractall(path=extract_to)\n\nprint(f\"Архив распакован в {extract_to}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:11:08.250603Z","iopub.execute_input":"2025-06-24T06:11:08.250872Z","iopub.status.idle":"2025-06-24T06:11:08.267414Z","shell.execute_reply.started":"2025-06-24T06:11:08.250846Z","shell.execute_reply":"2025-06-24T06:11:08.266765Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import py7zr\n\n# Путь к архиву\narchive_path = '/kaggle/input/cifar-10/test.7z'\n\n# Папка для распаковки\nextract_to = '/kaggle/working/'\n\n# Распаковка архива\nwith py7zr.SevenZipFile(archive_path, mode='r') as z:\n    z.extractall(path=extract_to)\n\nprint(f\"Архив распакован в {extract_to}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:11:08.268298Z","iopub.execute_input":"2025-06-24T06:11:08.268625Z","iopub.status.idle":"2025-06-24T06:11:08.284681Z","shell.execute_reply.started":"2025-06-24T06:11:08.268598Z","shell.execute_reply":"2025-06-24T06:11:08.283976Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nlabels = pd.read_csv('/kaggle/input/cifar-10/trainLabels.csv')\nlabels","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:11:08.286377Z","iopub.execute_input":"2025-06-24T06:11:08.286589Z","iopub.status.idle":"2025-06-24T06:11:08.658588Z","shell.execute_reply.started":"2025-06-24T06:11:08.286565Z","shell.execute_reply":"2025-06-24T06:11:08.657830Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\n\nle = LabelEncoder()\n\nle.fit(labels['label'])\n\nlabels['label'] = le.transform(labels['label'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:11:08.659376Z","iopub.execute_input":"2025-06-24T06:11:08.659619Z","iopub.status.idle":"2025-06-24T06:11:09.123690Z","shell.execute_reply.started":"2025-06-24T06:11:08.659600Z","shell.execute_reply":"2025-06-24T06:11:09.122784Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nfrom torch.utils.data import Dataset\nfrom PIL import Image","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:11:09.124561Z","iopub.execute_input":"2025-06-24T06:11:09.124973Z","iopub.status.idle":"2025-06-24T06:11:10.894187Z","shell.execute_reply.started":"2025-06-24T06:11:09.124946Z","shell.execute_reply":"2025-06-24T06:11:10.893636Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"d={}\n\nfor i in range(len(labels)):\n    d[str(labels.loc[i,'id'])] = labels.loc[i,'label']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:11:31.439022Z","iopub.execute_input":"2025-06-24T06:11:31.439280Z","iopub.status.idle":"2025-06-24T06:11:32.060435Z","shell.execute_reply.started":"2025-06-24T06:11:31.439261Z","shell.execute_reply":"2025-06-24T06:11:32.059882Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class CustomImageDataset(Dataset):\n    def __init__(self,image_dir,labels,transform=None):\n        self.image_dir = image_dir\n        self.transform = transform\n        self.image_paths = [os.path.join(image_dir,fname) for fname in os.listdir(image_dir) if fname.endswith('.png')]\n    def __len__(self):\n        return len(self.image_paths)\n    def __getitem__(self,idx):\n        image_path = self.image_paths[idx]\n        image = Image.open(image_path).convert('RGB')\n\n        filename = os.path.basename(image_path)\n        label = d[filename[0:len(filename)-4]]\n\n        if self.transform:\n            image = self.transform(image)\n\n        return image,label\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:16:01.136519Z","iopub.execute_input":"2025-06-24T06:16:01.136847Z","iopub.status.idle":"2025-06-24T06:16:01.142123Z","shell.execute_reply.started":"2025-06-24T06:16:01.136824Z","shell.execute_reply":"2025-06-24T06:16:01.141501Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.utils.data import DataLoader\nfrom torchvision import transforms\n\ntransform = transforms.Compose([\n    transforms.Resize(((224,224))),\n    transforms.ToTensor(),\n    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n])\n\ndataset = CustomImageDataset(image_dir='/kaggle/working/train',labels=labels,transform = transform)\ndataloader = DataLoader(dataset,batch_size=8,shuffle=True)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:16:03.015624Z","iopub.execute_input":"2025-06-24T06:16:03.016185Z","iopub.status.idle":"2025-06-24T06:16:03.084107Z","shell.execute_reply.started":"2025-06-24T06:16:03.016160Z","shell.execute_reply":"2025-06-24T06:16:03.083332Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.nn as nn\nimport torch.optim as optim","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:15:05.350541Z","iopub.execute_input":"2025-06-24T06:15:05.350891Z","iopub.status.idle":"2025-06-24T06:15:05.354647Z","shell.execute_reply.started":"2025-06-24T06:15:05.350866Z","shell.execute_reply":"2025-06-24T06:15:05.353892Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_for_train = dataloader","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:16:05.083291Z","iopub.execute_input":"2025-06-24T06:16:05.084132Z","iopub.status.idle":"2025-06-24T06:16:05.087458Z","shell.execute_reply.started":"2025-06-24T06:16:05.084105Z","shell.execute_reply":"2025-06-24T06:16:05.086755Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.nn.functional as F\nimport torch","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:15:08.113642Z","iopub.execute_input":"2025-06-24T06:15:08.114256Z","iopub.status.idle":"2025-06-24T06:15:08.117511Z","shell.execute_reply.started":"2025-06-24T06:15:08.114232Z","shell.execute_reply":"2025-06-24T06:15:08.116956Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torchvision import models, transforms","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:15:09.698631Z","iopub.execute_input":"2025-06-24T06:15:09.699255Z","iopub.status.idle":"2025-06-24T06:15:09.702630Z","shell.execute_reply.started":"2025-06-24T06:15:09.699230Z","shell.execute_reply":"2025-06-24T06:15:09.701940Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.nn as nn\nimport torch.nn.functional as F\n\n\n# Модель\nclass ResNetClassifier(nn.Module):\n    def __init__(self, num_classes=10):\n        super().__init__()\n        self.base = models.resnet18(pretrained=True)\n\n        # Разморозим только последние слои\n        for name, param in self.base.named_parameters():\n            if 'layer4' in name or 'fc' in name:\n                param.requires_grad = True\n            else:\n                param.requires_grad = False\n\n        self.base.fc = nn.Linear(self.base.fc.in_features, num_classes)\n\n    def forward(self, x):\n        return self.base(x)\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = ResNetClassifier(num_classes=10).to(device)\n\n# Loss + Optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=1e-4)\n\n# Обучение\nepochs = 2\nfor epoch in range(epochs):\n    model.train()\n    total_loss = 0\n    correct = 0\n    total = 0\n\n    for images, labels in data_for_train:\n        images = images.to(device)\n        labels = 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        total_loss += loss.item()\n        preds = torch.argmax(outputs, dim=1)\n        correct += (preds == labels).sum().item()\n        total += labels.size(0)\n\n    print(f\"Epoch {epoch+1}/{epochs}, Loss: {total_loss/len(data_for_train):.4f}, Accuracy: {correct/total:.4f}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T07:47:03.271241Z","iopub.execute_input":"2025-06-24T07:47:03.271820Z","iopub.status.idle":"2025-06-24T07:52:35.418046Z","shell.execute_reply.started":"2025-06-24T07:47:03.271794Z","shell.execute_reply":"2025-06-24T07:52:35.417286Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample = pd.read_csv('/kaggle/input/cifar-10/sampleSubmission.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T08:01:03.727927Z","iopub.execute_input":"2025-06-24T08:01:03.728462Z","iopub.status.idle":"2025-06-24T08:01:03.774300Z","shell.execute_reply.started":"2025-06-24T08:01:03.728438Z","shell.execute_reply":"2025-06-24T08:01:03.773768Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class ComfortableData(Dataset):\n    def __init__(self,image_dir,transform=None):\n        self.image_dir = image_dir\n        self.transform = transform\n        self.labels = labels\n        self.image_paths = [os.path.join(image_dir,fname) for fname in os.listdir(image_dir) if fname.endswith('.png')]\n    def __len__(self):\n        return len(self.image_paths)\n    def __getitem__(self,idx):\n        image_path = self.image_paths[idx]\n        image = Image.open(image_path)\n\n        filename = os.path.basename(image_path)\n        \n        if self.transform:\n            image = self.transform(image)\n\n        return image, os.path.basename(image_path)[:-4]\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T08:01:05.293602Z","iopub.execute_input":"2025-06-24T08:01:05.293889Z","iopub.status.idle":"2025-06-24T08:01:05.298905Z","shell.execute_reply.started":"2025-06-24T08:01:05.293868Z","shell.execute_reply":"2025-06-24T08:01:05.298350Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"comfort_data = ComfortableData(image_dir='/kaggle/working/test',transform = transform)\ndata_for_test = DataLoader(comfort_data, batch_size = 8, shuffle=False)\n    \nmodel.eval()  # Важный шаг\npreds = [0]*(len(sample)+1)\n\nwith torch.no_grad():\n    for image, ID in data_for_test:\n        image = image.to(device)\n        predictions = model(image)  # (batch_size, 10)\n        predicted_classes = torch.argmax(predictions, dim=1)  # (batch_size,)\n        \n        # Сохраняем предсказания по ID\n        for i in range(len(ID)):\n            preds[int(ID[i])] = le.inverse_transform([predicted_classes[i].item()])[0]\n            \n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T08:01:14.774518Z","iopub.execute_input":"2025-06-24T08:01:14.774829Z","iopub.status.idle":"2025-06-24T08:14:06.491653Z","shell.execute_reply.started":"2025-06-24T08:01:14.774806Z","shell.execute_reply":"2025-06-24T08:14:06.490891Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\n\n# Преобразуем в DataFrame\ndf = pd.DataFrame({\n    'id': sample['id'],\n    'label': preds[1:len(preds)]\n})\ndf.to_csv(\"submission.csv\", index=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T07:45:04.201913Z","iopub.execute_input":"2025-06-24T07:45:04.202203Z","iopub.status.idle":"2025-06-24T07:45:04.432982Z","shell.execute_reply.started":"2025-06-24T07:45:04.202176Z","shell.execute_reply":"2025-06-24T07:45:04.432256Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in os.listdir('/kaggle/working/test'):\n    print(i)\n    break\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-24T06:11:10.922278Z","iopub.status.idle":"2025-06-24T06:11:10.922559Z","shell.execute_reply.started":"2025-06-24T06:11:10.922392Z","shell.execute_reply":"2025-06-24T06:11:10.922408Z"}},"outputs":[],"execution_count":null}]}