{"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":"none","dataSources":[{"sourceType":"competition","sourceId":3649,"databundleVersionId":46718}],"dockerImageVersionId":31329,"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 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":"2026-04-23T16:28:42.858891Z","iopub.execute_input":"2026-04-23T16:28:42.859238Z","iopub.status.idle":"2026-04-23T16:28:43.213481Z","shell.execute_reply.started":"2026-04-23T16:28:42.859207Z","shell.execute_reply":"2026-04-23T16:28:43.212587Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!apt-get install p7zip-full -y\n!7z x /kaggle/input/competitions/cifar-10/train.7z -o./","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-23T16:28:43.215599Z","iopub.execute_input":"2026-04-23T16:28:43.216106Z","iopub.status.idle":"2026-04-23T16:37:23.839483Z","shell.execute_reply.started":"2026-04-23T16:28:43.216073Z","shell.execute_reply":"2026-04-23T16:37:23.838049Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(len(os.listdir('./train'))) #ok đã load đủ 50000 ảnh","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-23T16:37:23.841410Z","iopub.execute_input":"2026-04-23T16:37:23.841945Z","iopub.status.idle":"2026-04-23T16:37:23.880825Z","shell.execute_reply.started":"2026-04-23T16:37:23.841903Z","shell.execute_reply":"2026-04-23T16:37:23.879533Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Import lib\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch.nn.functional as F\nfrom PIL import Image #handling image files\nfrom torch.utils.data import Dataset, DataLoader, random_split","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-23T16:37:23.882326Z","iopub.execute_input":"2026-04-23T16:37:23.882775Z","iopub.status.idle":"2026-04-23T16:37:29.567776Z","shell.execute_reply.started":"2026-04-23T16:37:23.882742Z","shell.execute_reply":"2026-04-23T16:37:29.566799Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Config\nepochs = 10\nbatch_size_train = 64\nbatch_size_val = 128\nlearning_rate = 0.001\nlog_interval = 200\n\nrandom_seed = 42\ntorch.backends.cudnn.enabled = False\ntorch.manual_seed(random_seed)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-23T16:37:29.570114Z","iopub.execute_input":"2026-04-23T16:37:29.570977Z","iopub.status.idle":"2026-04-23T16:37:29.585640Z","shell.execute_reply.started":"2026-04-23T16:37:29.570944Z","shell.execute_reply":"2026-04-23T16:37:29.584447Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"transform = transforms.Compose([\n    transforms.Resize((32, 32)),\n    transforms.ToTensor(),\n    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\nclass CIFAR10(Dataset):\n    def __init__(self, csv_file, img_dir, transform=None):\n        self.df = pd.read_csv(csv_file)# tí sẽ cho đọc file labels\n        self.img_dir = img_dir\n        self.transform = transform\n        self.label_mapping = {\n            'airplane':0, 'automobile':1, 'bird':2, 'cat':3, 'deer':4,\n            'dog':5, 'frog':6, 'horse':7, 'ship':8, 'truck':9\n        }#convert labels-->text\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        img_id = str(self.df.iloc[idx, 0]) #Lấy id ảnh\n        img_name = os.path.join(self.img_dir, img_id + \".png\") #tạo path (ví dụ ./train/id.png)\n        image = Image.open(img_name) #mở ảnh\n        label = self.label_mapping[self.df.iloc[idx, 1]] #lấy label từ file labels.csv\n        if self.transform:\n            image = self.transform(image)\n        return image, label\n\ntrain_csv_dir = '/kaggle/input/competitions/cifar-10/trainLabels.csv'\ntrain_dir = './train' \n\nfull_dataset = CIFAR10(csv_file=train_csv_dir, img_dir=train_dir, transform=transform)\ntrain_size = 45000\nval_size = 5000\ntrain_data, val_data = random_split(full_dataset, [train_size, val_size])\n\ntrain_loader = DataLoader(train_data, batch_size=batch_size_train, shuffle=True)\nval_loader = DataLoader(val_data, batch_size=batch_size_val, shuffle=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-23T16:37:29.586981Z","iopub.execute_input":"2026-04-23T16:37:29.587361Z","iopub.status.idle":"2026-04-23T16:37:29.687781Z","shell.execute_reply.started":"2026-04-23T16:37:29.587318Z","shell.execute_reply":"2026-04-23T16:37:29.686769Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Model CNN\nclass CNN(nn.Module):\n    def __init__(self):\n        super(CNN, self).__init__()\n        self.conv1 = nn.Conv2d(3, 32, 3, padding=1)\n        self.bn1 = nn.BatchNorm2d(32)\n        self.conv2 = nn.Conv2d(32, 32, 3, padding=1)\n        self.bn2 = nn.BatchNorm2d(32)\n        self.conv3 = nn.Conv2d(32, 64, 3, padding=1)\n        self.bn3 = nn.BatchNorm2d(64)\n        self.pool = nn.MaxPool2d(2, 2)\n        self.dropout = nn.Dropout(0.3)\n        self.fc1 = nn.Linear(64 * 8 * 8, 128)\n        self.fc2 = nn.Linear(128, 10)\n\n    def forward(self, x):\n        x = F.relu(self.bn1(self.conv1(x)))\n        x = self.pool(F.relu(self.bn2(self.conv2(x))))\n        x = self.dropout(x)\n        x = self.pool(F.relu(self.bn3(self.conv3(x))))\n        x = self.dropout(x)\n        x = x.view(-1, 64 * 8 * 8)\n        x = F.relu(self.fc1(x))\n        x = self.fc2(x)\n        return x\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = CNN().to(device)\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=learning_rate)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-23T16:37:29.689038Z","iopub.execute_input":"2026-04-23T16:37:29.689413Z","iopub.status.idle":"2026-04-23T16:37:29.746182Z","shell.execute_reply.started":"2026-04-23T16:37:29.689373Z","shell.execute_reply":"2026-04-23T16:37:29.744987Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Training\nfor epoch in range(epochs):\n    model.train()\n    running_loss = 0.0\n    for i, (images, labels) in enumerate(train_loader):\n        images, labels = images.to(device), 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        running_loss += loss.item()\n        if (i + 1) % log_interval == 0:\n            avg_loss = running_loss / log_interval\n            print(f\"[Epoch {epoch+1}/{epochs}] Step {i+1}/{len(train_loader)} | Loss: {avg_loss:.4f}\")\n            running_loss = 0.0\n#Tính acc\n    model.eval()\n    correct = 0\n    total = 0\n    with torch.no_grad():\n        for images, labels in val_loader:\n            images, labels = images.to(device), labels.to(device)\n            outputs = model(images)\n            _, predicted = torch.max(outputs.data, 1)\n            total += labels.size(0)\n            correct += (predicted == labels).sum().item()\n    \n    print(f\"--- Epoch {epoch+1} | Validation Accuracy: {100 * correct / total:.4f}% ---\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-23T16:37:29.747658Z","iopub.execute_input":"2026-04-23T16:37:29.748075Z","iopub.status.idle":"2026-04-23T16:57:37.387996Z","shell.execute_reply.started":"2026-04-23T16:37:29.748040Z","shell.execute_reply":"2026-04-23T16:57:37.386967Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!apt-get install p7zip-full -y\n!7z x /kaggle/input/competitions/cifar-10/test.7z -o./","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-23T16:57:37.389365Z","iopub.execute_input":"2026-04-23T16:57:37.389778Z","execution_failed":"2026-04-23T17:20:01.873Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"inv_map = {v: k for k, v in full_dataset.label_mapping.items()} #convert từ tensor trở lại label\n\n# Lấy file test ra pred\nimport glob\ntest_dir = './test'\ntest_files = glob.glob(os.path.join(test_dir, \"*.png\"))\ntest_files.sort(key=lambda x: int(os.path.basename(x).split('.')[0]))\n\nmodel.eval()\nresults = []\n\nwith torch.no_grad():\n    for path in test_files:\n        img_id = os.path.basename(path).split('.')[0]\n        img = Image.open(path)\n        img = transform(img).unsqueeze(0).to(device) # Batch of 1\n        \n        output = model(img)\n        _, pred = torch.max(output, 1)\n        results.append([img_id, inv_map[pred.item()]])\n\n# Save to CSV\ndf_sub = pd.DataFrame(results, columns=['id', 'label'])\ndf_sub.to_csv('submission.csv', index=False)\nprint(\"Saved submission.csv\")","metadata":{"trusted":true,"execution":{"execution_failed":"2026-04-23T17:20:01.873Z"}},"outputs":[],"execution_count":null}]}