{"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-03T06:02:14.153063Z","iopub.execute_input":"2024-11-03T06:02:14.153978Z","iopub.status.idle":"2024-11-03T06:02:14.158065Z","shell.execute_reply.started":"2024-11-03T06:02:14.153917Z","shell.execute_reply":"2024-11-03T06:02:14.157128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:02:14.159531Z","iopub.execute_input":"2024-11-03T06:02:14.159806Z","iopub.status.idle":"2024-11-03T06:02:14.173225Z","shell.execute_reply.started":"2024-11-03T06:02:14.159776Z","shell.execute_reply":"2024-11-03T06:02:14.172098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:02:14.174797Z","iopub.execute_input":"2024-11-03T06:02:14.175078Z","iopub.status.idle":"2024-11-03T06:02:14.189463Z","shell.execute_reply.started":"2024-11-03T06:02:14.175047Z","shell.execute_reply":"2024-11-03T06:02:14.18864Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BASE_PATH = f\"/kaggle/input/rsna-atd-512x512-png-v2-dataset\"","metadata":{"execution":{"iopub.status.busy":"2024-11-03T06:02:14.190389Z","iopub.execute_input":"2024-11-03T06:02:14.190697Z","iopub.status.idle":"2024-11-03T06:02:14.198355Z","shell.execute_reply.started":"2024-11-03T06:02:14.190665Z","shell.execute_reply":"2024-11-03T06:02:14.197531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:02:14.200295Z","iopub.execute_input":"2024-11-03T06:02:14.200658Z","iopub.status.idle":"2024-11-03T06:02:14.312029Z","shell.execute_reply.started":"2024-11-03T06:02:14.200608Z","shell.execute_reply":"2024-11-03T06:02:14.311095Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:02:14.313443Z","iopub.execute_input":"2024-11-03T06:02:14.314142Z","iopub.status.idle":"2024-11-03T06:02:14.403794Z","shell.execute_reply.started":"2024-11-03T06:02:14.314105Z","shell.execute_reply":"2024-11-03T06:02:14.402925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.shape, val_data.shape","metadata":{"execution":{"iopub.status.busy":"2024-11-03T06:02:14.404939Z","iopub.execute_input":"2024-11-03T06:02:14.405244Z","iopub.status.idle":"2024-11-03T06:02:14.411099Z","shell.execute_reply.started":"2024-11-03T06:02:14.405209Z","shell.execute_reply":"2024-11-03T06:02:14.410198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:02:14.412533Z","iopub.execute_input":"2024-11-03T06:02:14.41295Z","iopub.status.idle":"2024-11-03T06:02:14.426246Z","shell.execute_reply.started":"2024-11-03T06:02:14.412905Z","shell.execute_reply":"2024-11-03T06:02:14.425372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:02:14.429705Z","iopub.execute_input":"2024-11-03T06:02:14.43008Z","iopub.status.idle":"2024-11-03T06:02:14.440826Z","shell.execute_reply.started":"2024-11-03T06:02:14.430046Z","shell.execute_reply":"2024-11-03T06:02:14.439948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:02:14.442209Z","iopub.execute_input":"2024-11-03T06:02:14.442561Z","iopub.status.idle":"2024-11-03T06:02:14.95182Z","shell.execute_reply.started":"2024-11-03T06:02:14.442516Z","shell.execute_reply":"2024-11-03T06:02:14.95074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:02:14.953167Z","iopub.execute_input":"2024-11-03T06:02:14.953524Z","iopub.status.idle":"2024-11-03T06:02:15.617271Z","shell.execute_reply.started":"2024-11-03T06:02:14.953485Z","shell.execute_reply":"2024-11-03T06:02:15.616344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class SimpleCNN(nn.Module):\n    def __init__(self, num_classes=11):\n        super(SimpleCNN, self).__init__()\n        \n        self.conv_layers = nn.Sequential(\n            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2),  # Giữ padding để không làm giảm kích thước ảnh\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2, stride=2),  # Kích thước ảnh giảm xuống một nửa\n            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=2, stride=2)  # Kích thước ảnh giảm xuống một nửa\n        )\n        \n        # Cập nhật kích thước đầu vào cho lớp Linear\n        self.fc_layers = nn.Sequential(\n            nn.Linear(64 * 64 * 64, 128),  # Cập nhật kích thước sau khi đã tính toán\n            nn.ReLU(),\n            nn.Linear(128, num_classes)\n        )\n        \n    def forward(self, x):\n        x = self.conv_layers(x)\n        print(\"Shape after conv layers:\", x.shape)  # In kích thước sau các lớp convolutional\n        x = x.view(x.size(0), -1)  # Chuyển đổi tensor thành một chiều\n        x = self.fc_layers(x)\n        return x\n","metadata":{"execution":{"iopub.status.busy":"2024-11-03T06:02:15.618457Z","iopub.execute_input":"2024-11-03T06:02:15.61877Z","iopub.status.idle":"2024-11-03T06:02:15.627578Z","shell.execute_reply.started":"2024-11-03T06:02:15.618737Z","shell.execute_reply":"2024-11-03T06:02:15.626626Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:02:15.62889Z","iopub.execute_input":"2024-11-03T06:02:15.62941Z","iopub.status.idle":"2024-11-03T06:02:15.646102Z","shell.execute_reply.started":"2024-11-03T06:02:15.629375Z","shell.execute_reply":"2024-11-03T06:02:15.645133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:02:15.647157Z","iopub.execute_input":"2024-11-03T06:02:15.647459Z","iopub.status.idle":"2024-11-03T06:02:15.662676Z","shell.execute_reply.started":"2024-11-03T06:02:15.647427Z","shell.execute_reply":"2024-11-03T06:02:15.66179Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:02:15.66458Z","iopub.execute_input":"2024-11-03T06:02:15.664931Z","iopub.status.idle":"2024-11-03T06:02:15.672988Z","shell.execute_reply.started":"2024-11-03T06:02:15.664885Z","shell.execute_reply":"2024-11-03T06:02:15.672104Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-4)\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-03T06:02:15.67438Z","iopub.execute_input":"2024-11-03T06:02:15.674709Z","iopub.status.idle":"2024-11-03T06:02:16.022358Z","shell.execute_reply.started":"2024-11-03T06:02:15.674676Z","shell.execute_reply":"2024-11-03T06:02:16.02136Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:02:16.023788Z","iopub.execute_input":"2024-11-03T06:02:16.024184Z","iopub.status.idle":"2024-11-03T06:03:05.496691Z","shell.execute_reply.started":"2024-11-03T06:02:16.024138Z","shell.execute_reply":"2024-11-03T06:03:05.495557Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:03:05.49873Z","iopub.execute_input":"2024-11-03T06:03:05.499749Z","iopub.status.idle":"2024-11-03T06:03:05.875428Z","shell.execute_reply.started":"2024-11-03T06:03:05.499694Z","shell.execute_reply":"2024-11-03T06:03:05.874469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-03T06:03:05.879484Z","iopub.execute_input":"2024-11-03T06:03:05.880109Z","iopub.status.idle":"2024-11-03T09:41:21.875319Z","shell.execute_reply.started":"2024-11-03T06:03:05.880074Z","shell.execute_reply":"2024-11-03T09:41:21.874274Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"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-11-03T09:41:21.876981Z","iopub.execute_input":"2024-11-03T09:41:21.877402Z","iopub.status.idle":"2024-11-03T09:41:21.885121Z","shell.execute_reply.started":"2024-11-03T09:41:21.877357Z","shell.execute_reply":"2024-11-03T09:41:21.88411Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-11-03T09:41:21.88633Z","iopub.execute_input":"2024-11-03T09:41:21.8867Z","iopub.status.idle":"2024-11-03T09:41:22.210612Z","shell.execute_reply.started":"2024-11-03T09:41:21.886653Z","shell.execute_reply":"2024-11-03T09:41:22.209621Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-11-03T09:41:22.212044Z","iopub.execute_input":"2024-11-03T09:41:22.212482Z","iopub.status.idle":"2024-11-03T09:41:38.308618Z","shell.execute_reply.started":"2024-11-03T09:41:22.212433Z","shell.execute_reply":"2024-11-03T09:41:38.307484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-11-03T09:41:38.310137Z","iopub.execute_input":"2024-11-03T09:41:38.310476Z","iopub.status.idle":"2024-11-03T09:41:38.316061Z","shell.execute_reply.started":"2024-11-03T09:41:38.310441Z","shell.execute_reply":"2024-11-03T09:41:38.315194Z"},"trusted":true},"execution_count":null,"outputs":[]}]}