{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":52254,"databundleVersionId":9674523,"sourceType":"competition"},{"sourceId":6211844,"sourceType":"datasetVersion","datasetId":3567114}],"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"Hi I tried convert Keras team's code to Pytorch including all training pipeline as well.","metadata":{}},{"cell_type":"code","source":"#!pip install iterative-stratification","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:14.761967Z","iopub.execute_input":"2024-11-30T21:06:14.762253Z","iopub.status.idle":"2024-11-30T21:06:14.766986Z","shell.execute_reply.started":"2024-11-30T21:06:14.762225Z","shell.execute_reply":"2024-11-30T21:06:14.766019Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom PIL import Image\nimport torch.optim as optim\nfrom torch import nn\n\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:14.771495Z","iopub.execute_input":"2024-11-30T21:06:14.771744Z","iopub.status.idle":"2024-11-30T21:06:20.370257Z","shell.execute_reply.started":"2024-11-30T21:06:14.771719Z","shell.execute_reply":"2024-11-30T21:06:20.369554Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class Config:\n    SEED = 42\n    IMAGE_SIZE = [256, 256]\n    BATCH_SIZE = 32\n    EPOCHS = 200\n    TARGET_COLS  = [\n        \"bowel_injury\", \"extravasation_injury\",\n        \"kidney_healthy\", \"kidney_low\", \"kidney_high\",\n        \"liver_healthy\", \"liver_low\", \"liver_high\",\n        \"spleen_healthy\", \"spleen_low\", \"spleen_high\",\n    ]\n\nconfig = Config()\nprint(f\"Số lượng nhãn mục tiêu: {len(Config.TARGET_COLS)}\")\ntorch.manual_seed(Config.SEED)\n","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:20.371775Z","iopub.execute_input":"2024-11-30T21:06:20.37217Z","iopub.status.idle":"2024-11-30T21:06:20.385648Z","shell.execute_reply.started":"2024-11-30T21:06:20.372112Z","shell.execute_reply":"2024-11-30T21:06:20.384864Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"BASE_PATH = f\"/kaggle/input/rsna-atd-512x512-png-v2-dataset\"","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:20.386685Z","iopub.execute_input":"2024-11-30T21:06:20.38692Z","iopub.status.idle":"2024-11-30T21:06:20.40598Z","shell.execute_reply.started":"2024-11-30T21:06:20.386897Z","shell.execute_reply":"2024-11-30T21:06:20.405198Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# train\ndataframe = pd.read_csv(f\"{BASE_PATH}/train.csv\")\ndataframe[\"image_path\"] = f\"{BASE_PATH}/train_images\"\\\n                    + \"/\" + dataframe.patient_id.astype(str)\\\n                    + \"/\" + dataframe.series_id.astype(str)\\\n                    + \"/\" + dataframe.instance_number.astype(str) +\".png\"\ndataframe = dataframe.drop_duplicates()\n\ndataframe.head(10)","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:20.408393Z","iopub.execute_input":"2024-11-30T21:06:20.409466Z","iopub.status.idle":"2024-11-30T21:06:20.541293Z","shell.execute_reply.started":"2024-11-30T21:06:20.409422Z","shell.execute_reply":"2024-11-30T21:06:20.540204Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Function to handle the split for each group\ndef split_group(group, test_size=0.2):\n    if len(group) == 1:\n        return (group, pd.DataFrame()) if np.random.rand() < test_size else (pd.DataFrame(), group)\n    else:\n        return train_test_split(group, test_size=test_size, random_state=42)\n\n# Initialize the train and validation datasets\ntrain_data = pd.DataFrame()\nval_data = pd.DataFrame()\n\n# Iterate through the groups and split them, handling single-sample groups\nfor _, group in dataframe.groupby(config.TARGET_COLS):\n    train_group, val_group = split_group(group)\n    train_data = pd.concat([train_data, train_group], ignore_index=True)\n    val_data = pd.concat([val_data, val_group], ignore_index=True)","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:20.542651Z","iopub.execute_input":"2024-11-30T21:06:20.543009Z","iopub.status.idle":"2024-11-30T21:06:20.617733Z","shell.execute_reply.started":"2024-11-30T21:06:20.542972Z","shell.execute_reply":"2024-11-30T21:06:20.6169Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data.shape, val_data.shape","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:20.618798Z","iopub.execute_input":"2024-11-30T21:06:20.619042Z","iopub.status.idle":"2024-11-30T21:06:20.624909Z","shell.execute_reply.started":"2024-11-30T21:06:20.619018Z","shell.execute_reply":"2024-11-30T21:06:20.623884Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"paths  = train_data.image_path.tolist()\nlabels = train_data[config.TARGET_COLS].values\n\nclass CustomDataset(Dataset):\n    def __init__(self, paths, labels, transform=None):\n        self.paths = paths\n        self.labels = labels\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.paths)\n\n    def __getitem__(self, idx):\n        image = Image.open(self.paths[idx]).convert('RGB')\n        label = torch.tensor(self.labels[idx], dtype=torch.float32)\n\n        if self.transform:\n            image = self.transform(image)\n\n        return image, label\n\n# Define any image transformations you want to apply, here we also add augmentation. \ntransform = transforms.Compose([\n    transforms.Resize((256, 256)),\n    transforms.RandomResizedCrop(256),   # Random crop and resize\n    transforms.RandomHorizontalFlip(),    # Random horizontal flip\n    transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),  # Color jitter\n    transforms.ToTensor(),\n    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n])","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:20.62612Z","iopub.execute_input":"2024-11-30T21:06:20.626676Z","iopub.status.idle":"2024-11-30T21:06:20.638549Z","shell.execute_reply.started":"2024-11-30T21:06:20.626638Z","shell.execute_reply":"2024-11-30T21:06:20.637717Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# get image_paths and labels\nprint(\"[INFO] Building the dataset...\")\n\ntrain_paths  = train_data.image_path.tolist()\ntrain_labels = train_data[config.TARGET_COLS].values\n\nval_paths  = val_data.image_path.tolist()\nval_labels = val_data[config.TARGET_COLS].values\n\n\n#torch dataset\nbatch_size = 32\n\n# Create the datasets\n\ndataset_train = CustomDataset(train_paths, train_labels, transform=transform)\ntrain_dataloader = DataLoader(dataset_train, batch_size=batch_size, shuffle=True)\n\n\ndataset_val = CustomDataset(val_paths, val_labels, transform=transform)\nval_dataloader = DataLoader(dataset_val, batch_size=batch_size, shuffle=True)\n\n\n# Define your dataset size and other configuration parameters\ndataset_size = len(dataset_train)  # Assuming you have defined 'dataset' earlier\nbatch_size = 32  # Your batch size\ntotal_epochs = 50  # Total number of epochs\n\n# Calculate total train steps\ntotal_train_steps = dataset_size * batch_size * total_epochs\n\n# Define warmup steps as 10% of total train steps\nwarmup_steps = int(total_train_steps * 0.10)\n\n# Define decay steps as the remaining steps after warmup\ndecay_steps = total_train_steps - warmup_steps\n\nprint(f\"Total Train Steps: {total_train_steps}\")\nprint(f\"Warmup Steps: {warmup_steps}\")\nprint(f\"Decay Steps: {decay_steps}\")","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:20.639672Z","iopub.execute_input":"2024-11-30T21:06:20.639989Z","iopub.status.idle":"2024-11-30T21:06:20.653601Z","shell.execute_reply.started":"2024-11-30T21:06:20.639954Z","shell.execute_reply":"2024-11-30T21:06:20.652558Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Loading Data","metadata":{}},{"cell_type":"code","source":"for img, label in train_dataloader:\n  print(img.shape)\n  break","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:20.654677Z","iopub.execute_input":"2024-11-30T21:06:20.655046Z","iopub.status.idle":"2024-11-30T21:06:21.458609Z","shell.execute_reply.started":"2024-11-30T21:06:20.654969Z","shell.execute_reply":"2024-11-30T21:06:21.457715Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#a function to display images\ndef show_images(images, labels):\n    fig, axes = plt.subplots(1, len(images), figsize=(15, 5))\n    for idx, (image, label) in enumerate(zip(images, labels)):\n        image = image.permute(1, 2, 0)  # Convert from (C, H, W) to (H, W, C) for displaying\n        axes[idx].imshow(image)\n        label_str = \", \".join([str(val) for val in label])  # Convert label tensor to string\n        axes[idx].set_title(f\"Labels: {label_str}\")\n        axes[idx].axis(\"off\")\n    plt.show()\n\n# Load a few images for visualization\nnum_images_to_display = 5\nsample_indices = torch.randint(len(dataset_train), size=(num_images_to_display,))\nsample_images = [dataset_train[i][0] for i in sample_indices]\nsample_labels = [dataset_train[i][1] for i in sample_indices]\n\n# Convert label tensors to numpy arrays for display\nsample_labels_np = [label.numpy() for label in sample_labels]\n\n# Display the sample images\nshow_images(sample_images, sample_labels_np)","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:21.462314Z","iopub.execute_input":"2024-11-30T21:06:21.462648Z","iopub.status.idle":"2024-11-30T21:06:22.075725Z","shell.execute_reply.started":"2024-11-30T21:06:21.462621Z","shell.execute_reply":"2024-11-30T21:06:22.074856Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\n\nclass ChannelAttention(nn.Module):\n    def __init__(self, channel):\n        super(ChannelAttention, self).__init__()\n        self.fc = nn.Linear(channel, channel)  # Lớp fully connected duy nhất\n\n    def forward(self, x):\n        avg_pool = x.mean(dim=(2, 3))  # Kích thước: (batch_size, channels)\n        max_pool = x.max(dim=2)[0].max(dim=2)[0]  # Kích thước: (batch_size, channels)\n        \n        # Tính toán trọng số kênh\n        channel_attention = torch.sigmoid(self.fc(avg_pool) + self.fc(max_pool))\n        \n        return x * channel_attention.view(x.size(0), -1, 1, 1)\n\nclass SpatialAttention(nn.Module):\n    def __init__(self):\n        super(SpatialAttention, self).__init__()\n        self.conv1 = nn.Conv2d(2, 1, kernel_size=7, padding=3)  # Lớp tích chập đầu tiên\n        self.conv2 = nn.Conv2d(1, 1, kernel_size=5, padding=2)  # Lớp tích chập thứ hai\n\n    def forward(self, x):\n        avg_pool = x.mean(dim=1, keepdim=True)  # Tính trung bình theo chiều kênh\n        max_pool = x.max(dim=1, keepdim=True)[0]  # Tính giá trị lớn nhất theo chiều kênh\n        concat = torch.cat([avg_pool, max_pool], dim=1)  # Kết hợp hai đầu ra\n        \n        # Áp dụng 2 lớp tích chập\n        spatial_attention = torch.sigmoid(self.conv1(concat))  # Lớp tích chập đầu tiên\n        spatial_attention = torch.sigmoid(self.conv2(spatial_attention))  # Lớp tích chập thứ hai\n        \n        return x * spatial_attention  # Nhân đầu vào với trọng số chú ý không gian\n","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:22.077055Z","iopub.execute_input":"2024-11-30T21:06:22.077883Z","iopub.status.idle":"2024-11-30T21:06:22.088638Z","shell.execute_reply.started":"2024-11-30T21:06:22.077841Z","shell.execute_reply":"2024-11-30T21:06:22.087728Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class SimpleCNN(nn.Module):\n    def __init__(self, num_classes=11):\n        super(SimpleCNN, self).__init__()\n\n        # Khối tích chập 1\n        self.conv1 = nn.Sequential(\n            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1),  # 3 kênh cho ảnh RGB\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2, stride=2),\n        )\n\n        # Channel Attention và Spatial Attention cho khối 1\n        self.channel_attention1 = ChannelAttention(32)\n        self.spatial_attention1 = SpatialAttention()\n\n        # Khối tích chập 2\n        self.conv2 = nn.Sequential(\n            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1),  \n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2, stride=2),\n        )\n        self.channel_attention2 = ChannelAttention(64)\n        self.spatial_attention2 = SpatialAttention()\n\n        # Khối tích chập 3\n        self.conv3 = nn.Sequential(\n            nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1),  \n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2, stride=2),\n        )\n        self.channel_attention3 = ChannelAttention(128)\n        self.spatial_attention3 = SpatialAttention()\n\n        # Tính toán kích thước sau các lớp tích chập\n        dummy_input = torch.randn(1, 3, 256, 256)  # Đảm bảo đầu vào giả có 3 kênh\n        conv_output = self.conv3(self.conv2(self.conv1(dummy_input)))  # Qua ba khối tích chập\n        flattened_size = conv_output.view(1, -1).size(1)  # Kích thước sau khi flatten\n\n        # Fully connected layers\n        self.fc_layers = nn.Sequential(\n            nn.Linear(flattened_size, 128),  # Kích thước đầu vào là flattened_size\n            nn.ReLU(),\n            nn.Linear(128, num_classes)\n        )\n\n    def forward(self, x):\n        # Conv1 + Attention\n        x = self.conv1(x)\n        x = self.channel_attention1(x)\n        x = self.spatial_attention1(x)\n\n        # Conv2 + Attention\n        x = self.conv2(x)\n        x = self.channel_attention2(x)\n        x = self.spatial_attention2(x)\n\n        # Conv3 + Attention\n        x = self.conv3(x)\n        x = self.channel_attention3(x)\n        x = self .spatial_attention3(x)\n\n        # Flatten and fully connected\n        x = x.view(x.size(0), -1)  # Flatten\n        x = self.fc_layers(x)  # Fully connected\n        return x","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:22.090203Z","iopub.execute_input":"2024-11-30T21:06:22.090545Z","iopub.status.idle":"2024-11-30T21:06:22.102831Z","shell.execute_reply.started":"2024-11-30T21:06:22.090507Z","shell.execute_reply":"2024-11-30T21:06:22.101921Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import KFold\n# Số lượng folds\nK = 4  # Bạn có thể chọn 5 hoặc 10 tùy ý\n\n# Khởi tạo K-Fold splitter\nkf = KFold(n_splits=K, shuffle=True, random_state=config.SEED)\n\n# Chuẩn bị dữ liệu\nX = dataframe.image_path.values\ny = dataframe[config.TARGET_COLS].values\n\n# Khởi tạo danh sách để lưu trữ các chỉ số và metric của từng fold\nfold_train_losses = []\nfold_val_losses = []\nfold_val_accuracies = []\nfold_val_f1_scores = []","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:22.103722Z","iopub.execute_input":"2024-11-30T21:06:22.103932Z","iopub.status.idle":"2024-11-30T21:06:22.116819Z","shell.execute_reply.started":"2024-11-30T21:06:22.10391Z","shell.execute_reply":"2024-11-30T21:06:22.116051Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Chia dữ liệu cho từng fold\nfor fold, (train_idx, val_idx) in enumerate(kf.split(X)):\n    X_train, X_val = X[train_idx], X[val_idx]\n    y_train, y_val = y[train_idx], y[val_idx]\n\n    # Tạo dataset và dataloader cho fold hiện tại\n    train_dataset = CustomDataset(paths=X_train, labels=y_train, transform=transform)\n    val_dataset = CustomDataset(paths=X_val, labels=y_val, transform=transform)\n\n    train_dataloader = DataLoader(train_dataset, batch_size=16, shuffle=True, num_workers=4, pin_memory=True)\n    val_dataloader = DataLoader(val_dataset, batch_size=16, shuffle=False, num_workers=4, pin_memory=True)\n\n    # Huấn luyện và đánh giá cho fold hiện tại\n    for epoch in range(config.EPOCHS):\n        # Vòng lặp huấn luyện và validation tương tự như trước\n        ...\n","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:22.117889Z","iopub.execute_input":"2024-11-30T21:06:22.118573Z","iopub.status.idle":"2024-11-30T21:06:22.136726Z","shell.execute_reply.started":"2024-11-30T21:06:22.118546Z","shell.execute_reply":"2024-11-30T21:06:22.135804Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Kiểm tra nếu có GPU thì sử dụng, nếu không sẽ sử dụng CPU\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(f\"Using device: {device}\")","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:22.137724Z","iopub.execute_input":"2024-11-30T21:06:22.138057Z","iopub.status.idle":"2024-11-30T21:06:22.186569Z","shell.execute_reply.started":"2024-11-30T21:06:22.138029Z","shell.execute_reply":"2024-11-30T21:06:22.185647Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = SimpleCNN(num_classes=len(config.TARGET_COLS)).to(device)\ncriterion = nn.BCEWithLogitsLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\nscheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=config.EPOCHS)\nscaler = torch.amp.GradScaler(\"cuda\")  # Sử dụng cho mixed precision","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:22.187766Z","iopub.execute_input":"2024-11-30T21:06:22.188138Z","iopub.status.idle":"2024-11-30T21:06:22.643028Z","shell.execute_reply.started":"2024-11-30T21:06:22.188084Z","shell.execute_reply":"2024-11-30T21:06:22.64212Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"accumulation_steps = 4  # ví dụ: cập nhật sau mỗi 4 batch\nfor i, (images, labels) in enumerate(train_dataloader):\n    images, labels = images.to(device), labels.to(device)\n    with torch.amp.autocast(device_type=device.type):\n        outputs = model(images)\n        loss = criterion(outputs, labels) / accumulation_steps\n    scaler.scale(loss).backward()\n\n    if (i + 1) % accumulation_steps == 0:\n        scaler.step(optimizer)\n        scaler.update()\n        optimizer.zero_grad()  # reset lại gradient","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:06:22.644222Z","iopub.execute_input":"2024-11-30T21:06:22.644561Z","iopub.status.idle":"2024-11-30T21:07:17.537534Z","shell.execute_reply.started":"2024-11-30T21:06:22.644527Z","shell.execute_reply":"2024-11-30T21:07:17.536527Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.utils.checkpoint as checkpoint\n\ndef forward(self, x):\n    x = checkpoint.checkpoint(self.conv_layers, x)\n    x = x.view(x.size(0), -1)\n    x = checkpoint.checkpoint(self.fc_layers, x)\n    return x\nif (epoch + 1) % 10 == 0:  # Lưu sau mỗi 10 epoch\n    torch.save(model.state_dict(), f\"model_checkpoint_epoch_{epoch+1}.pth\")\n","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:07:17.538789Z","iopub.execute_input":"2024-11-30T21:07:17.53907Z","iopub.status.idle":"2024-11-30T21:07:17.687185Z","shell.execute_reply.started":"2024-11-30T21:07:17.539043Z","shell.execute_reply":"2024-11-30T21:07:17.686179Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import f1_score, confusion_matrix\n\n# Vòng lặp huấn luyện cho mỗi fold\nfor epoch in range(config.EPOCHS):\n    model.train()\n    running_loss = 0.0\n    optimizer.zero_grad()  # Reset optimizer\n\n    # Training loop\n    for i, (images, labels) in enumerate(train_dataloader):\n        images, labels = images.to(device), labels.to(device)\n\n        # In kích thước batch chỉ một lần\n        if i == 0:  # Chỉ in cho batch đầu tiên\n            print(\"Kích thước batch trong training:\", images.size())\n        \n        # Sử dụng cú pháp mới của autocast\n        with torch.amp.autocast(device_type=device.type):\n            outputs = model(images)\n            loss = criterion(outputs, labels) / accumulation_steps  # Chia loss theo accumulation steps\n        \n        scaler.scale(loss).backward()  # Tích lũy gradient\n        \n        # Thực hiện bước optimizer mỗi accumulation_steps batch\n        if (i + 1) % accumulation_steps == 0:\n            scaler.step(optimizer)\n            scaler.update()\n            optimizer.zero_grad()  # Reset lại gradient\n\n        running_loss += loss.item() * images.size(0)  # Không nhân với accumulation_steps ở đây\n\n    # Lưu lại train loss\n    epoch_train_loss = running_loss / len(train_dataloader.dataset)\n    fold_train_losses.append(epoch_train_loss)\n\n    # Cập nhật learning rate\n    scheduler.step()\n\n    # Validation loop\n    model.eval()\n    val_loss, correct, total = 0.0, 0, 0\n    all_preds, all_targets = [], []\n\n    with torch.no_grad():\n        for images, labels in val_dataloader:\n            images, labels = images.to(device), labels.to(device)\n\n            # In kích thước batch chỉ một lần\n            if total == 0:  # Chỉ in cho batch đầu tiên\n                print(\"Kích thước batch trong validation:\", images.size())\n\n            # Sử dụng cú pháp mới của autocast trong validation\n            with torch.amp.autocast(device_type=device.type):\n                outputs = model(images)\n                loss = criterion(outputs, labels)\n\n            val_loss += loss.item() * images.size(0)\n\n            preds = torch.sigmoid(outputs) > 0.5\n            correct += (preds.int() == labels.int()).sum().item()\n            total += labels.numel()\n\n            all_preds.append(preds.cpu().numpy())\n            all_targets.append(labels.cpu().numpy())\n\n    # Lưu lại validation loss và accuracy\n    epoch_val_loss = val_loss / len(val_dataloader.dataset)\n    fold_val_losses.append(epoch_val_loss)\n\n    epoch_val_accuracy = 100.0 * correct / total\n    fold_val_accuracies.append(epoch_val_accuracy)\n\n    # Tính F1 score\n    all_preds_np = np.vstack(all_preds)\n    all_targets_np = np.vstack(all_targets)\n    epoch_f1 = f1_score(all_targets_np, all_preds_np, average='macro')\n    fold_val_f1_scores.append(epoch_f1)\n\n    # Tính các chỉ số khác: độ nhạy và độ đặc hiệu cho từng nhãn\n    sensitivity_per_class = []\n    specificity_per_class = []\n\n    for class_idx in range(all_targets_np.shape[1]):\n        tn, fp, fn, tp = confusion_matrix(all_targets_np[:, class_idx], all_preds_np[:, class_idx]).ravel()\n\n        sensitivity = tp / (tp + fn) if (tp + fn) > 0 else 0\n        specificity = tn / (tn + fp) if (tn + fp) > 0 else 0\n\n        sensitivity_per_class.append(sensitivity * 100)\n        specificity_per_class.append(specificity * 100)\n\n    # In các chỉ số sau mỗi epoch\n    print(f\"Epoch [{epoch + 1}/{config.EPOCHS}] - Train Loss: {epoch_train_loss:.4f} - Val Loss: {epoch_val_loss:.4f} - Val Acc: {epoch_val_accuracy:.2f}% - Val F1: {epoch_f1:.4f}\")\n    \n    for class_idx, organ in enumerate([\"Bowel\", \"Extravasation\", \"Liver\", \"Kidney\", \"Spleen\"]):\n        print(f\"{organ} - Sensitivity: {sensitivity_per_class[class_idx]:.2f}%, Specificity: {specificity_per_class[class_idx]:.2f}%\")\n","metadata":{"execution":{"iopub.status.busy":"2024-11-30T21:07:17.688359Z","iopub.execute_input":"2024-11-30T21:07:17.688629Z","iopub.status.idle":"2024-12-01T00:37:39.778257Z","shell.execute_reply.started":"2024-11-30T21:07:17.688604Z","shell.execute_reply":"2024-12-01T00:37:39.777208Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Calculate and print average metrics\navg_sensitivity = np.mean(sensitivity_per_class)\navg_specificity = np.mean(specificity_per_class)\navg_accuracy = epoch_val_accuracy  # Average accuracy for this epoch\navg_f1 = epoch_f1  # Macro F1 score for this epoch\n\n# Print average values\nprint(f\"Average Sensitivity: {avg_sensitivity:.2f}%\")\nprint(f\"Average Specificity: {avg_specificity:.2f}%\")\nprint(f\"Average Accuracy: {avg_accuracy:.2f}%\")\nprint(f\"Average F1 Score (Macro): {avg_f1:.2f}%\")\n","metadata":{"execution":{"iopub.status.busy":"2024-12-01T00:37:39.779705Z","iopub.execute_input":"2024-12-01T00:37:39.780068Z","iopub.status.idle":"2024-12-01T00:37:39.786384Z","shell.execute_reply.started":"2024-12-01T00:37:39.780036Z","shell.execute_reply":"2024-12-01T00:37:39.785571Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Giả sử có dữ liệu cho các giá trị accuracy theo từng epoch\nepochs = range(1, config.EPOCHS + 1)\n\n# Đồ thị cho accuracy và F1 score\nplt.figure(figsize=(8, 6))  # Đặt kích thước cho đồ thị\n\n# Vẽ đồ thị cho accuracy\nplt.plot(epochs, fold_val_accuracies, label='Validation Accuracy', color='blue', linewidth=2)\n\n# Đặt tiêu đề và nhãn cho trục\nplt.title('Validation Accuracy over Epochs', fontsize=16)\nplt.xlabel('Epochs', fontsize=12)\nplt.ylabel('Accuracy (%)', fontsize=12)\n\n# Hiển thị lưới (grid)\nplt.grid(True)\n\n# Hiển thị chú giải (legend)\nplt.legend()\n\n# Hiển thị biểu đồ\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-12-01T00:37:39.787648Z","iopub.execute_input":"2024-12-01T00:37:39.78799Z","iopub.status.idle":"2024-12-01T00:37:40.076974Z","shell.execute_reply.started":"2024-12-01T00:37:39.787953Z","shell.execute_reply":"2024-12-01T00:37:40.076205Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Khởi tạo fold_organ_accuracies ngoài vòng lặp epoch để chỉ khởi tạo một lần\nfold_organ_accuracies = { organ: [] for organ in [\"Bowel\", \"Extravasation\", \"Liver\", \"Kidney\", \"Spleen\"] }\n\n# Validation loop\nmodel.eval()\nval_loss, correct, total = 0.0, 0, 0\ncorrect_per_organ = { \"Bowel\": 0, \"Extravasation\": 0, \"Liver\": 0, \"Kidney\": 0, \"Spleen\": 0 }\ntotal_per_organ = { \"Bowel\": 0, \"Extravasation\": 0, \"Liver\": 0, \"Kidney\": 0, \"Spleen\": 0 }\n\nwith torch.no_grad():\n    for images, labels in val_dataloader:\n        images, labels = images.to(device), labels.to(device)\n\n        # Sử dụng cú pháp mới của autocast trong validation\n        with torch.amp.autocast(device_type=device.type):\n            outputs = model(images)\n            loss = criterion(outputs, labels)\n\n        val_loss += loss.item() * images.size(0)\n\n        preds = torch.sigmoid(outputs) > 0.5\n\n        # Cập nhật đúng và tổng số cho từng bộ phận\n        for organ_idx, organ_name in enumerate([\"Bowel\", \"Extravasation\", \"Liver\", \"Kidney\", \"Spleen\"]):\n            correct_per_organ[organ_name] += (preds[:, organ_idx].int() == labels[:, organ_idx].int()).sum().item()\n            total_per_organ[organ_name] += labels[:, organ_idx].numel()\n\n# Tính toán accuracy cho từng bộ phận\naccuracies_per_organ = { organ: 100.0 * correct_per_organ[organ] / total_per_organ[organ] for organ in correct_per_organ }\n","metadata":{"execution":{"iopub.status.busy":"2024-12-01T00:37:40.078302Z","iopub.execute_input":"2024-12-01T00:37:40.078672Z","iopub.status.idle":"2024-12-01T00:37:55.576845Z","shell.execute_reply.started":"2024-12-01T00:37:40.078632Z","shell.execute_reply":"2024-12-01T00:37:55.575727Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# In ra độ chính xác (accuracy) cho từng bộ phận sau mỗi epoch\nfor organ, accuracy in accuracies_per_organ.items():\n    print(f\"{organ} Accuracy: {accuracy:.2f}%\")\n","metadata":{"execution":{"iopub.status.busy":"2024-12-01T00:37:55.578454Z","iopub.execute_input":"2024-12-01T00:37:55.578856Z","iopub.status.idle":"2024-12-01T00:37:55.584401Z","shell.execute_reply.started":"2024-12-01T00:37:55.578813Z","shell.execute_reply":"2024-12-01T00:37:55.583545Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np\n\n# Set the model to evaluation mode\nmodel.eval()\n\n# Select a random image from the validation dataset\nrandom_index = np.random.randint(len(dataset_val))\nimage, label = dataset_val[random_index]\n\n# Move the image to the GPU if available\nimage = image.to('cuda')\n\n# Pass the image through the model\nwith torch.no_grad():\n    output = model(image.unsqueeze(0))  # Unsqueeze to add batch dimension\n\n# Convert the output logits to probabilities using sigmoid function\npredicted_probs = torch.sigmoid(output)[0]\n\n# Convert predicted probabilities to binary predictions\npredicted_labels = (predicted_probs > 0.5).int()\n\n\n# Display the image, actual labels, and predicted labels\nplt.imshow(image.permute(1, 2, 0).cpu())  # Move image to CPU and change channel order\n#plt.title(f\"Actual Labels: {label}\\nPredicted Labels: {predicted_labels}\")\nplt.title(f\"Actual Labels: {label}\\nPredicted Labels: {predicted_labels}\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T00:37:55.585498Z","iopub.execute_input":"2024-12-01T00:37:55.585834Z","iopub.status.idle":"2024-12-01T00:37:55.996864Z","shell.execute_reply.started":"2024-12-01T00:37:55.585808Z","shell.execute_reply":"2024-12-01T00:37:55.996002Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\nimport numpy as np\n\n# Convert targets and predictions to numpy arrays\nall_preds_np = np.vstack(all_preds)\nall_targets_np = np.vstack(all_targets)\n\n# Các bộ phận cần tính ma trận nhầm lẫn\norgans = [\"Bowel\", \"Extravasation\", \"Liver\", \"Kidney\", \"Spleen\"]\n\n# Lặp qua từng bộ phận và tính toán ma trận nhầm lẫn\nfor i, organ in enumerate(organs):\n    # Tạo ma trận nhầm lẫn cho từng bộ phận (sử dụng lớp tương ứng)\n    conf_matrix = confusion_matrix(all_targets_np[:, i], all_preds_np[:, i])\n    \n    # Hiển thị ma trận nhầm lẫn dưới dạng heatmap\n    plt.figure(figsize=(8, 6))\n    sns.heatmap(conf_matrix, annot=True, fmt=\"d\", cmap=\"Blues\", xticklabels=[\"Healthy\", \"Injury\"], yticklabels=[\"Healthy\", \"Injury\"])\n    plt.title(f'{organ} Confusion Matrix', fontsize=16)\n    plt.xlabel('Predicted', fontsize=12)\n    plt.ylabel('True', fontsize=12)\n    plt.show()\n\n    # In ra ma trận nhầm lẫn cho từng bộ phận\n    print(f\"{organ} Confusion Matrix:\")\n    print(conf_matrix)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T00:37:55.998157Z","iopub.execute_input":"2024-12-01T00:37:55.998509Z","iopub.status.idle":"2024-12-01T00:37:57.520675Z","shell.execute_reply.started":"2024-12-01T00:37:55.998471Z","shell.execute_reply":"2024-12-01T00:37:57.519781Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Vẽ đồ thị cho độ chính xác của validation qua các epoch\nplt.figure(figsize=(14, 6))\n\n# Độ chính xác validation\nplt.subplot(2, 2, 1)\nplt.plot(range(1, config.EPOCHS + 1), fold_val_accuracies, label=\"Val Accuracy\", color=\"blue\", linewidth=2)\nplt.title(\"Validation Accuracy Over Epochs\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy (%)\")\nplt.grid(True)\n\n# F1 Score\nplt.subplot(2, 2, 2)\nplt.plot(range(1, config.EPOCHS + 1), fold_val_f1_scores, label=\"Val F1 Score\", color=\"green\", linewidth=2)\nplt.title(\"Validation F1 Score Over Epochs\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"F1 Score\")\nplt.grid(True)\n\n# Sensitivity (Average over all classes)\navg_sensitivity = [np.mean(sensitivity_per_class[:epoch+1]) for epoch in range(config.EPOCHS)]\nplt.subplot(2, 2, 3)\nplt.plot(range(1, config.EPOCHS + 1), avg_sensitivity, label=\"Avg Sensitivity\", color=\"red\", linewidth=2)\nplt.title(\"Average Sensitivity Over Epochs\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Sensitivity (%)\")\nplt.grid(True)\n\n# Specificity (Average over all classes)\navg_specificity = [np.mean(specificity_per_class[:epoch+1]) for epoch in range(config.EPOCHS)]\nplt.subplot(2, 2, 4)\nplt.plot(range(1, config.EPOCHS + 1), avg_specificity, label=\"Avg Specificity\", color=\"purple\", linewidth=2)\nplt.title(\"Average Specificity Over Epochs\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Specificity (%)\")\nplt.grid(True)\n\n# Hiển thị tất cả các đồ thị\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-01T00:37:57.522199Z","iopub.execute_input":"2024-12-01T00:37:57.522819Z","iopub.status.idle":"2024-12-01T00:37:58.236938Z","shell.execute_reply.started":"2024-12-01T00:37:57.522773Z","shell.execute_reply":"2024-12-01T00:37:58.236014Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Vẽ đồ thị cho độ chính xác của validation qua các epoch\nplt.figure(figsize=(14, 6))\n\n# Độ chính xác validation\nplt.subplot(2, 2, 1)\nplt.plot(range(1, config.EPOCHS + 1), fold_val_accuracies, label=\"Val Accuracy\", color=\"blue\", linewidth=2)\nplt.title(\"Validation Accuracy Over Epochs\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy (%)\")\nplt.grid(True)\n\n# F1 Score\nplt.subplot(2, 2, 2)\nplt.plot(range(1, config.EPOCHS + 1), fold_val_f1_scores, label=\"Val F1 Score\", color=\"green\", linewidth=2)\nplt.title(\"Validation F1 Score Over Epochs\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"F1 Score\")\nplt.grid(True)\n\n# Sensitivity (Average over all classes)\navg_sensitivity = [np.mean(sensitivity_per_class[:epoch+1]) for epoch in range(config.EPOCHS)]\nplt.subplot(2, 2, 3)\nplt.plot(range(1, config.EPOCHS + 1), avg_sensitivity, label=\"Avg Sensitivity\", color=\"red\", linewidth=2)\nplt.title(\"Average Sensitivity Over Epochs\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Sensitivity (%)\")\nplt.grid(True)\n\n# Specificity (Average over all classes)\navg_specificity = [np.mean(specificity_per_class[:epoch+1]) for epoch in range(config.EPOCHS)]\nplt.subplot(2, 2, 4)\nplt.plot(range(1, config.EPOCHS + 1), avg_specificity, label=\"Avg Specificity\", color=\"purple\", linewidth=2)\nplt.title(\"Average Specificity Over Epochs\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Specificity (%)\")\nplt.grid(True)\n\n# Hiển thị tất cả các đồ thị\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Vẽ đồ thị độ chính xác cho từng bộ phận\nplt.figure(figsize=(14, 10))\n\nplt.plot(range(1, config.EPOCHS + 1), accuracies_bowel, label='Bowel Accuracy', color='blue', linewidth=2)\nplt.plot(range(1, config.EPOCHS + 1), accuracies_extravasation, label='Extravasation Accuracy', color='red', linewidth=2)\nplt.plot(range(1, config.EPOCHS + 1), accuracies_liver, label='Liver Accuracy', color='green', linewidth=2)\nplt.plot(range(1, config.EPOCHS + 1), accuracies_kidney, label='Kidney Accuracy', color='purple', linewidth=2)\nplt.plot(range(1, config.EPOCHS + 1), accuracies_spleen, label='Spleen Accuracy', color='orange', linewidth=2)\n\nplt.title('Accuracy for Each Organ Over Epochs', fontsize=16)\nplt.xlabel('Epochs', fontsize=12)\nplt.ylabel('Accuracy (%)', fontsize=12)\nplt.grid(True)\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Đảm bảo rằng bạn đã tính toán và lưu trữ giá trị loss qua các epoch\nepochs = range(1, config.EPOCHS + 1)\n\n# Vẽ đồ thị cho Train Loss và Validation Loss\nplt.figure(figsize=(10, 6))\n\n# Vẽ Train Loss\nplt.plot(epochs, fold_train_losses, label='Train Loss', color='blue', linestyle='-', marker='o')\n\n# Vẽ Validation Loss\nplt.plot(epochs, fold_val_losses, label='Validation Loss', color='red', linestyle='-', marker='x')\n\n# Thêm tiêu đề và nhãn cho các trục\nplt.title('Train Loss and Validation Loss over Epochs', fontsize=16)\nplt.xlabel('Epochs', fontsize=12)\nplt.ylabel('Loss', fontsize=12)\n\n# Thêm lưới cho dễ nhìn\nplt.grid(True)\n\n# Hiển thị chú thích để phân biệt giữa Train Loss và Validation Loss\nplt.legend()\n\n# Hiển thị đồ thị\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Tạo dữ liệu từ các danh sách lưu trữ độ chính xác của từng bộ phận\naccuracies_data = [\n    accuracies_bowel,\n    accuracies_extravasation,\n    accuracies_liver,\n    accuracies_kidney,\n    accuracies_spleen\n]\n\n# Tạo nhãn cho mỗi bộ phận\norgan_names = ['Bowel', 'Extravasation', 'Liver', 'Kidney', 'Spleen']\n\n# Tạo đồ thị boxplot\nplt.figure(figsize=(10, 6))\nsns.boxplot(data=accuracies_data)\n\n# Thêm tiêu đề và nhãn cho trục\nplt.title('Boxplot of Accuracy for Different Organs')\nplt.ylabel('Accuracy (%)')\nplt.xticks(ticks=range(len(organ_names)), labels=organ_names)\n\n# Hiển thị đồ thị\nplt.show()\n","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}