{"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":"nvidiaTeslaT4","dataSources":[{"sourceType":"competition","sourceId":24800,"datasetId":1042002,"databundleVersionId":1831594}],"dockerImageVersionId":31329,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport pandas as pd\nimport numpy as np\nimport cv2\nfrom tqdm import tqdm\nimport pydicom\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, models\n\nfrom sklearn.model_selection import train_test_split","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-03-25T06:57:05.438373Z","iopub.execute_input":"2026-03-25T06:57:05.438965Z","iopub.status.idle":"2026-03-25T06:57:05.955658Z","shell.execute_reply.started":"2026-03-25T06:57:05.438932Z","shell.execute_reply":"2026-03-25T06:57:05.955089Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"DATA_PATH = \"/kaggle/input/competitions/vinbigdata-chest-xray-abnormalities-detection\"\n\nIMG_SIZE = 224\nBATCH_SIZE = 32\nEPOCHS = 5\nLR = 1e-4\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T06:58:40.882899Z","iopub.execute_input":"2026-03-25T06:58:40.883468Z","iopub.status.idle":"2026-03-25T06:58:40.887352Z","shell.execute_reply.started":"2026-03-25T06:58:40.883437Z","shell.execute_reply":"2026-03-25T06:58:40.886708Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv(f\"{DATA_PATH}/train.csv\")\n\nprint(df.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T06:58:43.614118Z","iopub.execute_input":"2026-03-25T06:58:43.614519Z","iopub.status.idle":"2026-03-25T06:58:43.69079Z","shell.execute_reply.started":"2026-03-25T06:58:43.614488Z","shell.execute_reply":"2026-03-25T06:58:43.690081Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pydicom\nimport numpy as np\nimport cv2\n\ndef read_dicom(path):\n    dicom = pydicom.dcmread(path)\n    image = dicom.pixel_array\n\n    # normalize về 0-255\n    image = image - np.min(image)\n    image = image / np.max(image)\n    image = (image * 255).astype(np.uint8)\n\n    # convert sang 3 channel\n    image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)\n\n    return image","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T06:58:46.807674Z","iopub.execute_input":"2026-03-25T06:58:46.808408Z","iopub.status.idle":"2026-03-25T06:58:46.812702Z","shell.execute_reply.started":"2026-03-25T06:58:46.808375Z","shell.execute_reply":"2026-03-25T06:58:46.811868Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class XrayDataset(Dataset):\n    def __init__(self, df, img_dir, transform=None):\n        self.df = df\n        self.img_dir = img_dir\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        row = self.df.iloc[idx]\n\n        img_path = os.path.join(self.img_dir, row[\"image_id\"] + \".dicom\")\n\n        image = read_dicom(img_path)\n        \n        if image is None:\n            raise ValueError(f\"❌ Không tìm thấy ảnh: {img_base}\")\n            \n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n        if self.transform:\n            image = self.transform(image)\n\n        label = torch.tensor(row[\"class_id\"], dtype=torch.long)\n\n        return image, label","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T06:58:50.444464Z","iopub.execute_input":"2026-03-25T06:58:50.444931Z","iopub.status.idle":"2026-03-25T06:58:50.450806Z","shell.execute_reply.started":"2026-03-25T06:58:50.444897Z","shell.execute_reply":"2026-03-25T06:58:50.450045Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"transform = transforms.Compose([\n    transforms.ToPILImage(),\n    transforms.Resize((IMG_SIZE, IMG_SIZE)),\n    transforms.ToTensor(),\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T06:58:53.761917Z","iopub.execute_input":"2026-03-25T06:58:53.762602Z","iopub.status.idle":"2026-03-25T06:58:53.766325Z","shell.execute_reply.started":"2026-03-25T06:58:53.762534Z","shell.execute_reply":"2026-03-25T06:58:53.765543Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df, val_df = train_test_split(df, test_size=0.2, random_state=42)\n\ntrain_dataset = XrayDataset(train_df, f\"{DATA_PATH}/train\", transform)\nval_dataset   = XrayDataset(val_df, f\"{DATA_PATH}/train\", transform)\n\ntrain_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)\nval_loader   = DataLoader(val_dataset, batch_size=BATCH_SIZE)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T06:58:58.607977Z","iopub.execute_input":"2026-03-25T06:58:58.608661Z","iopub.status.idle":"2026-03-25T06:58:58.624145Z","shell.execute_reply.started":"2026-03-25T06:58:58.608622Z","shell.execute_reply":"2026-03-25T06:58:58.623285Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torchvision.models import resnet18, ResNet18_Weights\nmodel = resnet18(weights=ResNet18_Weights.DEFAULT)\n\nnum_classes = df[\"class_id\"].nunique()\nmodel.fc = nn.Linear(model.fc.in_features, num_classes)\n\nmodel = model.to(DEVICE)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T07:00:37.29666Z","iopub.execute_input":"2026-03-25T07:00:37.297526Z","iopub.status.idle":"2026-03-25T07:00:37.507226Z","shell.execute_reply.started":"2026-03-25T07:00:37.297486Z","shell.execute_reply":"2026-03-25T07:00:37.506332Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"criterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=LR)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T07:00:40.902673Z","iopub.execute_input":"2026-03-25T07:00:40.90331Z","iopub.status.idle":"2026-03-25T07:00:40.908133Z","shell.execute_reply.started":"2026-03-25T07:00:40.903275Z","shell.execute_reply":"2026-03-25T07:00:40.907465Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for epoch in range(EPOCHS):\n    model.train()\n    total_loss = 0\n\n    for images, labels in tqdm(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\n        loss.backward()\n        optimizer.step()\n\n        total_loss += loss.item()\n\n    print(f\"Epoch {epoch+1} - Loss: {total_loss/len(train_loader):.4f}\")\n\n    # Validation\n    model.eval()\n    correct = 0\n    total = 0\n\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\n            preds = torch.argmax(outputs, dim=1)\n            correct += (preds == labels).sum().item()\n            total += labels.size(0)\n\n    print(f\"Val Accuracy: {correct/total:.4f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-25T07:00:43.464182Z","iopub.execute_input":"2026-03-25T07:00:43.464865Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"MODEL_PATH = \"/kaggle/working/resnet18_xray.pth\"\n\ntorch.save(model.state_dict(), MODEL_PATH)\n\nprint(\"✅ Saved model!\")","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}