{"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":31328,"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-05-02T07:46:47.335738Z","iopub.execute_input":"2026-05-02T07:46:47.336044Z","iopub.status.idle":"2026-05-02T07:46:47.342990Z","shell.execute_reply.started":"2026-05-02T07:46:47.336019Z","shell.execute_reply":"2026-05-02T07:46:47.342345Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn # Layers\nimport torch.optim as optim # Optimization\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoader, Dataset\nfrom sklearn.model_selection import train_test_split","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-02T07:46:47.345339Z","iopub.execute_input":"2026-05-02T07:46:47.345659Z","iopub.status.idle":"2026-05-02T07:46:47.364641Z","shell.execute_reply.started":"2026-05-02T07:46:47.345637Z","shell.execute_reply":"2026-05-02T07:46:47.363887Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# giải nén file 7z?\n!rm -rf /kaggle/working/train\n!7z x /kaggle/input/competitions/cifar-10/train.7z -o/kaggle/working/ >/dev/null\n#!7z x /kaggle/input/competitions/cifar-10/test.7z -o/kaggle/working/ >/dev/null","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-02T07:46:47.365420Z","iopub.execute_input":"2026-05-02T07:46:47.365660Z","iopub.status.idle":"2026-05-02T07:53:52.519177Z","shell.execute_reply.started":"2026-05-02T07:46:47.365640Z","shell.execute_reply":"2026-05-02T07:53:52.518021Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# mã hóa các label từ chữ sang số\nlabels = pd.read_csv('/kaggle/input/competitions/cifar-10/trainLabels.csv')\nlabels.head()\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\nlabels['label'] = le.fit_transform(labels['label'])\nlabels.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-02T07:53:52.520321Z","iopub.execute_input":"2026-05-02T07:53:52.520583Z","iopub.status.idle":"2026-05-02T07:53:52.550165Z","shell.execute_reply.started":"2026-05-02T07:53:52.520555Z","shell.execute_reply":"2026-05-02T07:53:52.549096Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train, valid = train_test_split(labels,test_size = 0.2, random_state = 42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-02T07:53:52.552376Z","iopub.execute_input":"2026-05-02T07:53:52.552614Z","iopub.status.idle":"2026-05-02T07:53:52.561818Z","shell.execute_reply.started":"2026-05-02T07:53:52.552588Z","shell.execute_reply":"2026-05-02T07:53:52.560884Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# cài cấu hình\nLR = 1e-3\nEPOCH = 100\nBATCH_SIZE = 64\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-02T08:05:53.518240Z","iopub.execute_input":"2026-05-02T08:05:53.518538Z","iopub.status.idle":"2026-05-02T08:05:53.538292Z","shell.execute_reply.started":"2026-05-02T08:05:53.518436Z","shell.execute_reply":"2026-05-02T08:05:53.537178Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# chuyển ảnh về dạng tensor\ntransform = transforms.Compose([\n    transforms.RandomHorizontalFlip(), # Lật ngang ngẫu nhiên\n    transforms.RandomRotation(10),     # Xoay nhẹ\n    transforms.ToTensor(),\n    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-02T08:53:09.150369Z","iopub.execute_input":"2026-05-02T08:53:09.150675Z","iopub.status.idle":"2026-05-02T08:53:09.155334Z","shell.execute_reply.started":"2026-05-02T08:53:09.150646Z","shell.execute_reply":"2026-05-02T08:53:09.154623Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from PIL import Image\n\n# Mở một ảnh bất kỳ trong thư mục đã giải nén\nimg = Image.open('/kaggle/working/train/1.png')\n\n# Xem kích thước (Width, Height)\nprint(f\"Kích thước ảnh (W x H): {img.size}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-02T07:53:52.600948Z","iopub.execute_input":"2026-05-02T07:53:52.601132Z","iopub.status.idle":"2026-05-02T07:53:52.620119Z","shell.execute_reply.started":"2026-05-02T07:53:52.601113Z","shell.execute_reply":"2026-05-02T07:53:52.619145Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# bốc ảnh \nclass DataSet32 (Dataset):\n    def __init__(self, dataframe, img_dir, transform = None):\n        self.df = dataframe\n        self.img_dir = img_dir\n        self.transform = transform\n    def __len__ (self):\n        return len(self.df)\n    def __getitem__(self,idx):\n        img_id = self.df.iloc[idx,0]\n        label = self.df.iloc[idx,1]\n        img_path = os.path.join(self.img_dir, f\"{img_id}.png\")\n        image = Image.open(img_path)\n        if self.transform:\n            image = self.transform(image)\n        return image, label","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-02T08:53:14.738523Z","iopub.execute_input":"2026-05-02T08:53:14.738791Z","iopub.status.idle":"2026-05-02T08:53:14.744527Z","shell.execute_reply.started":"2026-05-02T08:53:14.738769Z","shell.execute_reply":"2026-05-02T08:53:14.743585Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data = DataSet32(train,'/kaggle/working/train' , transform=transform )\ntrain_loader = DataLoader(dataset=train_data,batch_size = 32,shuffle=True)\n\nvalid_data =DataSet32(valid,'/kaggle/working/train',transform = transform)\nvalid_loader = DataLoader(dataset=valid_data,batch_size = 32,shuffle=True)\n\n#test_data = DataSet32(labels,'/kaggle/working/test' , transform=transform )\n#test_loader = DataLoader(dataset=train_data,batch_size = 32,shuffle=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-02T08:53:16.502058Z","iopub.execute_input":"2026-05-02T08:53:16.502349Z","iopub.status.idle":"2026-05-02T08:53:16.507376Z","shell.execute_reply.started":"2026-05-02T08:53:16.502328Z","shell.execute_reply":"2026-05-02T08:53:16.506583Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# tạo model\nclass cnn(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.conv1 = nn.Conv2d(3,32,kernel_size = 3,padding =1)\n        self.pool = nn.MaxPool2d(2,2)\n\n        self.conv2 = nn.Conv2d(32,64,kernel_size = 3,padding =1)\n        self.ReLU = nn.ReLU()\n        self.dropout = nn.Dropout(0.2)\n\n        self.fc1 = nn.Linear(64*8*8,128)\n        self.fc2 = nn.Linear(128,10)\n    def forward(self,x):\n        x= self.pool(self.dropout(self.ReLU(self.conv1(x))))\n        x= self.pool(self.dropout(self.ReLU(self.conv2(x))))\n        x = x.view(x.size(0),-1)\n        x = self.ReLU(self.fc1(x))\n        x = self.fc2(x)\n        return x\n\nmodel = cnn().to(DEVICE)\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=LR)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-02T08:53:18.710384Z","iopub.execute_input":"2026-05-02T08:53:18.710641Z","iopub.status.idle":"2026-05-02T08:53:18.722787Z","shell.execute_reply.started":"2026-05-02T08:53:18.710620Z","shell.execute_reply":"2026-05-02T08:53:18.721449Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def train_and_eval(epoch):\n    # --- TRAINING ---\n    model.train()\n    total_train_loss = 0\n    for images, labels in 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        total_train_loss += loss.item()\n\n    # --- VALIDATION ---\n    model.eval()\n    total_valid_loss = 0\n    correct = 0\n    with torch.no_grad():\n        for images, labels in valid_loader:\n            images, labels = images.to(DEVICE), labels.to(DEVICE)\n            outputs = model(images)\n            loss = criterion(outputs, labels)\n            total_valid_loss += loss.item()\n            \n            _, predicted = torch.max(outputs, 1)\n            correct += (predicted == labels).sum().item()\n\n    avg_train_loss = total_train_loss / len(train_loader)\n    avg_valid_loss = total_valid_loss / len(valid_loader)\n    accuracy = 100 * correct / len(valid_data)\n    \n    print(f\"Epoch [{epoch+1}/{EPOCH}] | Train Loss: {avg_train_loss:.4f} | Valid Loss: {avg_valid_loss:.4f} | Valid Acc: {accuracy:.2f}%\")\n\n# Chạy thử 10 epoch\nfor epoch in range(10):\n    train_and_eval(epoch)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-02T08:53:20.862290Z","iopub.execute_input":"2026-05-02T08:53:20.862623Z","iopub.status.idle":"2026-05-02T09:05:13.105254Z","shell.execute_reply.started":"2026-05-02T08:53:20.862597Z","shell.execute_reply":"2026-05-02T09:05:13.104513Z"}},"outputs":[],"execution_count":null}]}