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
"outputs": [],
|
| 15 |
+
"source": [
|
| 16 |
+
"import os\n",
|
| 17 |
+
"import shutil\n",
|
| 18 |
+
"import random\n",
|
| 19 |
+
"import multiprocessing\n",
|
| 20 |
+
"from copy import deepcopy\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"def recursive_copy_dicom(src_folder, dest_folder, file_counter):\n",
|
| 23 |
+
" \"\"\"\n",
|
| 24 |
+
" Recursively finds and copies DICOM files from the source to the destination folder, renaming them sequentially.\n",
|
| 25 |
+
" \n",
|
| 26 |
+
" :param src_folder: The source folder containing DICOM files (including subdirectories).\n",
|
| 27 |
+
" :param dest_folder: The destination folder where the files will be copied and renamed.\n",
|
| 28 |
+
" :param file_counter: The sequential counter for renaming files.\n",
|
| 29 |
+
" :return: List of renamed files for further splitting.\n",
|
| 30 |
+
" \"\"\"\n",
|
| 31 |
+
" renamed_files = []\n",
|
| 32 |
+
"\n",
|
| 33 |
+
" for root, dirs, files in os.walk(src_folder):\n",
|
| 34 |
+
" for dicom_file in files:\n",
|
| 35 |
+
" if dicom_file.lower().endswith('.dcm'):\n",
|
| 36 |
+
" # Get full path of the source file\n",
|
| 37 |
+
" src_file_path = os.path.join(root, dicom_file)\n",
|
| 38 |
+
" \n",
|
| 39 |
+
" # Create the new file path in the destination folder\n",
|
| 40 |
+
" dest_file_path = os.path.join(dest_folder, f\"{file_counter}.dcm\")\n",
|
| 41 |
+
" \n",
|
| 42 |
+
" # Copy and rename the file\n",
|
| 43 |
+
" shutil.copy(src_file_path, dest_file_path)\n",
|
| 44 |
+
" \n",
|
| 45 |
+
" # Append the renamed file to the list\n",
|
| 46 |
+
" renamed_files.append(f\"{file_counter}.dcm\")\n",
|
| 47 |
+
" \n",
|
| 48 |
+
" # Increment the file counter for the next file\n",
|
| 49 |
+
" file_counter += 1\n",
|
| 50 |
+
"\n",
|
| 51 |
+
" return renamed_files\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"def split_and_transfer_files(file_list, dest_folder, split_factor):\n",
|
| 54 |
+
" \"\"\"\n",
|
| 55 |
+
" Splits the list of renamed files into train and val sets and moves them into the appropriate folders.\n",
|
| 56 |
+
" \n",
|
| 57 |
+
" :param file_list: List of renamed DICOM files.\n",
|
| 58 |
+
" :param dest_folder: Destination folder where train and val subfolders will be created.\n",
|
| 59 |
+
" :param split_factor: The ratio of files to go into the train subfolder.\n",
|
| 60 |
+
" \"\"\"\n",
|
| 61 |
+
" # Ensure the destination folder and subfolders exist\n",
|
| 62 |
+
" train_folder = os.path.join(dest_folder, 'train')\n",
|
| 63 |
+
" val_folder = os.path.join(dest_folder, 'val')\n",
|
| 64 |
+
" \n",
|
| 65 |
+
" if not os.path.exists(train_folder):\n",
|
| 66 |
+
" os.makedirs(train_folder)\n",
|
| 67 |
+
" \n",
|
| 68 |
+
" if not os.path.exists(val_folder):\n",
|
| 69 |
+
" os.makedirs(val_folder)\n",
|
| 70 |
+
"\n",
|
| 71 |
+
" # Shuffle the files for randomness\n",
|
| 72 |
+
" random.shuffle(file_list)\n",
|
| 73 |
+
"\n",
|
| 74 |
+
" # Calculate the number of files for the train and validation sets\n",
|
| 75 |
+
" split_index = int(len(file_list) * split_factor)\n",
|
| 76 |
+
" \n",
|
| 77 |
+
" # Split the files into train and val sets\n",
|
| 78 |
+
" train_files = file_list[:split_index]\n",
|
| 79 |
+
" val_files = file_list[split_index:]\n",
|
| 80 |
+
"\n",
|
| 81 |
+
" # Move the files to the respective folders\n",
|
| 82 |
+
" for file in train_files:\n",
|
| 83 |
+
" src_file = os.path.join(dest_folder, file)\n",
|
| 84 |
+
" dest_file = os.path.join(train_folder, file)\n",
|
| 85 |
+
" shutil.move(src_file, dest_file)\n",
|
| 86 |
+
" print(f\"Moved {file} to train folder\")\n",
|
| 87 |
+
" \n",
|
| 88 |
+
" for file in val_files:\n",
|
| 89 |
+
" src_file = os.path.join(dest_folder, file)\n",
|
| 90 |
+
" dest_file = os.path.join(val_folder, file)\n",
|
| 91 |
+
" shutil.move(src_file, dest_file)\n",
|
| 92 |
+
" print(f\"Moved {file} to val folder\")\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"def process_dicom_files(src_folder, dest_folder, split_factor):\n",
|
| 95 |
+
" \"\"\"\n",
|
| 96 |
+
" Recursively finds, renames, copies DICOM files, and splits them into train and val sets.\n",
|
| 97 |
+
" \n",
|
| 98 |
+
" :param src_folder: The source folder containing DICOM files (including subdirectories).\n",
|
| 99 |
+
" :param dest_folder: The destination folder where the renamed files and the train/val split will be created.\n",
|
| 100 |
+
" :param split_factor: The ratio of files to go into the train subfolder.\n",
|
| 101 |
+
" \"\"\"\n",
|
| 102 |
+
" # Ensure the destination folder exists\n",
|
| 103 |
+
" if not os.path.exists(dest_folder):\n",
|
| 104 |
+
" os.makedirs(dest_folder)\n",
|
| 105 |
+
"\n",
|
| 106 |
+
" # Initialize file counter\n",
|
| 107 |
+
" file_counter = 1\n",
|
| 108 |
+
"\n",
|
| 109 |
+
" # Recursively copy DICOM files and rename them\n",
|
| 110 |
+
" renamed_files = recursive_copy_dicom(src_folder, dest_folder, file_counter)\n",
|
| 111 |
+
"\n",
|
| 112 |
+
" # Step 2: Split the renamed files into train and val sets\n",
|
| 113 |
+
" split_and_transfer_files(renamed_files, dest_folder, split_factor)\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"# Example usage:\n",
|
| 116 |
+
"src_folder = r\"F:\\TCIA\" # Replace with your source folder path\n",
|
| 117 |
+
"dest_folder = r\"F:\\TCIA_Split\" # Destination folder for the renamed files and train/val split\n",
|
| 118 |
+
"split_factor = 0.9 # 90% of files will go to 'train', 10% will go to 'val'\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"# Perform the entire process\n",
|
| 121 |
+
"process_dicom_files(src_folder, dest_folder, split_factor)"
|
| 122 |
+
]
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "markdown",
|
| 126 |
+
"metadata": {},
|
| 127 |
+
"source": [
|
| 128 |
+
"### Basic U-Net"
|
| 129 |
+
]
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"execution_count": null,
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"outputs": [],
|
| 136 |
+
"source": [
|
| 137 |
+
"import torch\n",
|
| 138 |
+
"import torch.nn as nn\n",
|
| 139 |
+
"import torch.nn.functional as F\n",
|
| 140 |
+
"import pydicom\n",
|
| 141 |
+
"import numpy as np\n",
|
| 142 |
+
"from torch.utils.data import Dataset, DataLoader\n",
|
| 143 |
+
"import os\n",
|
| 144 |
+
"from torch.utils.checkpoint import checkpoint\n",
|
| 145 |
+
"from tqdm import tqdm # Import tqdm for progress bar\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"class MedicalImageDataset(Dataset):\n",
|
| 150 |
+
" def __init__(self, dicom_dir):\n",
|
| 151 |
+
" self.dicom_files = [os.path.join(dicom_dir, f) for f in os.listdir(dicom_dir) if f.endswith('.dcm')]\n",
|
| 152 |
+
" \n",
|
| 153 |
+
" def __len__(self):\n",
|
| 154 |
+
" return len(self.dicom_files)\n",
|
| 155 |
+
" \n",
|
| 156 |
+
" def __getitem__(self, idx):\n",
|
| 157 |
+
" # Read DICOM file and normalize\n",
|
| 158 |
+
" dcm = pydicom.dcmread(self.dicom_files[idx])\n",
|
| 159 |
+
" image = dcm.pixel_array.astype(float)\n",
|
| 160 |
+
" image = (image - image.min()) / (image.max() - image.min())\n",
|
| 161 |
+
" \n",
|
| 162 |
+
" # Convert to tensor\n",
|
| 163 |
+
" image_tensor = torch.from_numpy(image).float().unsqueeze(0)\n",
|
| 164 |
+
" return image_tensor, image_tensor\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"class UNetBlock(nn.Module):\n",
|
| 167 |
+
" def __init__(self, in_channels, out_channels):\n",
|
| 168 |
+
" super().__init__()\n",
|
| 169 |
+
" self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1)\n",
|
| 170 |
+
" self.bn1 = nn.BatchNorm2d(out_channels)\n",
|
| 171 |
+
" self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1)\n",
|
| 172 |
+
" self.bn2 = nn.BatchNorm2d(out_channels)\n",
|
| 173 |
+
" \n",
|
| 174 |
+
" def forward(self, x):\n",
|
| 175 |
+
" x = F.relu(self.bn1(self.conv1(x)))\n",
|
| 176 |
+
" x = F.relu(self.bn2(self.conv2(x)))\n",
|
| 177 |
+
" return x\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"class UNet(nn.Module):\n",
|
| 180 |
+
" def __init__(self, in_channels=1, out_channels=1):\n",
|
| 181 |
+
" super().__init__()\n",
|
| 182 |
+
" # Encoder\n",
|
| 183 |
+
" self.enc1 = UNetBlock(in_channels, 64)\n",
|
| 184 |
+
" self.enc2 = UNetBlock(64, 128)\n",
|
| 185 |
+
" self.enc3 = UNetBlock(128, 256)\n",
|
| 186 |
+
" \n",
|
| 187 |
+
" # Decoder\n",
|
| 188 |
+
" self.dec3 = UNetBlock(256 + 128, 128) # Adjust for concatenation with skip connection\n",
|
| 189 |
+
" self.dec2 = UNetBlock(128 + 64, 64) # Adjust for concatenation with skip connection\n",
|
| 190 |
+
" self.dec1 = UNetBlock(64, out_channels)\n",
|
| 191 |
+
" \n",
|
| 192 |
+
" # Pooling and upsampling\n",
|
| 193 |
+
" self.pool = nn.MaxPool2d(2, 2)\n",
|
| 194 |
+
" self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n",
|
| 195 |
+
" \n",
|
| 196 |
+
" def forward(self, x):\n",
|
| 197 |
+
" # Encoder path\n",
|
| 198 |
+
" e1 = checkpoint(self.enc1, x)\n",
|
| 199 |
+
" e2 = checkpoint(self.enc2, self.pool(e1))\n",
|
| 200 |
+
" e3 = checkpoint(self.enc3, self.pool(e2))\n",
|
| 201 |
+
" \n",
|
| 202 |
+
" # Decoder path with skip connections\n",
|
| 203 |
+
" d3 = self.upsample(e3)\n",
|
| 204 |
+
" d3 = torch.cat([d3, e2], dim=1) # Concatenate along channels\n",
|
| 205 |
+
" d3 = checkpoint(self.dec3, d3)\n",
|
| 206 |
+
" \n",
|
| 207 |
+
" d2 = self.upsample(d3)\n",
|
| 208 |
+
" d2 = torch.cat([d2, e1], dim=1) # Concatenate along channels\n",
|
| 209 |
+
" d2 = checkpoint(self.dec2, d2)\n",
|
| 210 |
+
" \n",
|
| 211 |
+
" d1 = self.dec1(d2) # No checkpointing for final output layer\n",
|
| 212 |
+
" \n",
|
| 213 |
+
" return d1\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"def calculate_loss(model, dataloader, criterion):\n",
|
| 216 |
+
" model.eval()\n",
|
| 217 |
+
" total_loss = 0\n",
|
| 218 |
+
" with torch.no_grad():\n",
|
| 219 |
+
" for images, targets in dataloader:\n",
|
| 220 |
+
" images, targets = images.to(device), targets.to(device)\n",
|
| 221 |
+
" outputs = model(images)\n",
|
| 222 |
+
" loss = criterion(outputs, targets)\n",
|
| 223 |
+
" total_loss += loss.item()\n",
|
| 224 |
+
" return total_loss / len(dataloader)\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"def calculate_psnr(output, target, max_pixel=1.0):\n",
|
| 227 |
+
" # Ensure the values are in the correct range\n",
|
| 228 |
+
" mse = F.mse_loss(output, target)\n",
|
| 229 |
+
" psnr = 20 * torch.log10(max_pixel / torch.sqrt(mse))\n",
|
| 230 |
+
" return psnr.item()\n",
|
| 231 |
+
"\n",
|
| 232 |
+
"def calculate_loss_and_psnr(model, dataloader, criterion):\n",
|
| 233 |
+
" model.eval()\n",
|
| 234 |
+
" total_loss = 0\n",
|
| 235 |
+
" total_psnr = 0\n",
|
| 236 |
+
" num_batches = len(dataloader)\n",
|
| 237 |
+
" \n",
|
| 238 |
+
" with torch.no_grad():\n",
|
| 239 |
+
" for images, targets in dataloader:\n",
|
| 240 |
+
" images, targets = images.to(device), targets.to(device)\n",
|
| 241 |
+
" outputs = model(images)\n",
|
| 242 |
+
" \n",
|
| 243 |
+
" # Calculate MSE loss\n",
|
| 244 |
+
" loss = criterion(outputs, targets)\n",
|
| 245 |
+
" total_loss += loss.item()\n",
|
| 246 |
+
" \n",
|
| 247 |
+
" # Calculate PSNR\n",
|
| 248 |
+
" psnr = calculate_psnr(outputs, targets)\n",
|
| 249 |
+
" total_psnr += psnr\n",
|
| 250 |
+
" \n",
|
| 251 |
+
" avg_loss = total_loss / num_batches\n",
|
| 252 |
+
" avg_psnr = total_psnr / num_batches\n",
|
| 253 |
+
" \n",
|
| 254 |
+
" return avg_loss, avg_psnr\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"best_val_loss = float('inf')\n",
|
| 257 |
+
"best_model_path = 'best_model.pth'\n",
|
| 258 |
+
"\n",
|
| 259 |
+
"def train_unet(dicom_dir, val_dicom_dir, epochs=50, batch_size=4, grad_accumulation_steps=2):\n",
|
| 260 |
+
" # Dataset and DataLoader\n",
|
| 261 |
+
" dataset = MedicalImageDataset(dicom_dir)\n",
|
| 262 |
+
" train_dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)\n",
|
| 263 |
+
" val_dataset = MedicalImageDataset(val_dicom_dir)\n",
|
| 264 |
+
" val_dataloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)\n",
|
| 265 |
+
" \n",
|
| 266 |
+
" # Model, Loss, Optimizer\n",
|
| 267 |
+
" model = UNet().to(device)\n",
|
| 268 |
+
" criterion = nn.MSELoss()\n",
|
| 269 |
+
" optimizer = torch.optim.Adam(model.parameters(), lr=0.0001)\n",
|
| 270 |
+
" \n",
|
| 271 |
+
" # Training loop with tqdm\n",
|
| 272 |
+
" for epoch in range(epochs):\n",
|
| 273 |
+
" model.train()\n",
|
| 274 |
+
" total_loss = 0\n",
|
| 275 |
+
" optimizer.zero_grad()\n",
|
| 276 |
+
" \n",
|
| 277 |
+
" with tqdm(train_dataloader, unit=\"batch\", desc=f\"Epoch {epoch+1}/{epochs}\") as tepoch:\n",
|
| 278 |
+
" for i, (images, targets) in enumerate(tepoch):\n",
|
| 279 |
+
" images, targets = images.to(device), targets.to(device)\n",
|
| 280 |
+
" \n",
|
| 281 |
+
" # Forward pass\n",
|
| 282 |
+
" outputs = model(images)\n",
|
| 283 |
+
" loss = criterion(outputs, targets)\n",
|
| 284 |
+
" loss.backward()\n",
|
| 285 |
+
" \n",
|
| 286 |
+
" # Gradient accumulation\n",
|
| 287 |
+
" if (i + 1) % grad_accumulation_steps == 0 or (i + 1) == len(tepoch):\n",
|
| 288 |
+
" optimizer.step()\n",
|
| 289 |
+
" optimizer.zero_grad()\n",
|
| 290 |
+
" \n",
|
| 291 |
+
" total_loss += loss.item()\n",
|
| 292 |
+
" \n",
|
| 293 |
+
" # Update the tqdm progress bar with the current loss\n",
|
| 294 |
+
" tepoch.set_postfix(loss=total_loss / ((i + 1) * batch_size))\n",
|
| 295 |
+
" \n",
|
| 296 |
+
" avg_train_loss = total_loss / len(train_dataloader)\n",
|
| 297 |
+
" avg_val_loss, avg_val_psnr = calculate_loss_and_psnr(model, val_dataloader, criterion)\n",
|
| 298 |
+
" \n",
|
| 299 |
+
" print(f\"Epoch [{epoch+1}/{epochs}] - Train Loss: {avg_train_loss:.4f}, Validation Loss: {avg_val_loss:.4f}, Validation PSNR: {avg_val_psnr:.4f}\")\n",
|
| 300 |
+
"\n",
|
| 301 |
+
" if avg_val_loss < best_val_loss:\n",
|
| 302 |
+
" best_val_loss = avg_val_loss\n",
|
| 303 |
+
" torch.save(model.state_dict(), best_model_path)\n",
|
| 304 |
+
" print(f\"Model saved with improved validation loss: {avg_val_loss:.4f}\")\n",
|
| 305 |
+
" \n",
|
| 306 |
+
" return model\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"# Example usage with train and validation directories\n",
|
| 309 |
+
"model = train_unet(r\"D:\\PN_Split\\train\", r\"D:\\PN_Split\\val\", epochs=50, batch_size=4, grad_accumulation_steps=8)"
|
| 310 |
+
]
|
| 311 |
+
},
|
| 312 |
+
{
|
| 313 |
+
"cell_type": "markdown",
|
| 314 |
+
"metadata": {},
|
| 315 |
+
"source": [
|
| 316 |
+
"### U-Net Inference"
|
| 317 |
+
]
|
| 318 |
+
},
|
| 319 |
+
{
|
| 320 |
+
"cell_type": "code",
|
| 321 |
+
"execution_count": null,
|
| 322 |
+
"metadata": {},
|
| 323 |
+
"outputs": [],
|
| 324 |
+
"source": [
|
| 325 |
+
"import torch\n",
|
| 326 |
+
"import torch.nn as nn\n",
|
| 327 |
+
"import pydicom\n",
|
| 328 |
+
"import numpy as np\n",
|
| 329 |
+
"import matplotlib.pyplot as plt\n",
|
| 330 |
+
"import os\n",
|
| 331 |
+
"\n",
|
| 332 |
+
"# Import the UNet and related classes from the previous script\n",
|
| 333 |
+
"# Replace with the actual import method\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"def load_dicom_image(dicom_path):\n",
|
| 336 |
+
" \"\"\"\n",
|
| 337 |
+
" Load and normalize a DICOM image\n",
|
| 338 |
+
" \n",
|
| 339 |
+
" Args:\n",
|
| 340 |
+
" dicom_path (str): Path to the DICOM file\n",
|
| 341 |
+
" \n",
|
| 342 |
+
" Returns:\n",
|
| 343 |
+
" torch.Tensor: Normalized image tensor\n",
|
| 344 |
+
" \"\"\"\n",
|
| 345 |
+
" # Read DICOM file\n",
|
| 346 |
+
" dcm = pydicom.dcmread(dicom_path)\n",
|
| 347 |
+
" image = dcm.pixel_array.astype(float)\n",
|
| 348 |
+
" \n",
|
| 349 |
+
" # Normalize image\n",
|
| 350 |
+
" image = (image - image.min()) / (image.max() - image.min())\n",
|
| 351 |
+
" \n",
|
| 352 |
+
" # Convert to tensor\n",
|
| 353 |
+
" image_tensor = torch.from_numpy(image).float().unsqueeze(0).unsqueeze(0)\n",
|
| 354 |
+
" return image_tensor\n",
|
| 355 |
+
"\n",
|
| 356 |
+
"def calculate_psnr(output, target, max_pixel=1.0):\n",
|
| 357 |
+
" \"\"\"\n",
|
| 358 |
+
" Calculate Peak Signal-to-Noise Ratio (PSNR)\n",
|
| 359 |
+
" \n",
|
| 360 |
+
" Args:\n",
|
| 361 |
+
" output (torch.Tensor): Reconstructed image\n",
|
| 362 |
+
" target (torch.Tensor): Original image\n",
|
| 363 |
+
" max_pixel (float): Maximum pixel value\n",
|
| 364 |
+
" \n",
|
| 365 |
+
" Returns:\n",
|
| 366 |
+
" float: PSNR value\n",
|
| 367 |
+
" \"\"\"\n",
|
| 368 |
+
" # Ensure the values are in the correct range\n",
|
| 369 |
+
" mse = torch.nn.functional.mse_loss(output, target)\n",
|
| 370 |
+
" psnr = 20 * torch.log10(max_pixel / torch.sqrt(mse))\n",
|
| 371 |
+
" return psnr.item()\n",
|
| 372 |
+
"\n",
|
| 373 |
+
"def visualize_reconstruction(original_image, reconstructed_image, psnr):\n",
|
| 374 |
+
" \"\"\"\n",
|
| 375 |
+
" Visualize original and reconstructed images\n",
|
| 376 |
+
" \n",
|
| 377 |
+
" Args:\n",
|
| 378 |
+
" original_image (torch.Tensor): Original image tensor\n",
|
| 379 |
+
" reconstructed_image (torch.Tensor): Reconstructed image tensor\n",
|
| 380 |
+
" psnr (float): Peak Signal-to-Noise Ratio\n",
|
| 381 |
+
" \"\"\"\n",
|
| 382 |
+
" # Convert tensors to numpy for visualization\n",
|
| 383 |
+
" original = original_image.squeeze().cpu().numpy()\n",
|
| 384 |
+
" reconstructed = reconstructed_image.squeeze().cpu().numpy()\n",
|
| 385 |
+
" \n",
|
| 386 |
+
" # Create subplot\n",
|
| 387 |
+
" fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))\n",
|
| 388 |
+
" \n",
|
| 389 |
+
" # Plot original image\n",
|
| 390 |
+
" im1 = ax1.imshow(original, cmap='gray')\n",
|
| 391 |
+
" ax1.set_title('Original Image')\n",
|
| 392 |
+
" plt.colorbar(im1, ax=ax1)\n",
|
| 393 |
+
" \n",
|
| 394 |
+
" # Plot reconstructed image\n",
|
| 395 |
+
" im2 = ax2.imshow(reconstructed, cmap='gray')\n",
|
| 396 |
+
" ax2.set_title(f'Reconstructed Image\\nPSNR: {psnr:.2f} dB')\n",
|
| 397 |
+
" plt.colorbar(im2, ax=ax2)\n",
|
| 398 |
+
" \n",
|
| 399 |
+
" plt.tight_layout()\n",
|
| 400 |
+
" plt.show()\n",
|
| 401 |
+
"\n",
|
| 402 |
+
"def inference_single_image(model_path, test_dicom_path):\n",
|
| 403 |
+
" \"\"\"\n",
|
| 404 |
+
" Perform inference on a single DICOM image\n",
|
| 405 |
+
" \n",
|
| 406 |
+
" Args:\n",
|
| 407 |
+
" model_path (str): Path to the saved model weights\n",
|
| 408 |
+
" test_dicom_path (str): Path to the test DICOM file\n",
|
| 409 |
+
" \"\"\"\n",
|
| 410 |
+
" # Set device\n",
|
| 411 |
+
" device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
|
| 412 |
+
" \n",
|
| 413 |
+
" # Initialize model\n",
|
| 414 |
+
" model = UNet().to(device)\n",
|
| 415 |
+
" \n",
|
| 416 |
+
" # Load saved model weights\n",
|
| 417 |
+
" model.load_state_dict(torch.load(model_path))\n",
|
| 418 |
+
" model.eval()\n",
|
| 419 |
+
" \n",
|
| 420 |
+
" # Load and preprocess test image\n",
|
| 421 |
+
" with torch.no_grad():\n",
|
| 422 |
+
" test_image = load_dicom_image(test_dicom_path).to(device)\n",
|
| 423 |
+
" \n",
|
| 424 |
+
" # Perform reconstruction\n",
|
| 425 |
+
" reconstructed_image = model(test_image)\n",
|
| 426 |
+
" \n",
|
| 427 |
+
" # Calculate PSNR\n",
|
| 428 |
+
" psnr = calculate_psnr(reconstructed_image, test_image)\n",
|
| 429 |
+
"\n",
|
| 430 |
+
" print(f\"PSNR: {psnr:.2f} dB\")\n",
|
| 431 |
+
" \n",
|
| 432 |
+
" # Visualize results\n",
|
| 433 |
+
" visualize_reconstruction(test_image, reconstructed_image, psnr)\n",
|
| 434 |
+
"\n",
|
| 435 |
+
"# Example usage\n",
|
| 436 |
+
"if __name__ == \"__main__\":\n",
|
| 437 |
+
" # Paths to model and test image\n",
|
| 438 |
+
" MODEL_PATH = r\"D:\\VSCODE\\PreSense\\best_model.pth\" # Path to your saved model\n",
|
| 439 |
+
" TEST_DICOM_PATH = r\"D:\\VSCODE\\PreSense\\test.dcm\" # Replace with actual path to test DICOM\n",
|
| 440 |
+
" \n",
|
| 441 |
+
" # Run inference\n",
|
| 442 |
+
" inference_single_image(MODEL_PATH, TEST_DICOM_PATH)"
|
| 443 |
+
]
|
| 444 |
+
},
|
| 445 |
+
{
|
| 446 |
+
"cell_type": "markdown",
|
| 447 |
+
"metadata": {},
|
| 448 |
+
"source": [
|
| 449 |
+
"### U-Net Inference for Complete Scan"
|
| 450 |
+
]
|
| 451 |
+
},
|
| 452 |
+
{
|
| 453 |
+
"cell_type": "code",
|
| 454 |
+
"execution_count": null,
|
| 455 |
+
"metadata": {},
|
| 456 |
+
"outputs": [],
|
| 457 |
+
"source": [
|
| 458 |
+
"import torch\n",
|
| 459 |
+
"import torch.nn as nn\n",
|
| 460 |
+
"import pydicom\n",
|
| 461 |
+
"import numpy as np\n",
|
| 462 |
+
"import os\n",
|
| 463 |
+
"from tqdm import tqdm\n",
|
| 464 |
+
"\n",
|
| 465 |
+
"# Import the UNet and related classes from the previous script\n",
|
| 466 |
+
"\n",
|
| 467 |
+
"def load_dicom_image(dicom_path):\n",
|
| 468 |
+
" \"\"\"\n",
|
| 469 |
+
" Load and normalize a DICOM image\n",
|
| 470 |
+
" \n",
|
| 471 |
+
" Args:\n",
|
| 472 |
+
" dicom_path (str): Path to the DICOM file\n",
|
| 473 |
+
" \n",
|
| 474 |
+
" Returns:\n",
|
| 475 |
+
" torch.Tensor: Normalized image tensor\n",
|
| 476 |
+
" \"\"\"\n",
|
| 477 |
+
" # Read DICOM file\n",
|
| 478 |
+
" dcm = pydicom.dcmread(dicom_path)\n",
|
| 479 |
+
" image = dcm.pixel_array.astype(float)\n",
|
| 480 |
+
" \n",
|
| 481 |
+
" # Normalize image\n",
|
| 482 |
+
" image = (image - image.min()) / (image.max() - image.min())\n",
|
| 483 |
+
" \n",
|
| 484 |
+
" # Convert to tensor\n",
|
| 485 |
+
" image_tensor = torch.from_numpy(image).float().unsqueeze(0).unsqueeze(0)\n",
|
| 486 |
+
" return image_tensor, dcm\n",
|
| 487 |
+
"\n",
|
| 488 |
+
"def save_reconstructed_dicom(image_tensor, original_dcm, output_path):\n",
|
| 489 |
+
" \"\"\"\n",
|
| 490 |
+
" Save reconstructed image as a DICOM file\n",
|
| 491 |
+
" \n",
|
| 492 |
+
" Args:\n",
|
| 493 |
+
" image_tensor (torch.Tensor): Reconstructed image tensor\n",
|
| 494 |
+
" original_dcm (pydicom.Dataset): Original DICOM dataset\n",
|
| 495 |
+
" output_path (str): Path to save the reconstructed image\n",
|
| 496 |
+
" \"\"\"\n",
|
| 497 |
+
" # Convert tensor to numpy and scale back to original pixel range\n",
|
| 498 |
+
" reconstructed_image = image_tensor.squeeze().cpu().numpy()\n",
|
| 499 |
+
" \n",
|
| 500 |
+
" # Scale to original pixel array range\n",
|
| 501 |
+
" min_val = original_dcm.pixel_array.min()\n",
|
| 502 |
+
" max_val = original_dcm.pixel_array.max()\n",
|
| 503 |
+
" reconstructed_image = reconstructed_image * (max_val - min_val) + min_val\n",
|
| 504 |
+
" \n",
|
| 505 |
+
" # Create a copy of the original DICOM dataset\n",
|
| 506 |
+
" ds = pydicom.Dataset()\n",
|
| 507 |
+
" ds.update(original_dcm)\n",
|
| 508 |
+
" \n",
|
| 509 |
+
" # Set the new pixel data\n",
|
| 510 |
+
" ds.PixelData = reconstructed_image.astype(original_dcm.pixel_array.dtype).tobytes()\n",
|
| 511 |
+
" \n",
|
| 512 |
+
" # Set transfer syntax to explicit VR little endian (common default)\n",
|
| 513 |
+
" ds.file_meta = pydicom.Dataset()\n",
|
| 514 |
+
" ds.file_meta.TransferSyntaxUID = pydicom.uid.ExplicitVRLittleEndian\n",
|
| 515 |
+
" \n",
|
| 516 |
+
" # Write the DICOM file\n",
|
| 517 |
+
" pydicom.dcmwrite(output_path, ds)\n",
|
| 518 |
+
"\n",
|
| 519 |
+
"def calculate_psnr(output, target, max_pixel=1.0):\n",
|
| 520 |
+
" \"\"\"\n",
|
| 521 |
+
" Calculate Peak Signal-to-Noise Ratio (PSNR)\n",
|
| 522 |
+
" \n",
|
| 523 |
+
" Args:\n",
|
| 524 |
+
" output (torch.Tensor): Reconstructed image\n",
|
| 525 |
+
" target (torch.Tensor): Original image\n",
|
| 526 |
+
" max_pixel (float): Maximum pixel value\n",
|
| 527 |
+
" \n",
|
| 528 |
+
" Returns:\n",
|
| 529 |
+
" float: PSNR value\n",
|
| 530 |
+
" \"\"\"\n",
|
| 531 |
+
" # Ensure the values are in the correct range\n",
|
| 532 |
+
" mse = torch.nn.functional.mse_loss(output, target)\n",
|
| 533 |
+
" psnr = 20 * torch.log10(max_pixel / torch.sqrt(mse))\n",
|
| 534 |
+
" return psnr.item()\n",
|
| 535 |
+
"\n",
|
| 536 |
+
"def batch_inference(model_path, input_dir, output_dir):\n",
|
| 537 |
+
" \"\"\"\n",
|
| 538 |
+
" Perform batch inference on all DICOM files in a directory\n",
|
| 539 |
+
" \n",
|
| 540 |
+
" Args:\n",
|
| 541 |
+
" model_path (str): Path to the saved model weights\n",
|
| 542 |
+
" input_dir (str): Directory containing input DICOM files\n",
|
| 543 |
+
" output_dir (str): Directory to save reconstructed DICOM files\n",
|
| 544 |
+
" \"\"\"\n",
|
| 545 |
+
" # Create output directory if it doesn't exist\n",
|
| 546 |
+
" os.makedirs(output_dir, exist_ok=True)\n",
|
| 547 |
+
" \n",
|
| 548 |
+
" # Set device\n",
|
| 549 |
+
" device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
|
| 550 |
+
" \n",
|
| 551 |
+
" # Initialize model\n",
|
| 552 |
+
" model = UNet().to(device)\n",
|
| 553 |
+
" \n",
|
| 554 |
+
" # Load saved model weights\n",
|
| 555 |
+
" model.load_state_dict(torch.load(model_path))\n",
|
| 556 |
+
" model.eval()\n",
|
| 557 |
+
" \n",
|
| 558 |
+
" # Get list of DICOM files\n",
|
| 559 |
+
" dcm_files = [f for f in os.listdir(input_dir) if f.endswith('.dcm')]\n",
|
| 560 |
+
" \n",
|
| 561 |
+
" # Prepare for inference\n",
|
| 562 |
+
" print(f\"Starting batch inference on {len(dcm_files)} DICOM files...\")\n",
|
| 563 |
+
" \n",
|
| 564 |
+
" # Store PSNR values\n",
|
| 565 |
+
" psnr_values = {}\n",
|
| 566 |
+
" \n",
|
| 567 |
+
" # Perform inference\n",
|
| 568 |
+
" with torch.no_grad():\n",
|
| 569 |
+
" for dcm_file in tqdm(dcm_files, desc=\"Reconstructing Images\"):\n",
|
| 570 |
+
" # Full paths\n",
|
| 571 |
+
" input_path = os.path.join(input_dir, dcm_file)\n",
|
| 572 |
+
" output_path = os.path.join(output_dir, dcm_file)\n",
|
| 573 |
+
" \n",
|
| 574 |
+
" # Load image\n",
|
| 575 |
+
" test_image, original_dcm = load_dicom_image(input_path)\n",
|
| 576 |
+
" test_image = test_image.to(device)\n",
|
| 577 |
+
" \n",
|
| 578 |
+
" # Perform reconstruction\n",
|
| 579 |
+
" reconstructed_image = model(test_image)\n",
|
| 580 |
+
" \n",
|
| 581 |
+
" # Calculate PSNR\n",
|
| 582 |
+
" psnr = calculate_psnr(reconstructed_image, test_image)\n",
|
| 583 |
+
" psnr_values[dcm_file] = psnr\n",
|
| 584 |
+
" \n",
|
| 585 |
+
" # Save reconstructed image\n",
|
| 586 |
+
" save_reconstructed_dicom(reconstructed_image, original_dcm, output_path)\n",
|
| 587 |
+
" \n",
|
| 588 |
+
" # Print PSNR values\n",
|
| 589 |
+
" print(\"\\nPSNR Values:\")\n",
|
| 590 |
+
" for filename, psnr in psnr_values.items():\n",
|
| 591 |
+
" print(f\"{filename}: {psnr:.2f} dB\")\n",
|
| 592 |
+
" \n",
|
| 593 |
+
" # Calculate and print overall statistics\n",
|
| 594 |
+
" psnr_list = list(psnr_values.values())\n",
|
| 595 |
+
" print(f\"\\nPSNR Statistics:\")\n",
|
| 596 |
+
" print(f\"Average PSNR: {np.mean(psnr_list):.2f} dB\")\n",
|
| 597 |
+
" print(f\"Minimum PSNR: {np.min(psnr_list):.2f} dB\")\n",
|
| 598 |
+
" print(f\"Maximum PSNR: {np.max(psnr_list):.2f} dB\")\n",
|
| 599 |
+
"\n",
|
| 600 |
+
"# Example usage\n",
|
| 601 |
+
"if __name__ == \"__main__\":\n",
|
| 602 |
+
" # Paths to model, input, and output directories\n",
|
| 603 |
+
" MODEL_PATH = r\"D:\\VSCODE\\PreSense\\best_model.pth\" # Path to your saved model\n",
|
| 604 |
+
" INPUT_DICOM_DIR = r\"D:\\Pancreatic Neuroendocrine\\manifest-1662644254281\\CTpred-Sunitinib-panNET\\PAN_01\\04-11-2001-NA-NA-29221\\3.000000-CEFC07AIDR 3D STD-16260\" # Directory with input DICOM files\n",
|
| 605 |
+
" OUTPUT_DICOM_DIR = r\"D:\\VSCODE\\PreSense\\reconstructed_dicom\" # Directory to save reconstructed DICOM files\n",
|
| 606 |
+
" \n",
|
| 607 |
+
" # Run batch inference\n",
|
| 608 |
+
" batch_inference(MODEL_PATH, INPUT_DICOM_DIR, OUTPUT_DICOM_DIR)"
|
| 609 |
+
]
|
| 610 |
+
},
|
| 611 |
+
{
|
| 612 |
+
"cell_type": "code",
|
| 613 |
+
"execution_count": null,
|
| 614 |
+
"metadata": {},
|
| 615 |
+
"outputs": [],
|
| 616 |
+
"source": [
|
| 617 |
+
"import torch\n",
|
| 618 |
+
"import torch.nn as nn\n",
|
| 619 |
+
"import pydicom\n",
|
| 620 |
+
"import numpy as np\n",
|
| 621 |
+
"import os\n",
|
| 622 |
+
"from tqdm import tqdm\n",
|
| 623 |
+
"from PIL import Image\n",
|
| 624 |
+
"\n",
|
| 625 |
+
"# Import the UNet and related classes from the previous script\n",
|
| 626 |
+
"\n",
|
| 627 |
+
"def load_dicom_image(dicom_path):\n",
|
| 628 |
+
" \"\"\"\n",
|
| 629 |
+
" Load and normalize a DICOM image\n",
|
| 630 |
+
" \n",
|
| 631 |
+
" Args:\n",
|
| 632 |
+
" dicom_path (str): Path to the DICOM file\n",
|
| 633 |
+
" \n",
|
| 634 |
+
" Returns:\n",
|
| 635 |
+
" torch.Tensor: Normalized image tensor\n",
|
| 636 |
+
" \"\"\"\n",
|
| 637 |
+
" # Read DICOM file\n",
|
| 638 |
+
" dcm = pydicom.dcmread(dicom_path)\n",
|
| 639 |
+
" image = dcm.pixel_array.astype(float)\n",
|
| 640 |
+
" \n",
|
| 641 |
+
" # Normalize image\n",
|
| 642 |
+
" image = (image - image.min()) / (image.max() - image.min())\n",
|
| 643 |
+
" \n",
|
| 644 |
+
" # Convert to tensor\n",
|
| 645 |
+
" image_tensor = torch.from_numpy(image).float().unsqueeze(0).unsqueeze(0)\n",
|
| 646 |
+
" return image_tensor, dcm\n",
|
| 647 |
+
"\n",
|
| 648 |
+
"def save_reconstructed_image(image_tensor, output_path):\n",
|
| 649 |
+
" \"\"\"\n",
|
| 650 |
+
" Save reconstructed image as a JPEG file\n",
|
| 651 |
+
" \n",
|
| 652 |
+
" Args:\n",
|
| 653 |
+
" image_tensor (torch.Tensor): Reconstructed image tensor\n",
|
| 654 |
+
" output_path (str): Path to save the reconstructed JPEG image\n",
|
| 655 |
+
" \"\"\"\n",
|
| 656 |
+
" # Convert tensor to numpy array\n",
|
| 657 |
+
" reconstructed_image = image_tensor.squeeze().cpu().numpy()\n",
|
| 658 |
+
" \n",
|
| 659 |
+
" # Scale back to the original pixel range (assuming input was normalized to [0, 1])\n",
|
| 660 |
+
" reconstructed_image = np.uint8(reconstructed_image * 255)\n",
|
| 661 |
+
" \n",
|
| 662 |
+
" # Convert to PIL Image\n",
|
| 663 |
+
" pil_image = Image.fromarray(reconstructed_image)\n",
|
| 664 |
+
" \n",
|
| 665 |
+
" # Save as JPEG\n",
|
| 666 |
+
" pil_image.save(output_path, 'JPEG')\n",
|
| 667 |
+
"\n",
|
| 668 |
+
"def calculate_psnr(output, target, max_pixel=1.0):\n",
|
| 669 |
+
" \"\"\"\n",
|
| 670 |
+
" Calculate Peak Signal-to-Noise Ratio (PSNR)\n",
|
| 671 |
+
" \n",
|
| 672 |
+
" Args:\n",
|
| 673 |
+
" output (torch.Tensor): Reconstructed image\n",
|
| 674 |
+
" target (torch.Tensor): Original image\n",
|
| 675 |
+
" max_pixel (float): Maximum pixel value\n",
|
| 676 |
+
" \n",
|
| 677 |
+
" Returns:\n",
|
| 678 |
+
" float: PSNR value\n",
|
| 679 |
+
" \"\"\"\n",
|
| 680 |
+
" # Ensure the values are in the correct range\n",
|
| 681 |
+
" mse = torch.nn.functional.mse_loss(output, target)\n",
|
| 682 |
+
" psnr = 20 * torch.log10(max_pixel / torch.sqrt(mse))\n",
|
| 683 |
+
" return psnr.item()\n",
|
| 684 |
+
"\n",
|
| 685 |
+
"def batch_inference(model_path, input_dir, output_dir):\n",
|
| 686 |
+
" \"\"\"\n",
|
| 687 |
+
" Perform batch inference on all DICOM files in a directory\n",
|
| 688 |
+
" \n",
|
| 689 |
+
" Args:\n",
|
| 690 |
+
" model_path (str): Path to the saved model weights\n",
|
| 691 |
+
" input_dir (str): Directory containing input DICOM files\n",
|
| 692 |
+
" output_dir (str): Directory to save reconstructed JPEG images\n",
|
| 693 |
+
" \"\"\"\n",
|
| 694 |
+
" # Create output directory if it doesn't exist\n",
|
| 695 |
+
" os.makedirs(output_dir, exist_ok=True)\n",
|
| 696 |
+
" \n",
|
| 697 |
+
" # Set device\n",
|
| 698 |
+
" device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
|
| 699 |
+
" \n",
|
| 700 |
+
" # Initialize model\n",
|
| 701 |
+
" model = UNet().to(device)\n",
|
| 702 |
+
" \n",
|
| 703 |
+
" # Load saved model weights\n",
|
| 704 |
+
" model.load_state_dict(torch.load(model_path))\n",
|
| 705 |
+
" model.eval()\n",
|
| 706 |
+
" \n",
|
| 707 |
+
" # Get list of DICOM files\n",
|
| 708 |
+
" dcm_files = [f for f in os.listdir(input_dir) if f.endswith('.dcm')]\n",
|
| 709 |
+
" \n",
|
| 710 |
+
" # Prepare for inference\n",
|
| 711 |
+
" print(f\"Starting batch inference on {len(dcm_files)} DICOM files...\")\n",
|
| 712 |
+
" \n",
|
| 713 |
+
" # Store PSNR values\n",
|
| 714 |
+
" psnr_values = {}\n",
|
| 715 |
+
" \n",
|
| 716 |
+
" # Perform inference\n",
|
| 717 |
+
" with torch.no_grad():\n",
|
| 718 |
+
" for dcm_file in tqdm(dcm_files, desc=\"Reconstructing Images\"):\n",
|
| 719 |
+
" # Full paths\n",
|
| 720 |
+
" input_path = os.path.join(input_dir, dcm_file)\n",
|
| 721 |
+
" output_path = os.path.join(output_dir, f\"{os.path.splitext(dcm_file)[0]}.jpg\") # Save as .jpg\n",
|
| 722 |
+
" \n",
|
| 723 |
+
" # Load image\n",
|
| 724 |
+
" test_image, original_dcm = load_dicom_image(input_path)\n",
|
| 725 |
+
" test_image = test_image.to(device)\n",
|
| 726 |
+
" \n",
|
| 727 |
+
" # Perform reconstruction\n",
|
| 728 |
+
" reconstructed_image = model(test_image)\n",
|
| 729 |
+
" \n",
|
| 730 |
+
" # Calculate PSNR\n",
|
| 731 |
+
" psnr = calculate_psnr(reconstructed_image, test_image)\n",
|
| 732 |
+
" psnr_values[dcm_file] = psnr\n",
|
| 733 |
+
" \n",
|
| 734 |
+
" # Save reconstructed image as JPEG\n",
|
| 735 |
+
" save_reconstructed_image(reconstructed_image, output_path)\n",
|
| 736 |
+
" \n",
|
| 737 |
+
" # Print PSNR values\n",
|
| 738 |
+
" print(\"\\nPSNR Values:\")\n",
|
| 739 |
+
" for filename, psnr in psnr_values.items():\n",
|
| 740 |
+
" print(f\"{filename}: {psnr:.2f} dB\")\n",
|
| 741 |
+
" \n",
|
| 742 |
+
" # Calculate and print overall statistics\n",
|
| 743 |
+
" psnr_list = list(psnr_values.values())\n",
|
| 744 |
+
" print(f\"\\nPSNR Statistics:\")\n",
|
| 745 |
+
" print(f\"Average PSNR: {np.mean(psnr_list):.2f} dB\")\n",
|
| 746 |
+
" print(f\"Minimum PSNR: {np.min(psnr_list):.2f} dB\")\n",
|
| 747 |
+
" print(f\"Maximum PSNR: {np.max(psnr_list):.2f} dB\")\n",
|
| 748 |
+
"\n",
|
| 749 |
+
"# Example usage\n",
|
| 750 |
+
"if __name__ == \"__main__\":\n",
|
| 751 |
+
" # Paths to model, input, and output directories\n",
|
| 752 |
+
" MODEL_PATH = r\"D:\\VSCODE\\PreSense\\best_model.pth\" # Path to your saved model\n",
|
| 753 |
+
" INPUT_DICOM_DIR = r\"D:\\Pancreatic Neuroendocrine\\manifest-1662644254281\\CTpred-Sunitinib-panNET\\PAN_01\\04-11-2001-NA-NA-29221\\3.000000-CEFC07AIDR 3D STD-16260\" # Directory with input DICOM files\n",
|
| 754 |
+
" OUTPUT_JPEG_DIR = r\"D:\\VSCODE\\PreSense\\reconstructed_images\" # Directory to save reconstructed JPEG images\n",
|
| 755 |
+
" \n",
|
| 756 |
+
" # Run batch inference\n",
|
| 757 |
+
" batch_inference(MODEL_PATH, INPUT_DICOM_DIR, OUTPUT_JPEG_DIR)"
|
| 758 |
+
]
|
| 759 |
+
},
|
| 760 |
+
{
|
| 761 |
+
"cell_type": "markdown",
|
| 762 |
+
"metadata": {},
|
| 763 |
+
"source": [
|
| 764 |
+
"### Small Reconstructor and Denoiser U-Net (smallRD)"
|
| 765 |
+
]
|
| 766 |
+
},
|
| 767 |
+
{
|
| 768 |
+
"cell_type": "code",
|
| 769 |
+
"execution_count": null,
|
| 770 |
+
"metadata": {},
|
| 771 |
+
"outputs": [],
|
| 772 |
+
"source": [
|
| 773 |
+
"import torch\n",
|
| 774 |
+
"import torch.nn as nn\n",
|
| 775 |
+
"import torch.nn.functional as F\n",
|
| 776 |
+
"import pydicom\n",
|
| 777 |
+
"import numpy as np\n",
|
| 778 |
+
"from torch.utils.data import Dataset, DataLoader\n",
|
| 779 |
+
"import os\n",
|
| 780 |
+
"from torch.utils.checkpoint import checkpoint\n",
|
| 781 |
+
"from tqdm import tqdm # Import tqdm for progress bar\n",
|
| 782 |
+
"\n",
|
| 783 |
+
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
|
| 784 |
+
"\n",
|
| 785 |
+
"class MedicalImageDataset(Dataset):\n",
|
| 786 |
+
" def __init__(self, dicom_dir):\n",
|
| 787 |
+
" self.dicom_files = [os.path.join(dicom_dir, f) for f in os.listdir(dicom_dir) if f.endswith('.dcm')]\n",
|
| 788 |
+
" \n",
|
| 789 |
+
" def __len__(self):\n",
|
| 790 |
+
" return len(self.dicom_files)\n",
|
| 791 |
+
" \n",
|
| 792 |
+
" def __getitem__(self, idx):\n",
|
| 793 |
+
" # Read DICOM file and normalize\n",
|
| 794 |
+
" dcm = pydicom.dcmread(self.dicom_files[idx])\n",
|
| 795 |
+
" image = dcm.pixel_array.astype(float)\n",
|
| 796 |
+
" image = (image - image.min()) / (image.max() - image.min())\n",
|
| 797 |
+
" \n",
|
| 798 |
+
" # Convert to tensor\n",
|
| 799 |
+
" image_tensor = torch.from_numpy(image).float().unsqueeze(0)\n",
|
| 800 |
+
" return image_tensor, image_tensor\n",
|
| 801 |
+
"\n",
|
| 802 |
+
"class UNetBlock(nn.Module):\n",
|
| 803 |
+
" def __init__(self, in_channels, out_channels):\n",
|
| 804 |
+
" super().__init__()\n",
|
| 805 |
+
" self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1)\n",
|
| 806 |
+
" self.bn1 = nn.BatchNorm2d(out_channels)\n",
|
| 807 |
+
" self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1)\n",
|
| 808 |
+
" self.bn2 = nn.BatchNorm2d(out_channels)\n",
|
| 809 |
+
" \n",
|
| 810 |
+
" def forward(self, x):\n",
|
| 811 |
+
" x = F.relu(self.bn1(self.conv1(x)))\n",
|
| 812 |
+
" x = F.relu(self.bn2(self.conv2(x)))\n",
|
| 813 |
+
" return x\n",
|
| 814 |
+
"\n",
|
| 815 |
+
"class UNet(nn.Module):\n",
|
| 816 |
+
" def __init__(self, in_channels=1, out_channels=1):\n",
|
| 817 |
+
" super().__init__()\n",
|
| 818 |
+
" # Encoder\n",
|
| 819 |
+
" self.enc1 = UNetBlock(in_channels, 64)\n",
|
| 820 |
+
" self.enc2 = UNetBlock(64, 128)\n",
|
| 821 |
+
" self.enc3 = UNetBlock(128, 256)\n",
|
| 822 |
+
" \n",
|
| 823 |
+
" # Decoder\n",
|
| 824 |
+
" self.dec3 = UNetBlock(256 + 128, 128) # Adjust for concatenation with skip connection\n",
|
| 825 |
+
" self.dec2 = UNetBlock(128 + 64, 64) # Adjust for concatenation with skip connection\n",
|
| 826 |
+
" self.dec1 = UNetBlock(64, out_channels)\n",
|
| 827 |
+
" \n",
|
| 828 |
+
" # Pooling and upsampling\n",
|
| 829 |
+
" self.pool = nn.MaxPool2d(2, 2)\n",
|
| 830 |
+
" self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n",
|
| 831 |
+
" \n",
|
| 832 |
+
" def forward(self, x):\n",
|
| 833 |
+
" # Encoder path\n",
|
| 834 |
+
" e1 = checkpoint(self.enc1, x)\n",
|
| 835 |
+
" e2 = checkpoint(self.enc2, self.pool(e1))\n",
|
| 836 |
+
" e3 = checkpoint(self.enc3, self.pool(e2))\n",
|
| 837 |
+
" \n",
|
| 838 |
+
" # Decoder path with skip connections\n",
|
| 839 |
+
" d3 = self.upsample(e3)\n",
|
| 840 |
+
" d3 = torch.cat([d3, e2], dim=1) # Concatenate along channels\n",
|
| 841 |
+
" d3 = checkpoint(self.dec3, d3)\n",
|
| 842 |
+
" \n",
|
| 843 |
+
" d2 = self.upsample(d3)\n",
|
| 844 |
+
" d2 = torch.cat([d2, e1], dim=1) # Concatenate along channels\n",
|
| 845 |
+
" d2 = checkpoint(self.dec2, d2)\n",
|
| 846 |
+
" \n",
|
| 847 |
+
" d1 = self.dec1(d2) # No checkpointing for final output layer\n",
|
| 848 |
+
" \n",
|
| 849 |
+
" return d1\n",
|
| 850 |
+
"\n",
|
| 851 |
+
"def calculate_loss(model, dataloader, criterion):\n",
|
| 852 |
+
" model.eval()\n",
|
| 853 |
+
" total_loss = 0\n",
|
| 854 |
+
" with torch.no_grad():\n",
|
| 855 |
+
" for images, targets in dataloader:\n",
|
| 856 |
+
" images, targets = images.to(device), targets.to(device)\n",
|
| 857 |
+
" outputs = model(images)\n",
|
| 858 |
+
" loss = criterion(outputs, targets)\n",
|
| 859 |
+
" total_loss += loss.item()\n",
|
| 860 |
+
" return total_loss / len(dataloader)\n",
|
| 861 |
+
"\n",
|
| 862 |
+
"def calculate_psnr(output, target, max_pixel=1.0):\n",
|
| 863 |
+
" # Ensure the values are in the correct range\n",
|
| 864 |
+
" mse = F.mse_loss(output, target)\n",
|
| 865 |
+
" psnr = 20 * torch.log10(max_pixel / torch.sqrt(mse))\n",
|
| 866 |
+
" return psnr.item()\n",
|
| 867 |
+
"\n",
|
| 868 |
+
"def calculate_loss_and_psnr(model, dataloader, criterion):\n",
|
| 869 |
+
" model.eval()\n",
|
| 870 |
+
" total_loss = 0\n",
|
| 871 |
+
" total_psnr = 0\n",
|
| 872 |
+
" num_batches = len(dataloader)\n",
|
| 873 |
+
" \n",
|
| 874 |
+
" with torch.no_grad():\n",
|
| 875 |
+
" for images, targets in dataloader:\n",
|
| 876 |
+
" images, targets = images.to(device), targets.to(device)\n",
|
| 877 |
+
" outputs = model(images)\n",
|
| 878 |
+
" \n",
|
| 879 |
+
" # Calculate MSE loss\n",
|
| 880 |
+
" loss = criterion(outputs, targets)\n",
|
| 881 |
+
" total_loss += loss.item()\n",
|
| 882 |
+
" \n",
|
| 883 |
+
" # Calculate PSNR\n",
|
| 884 |
+
" psnr = calculate_psnr(outputs, targets)\n",
|
| 885 |
+
" total_psnr += psnr\n",
|
| 886 |
+
" \n",
|
| 887 |
+
" avg_loss = total_loss / num_batches\n",
|
| 888 |
+
" avg_psnr = total_psnr / num_batches\n",
|
| 889 |
+
" \n",
|
| 890 |
+
" return avg_loss, avg_psnr\n",
|
| 891 |
+
"\n",
|
| 892 |
+
"class UNet(nn.Module):\n",
|
| 893 |
+
" def __init__(self, in_channels=1, out_channels=1):\n",
|
| 894 |
+
" super().__init__()\n",
|
| 895 |
+
" # Encoder\n",
|
| 896 |
+
" self.enc1 = UNetBlock(in_channels, 64)\n",
|
| 897 |
+
" self.enc2 = UNetBlock(64, 128)\n",
|
| 898 |
+
" self.enc3 = UNetBlock(128, 256)\n",
|
| 899 |
+
" \n",
|
| 900 |
+
" # Decoder\n",
|
| 901 |
+
" self.dec3 = UNetBlock(256 + 128, 128) # Adjust for concatenation with skip connection\n",
|
| 902 |
+
" self.dec2 = UNetBlock(128 + 64, 64) # Adjust for concatenation with skip connection\n",
|
| 903 |
+
" self.dec1 = UNetBlock(64, out_channels)\n",
|
| 904 |
+
" \n",
|
| 905 |
+
" # Pooling and upsampling\n",
|
| 906 |
+
" self.pool = nn.MaxPool2d(2, 2)\n",
|
| 907 |
+
" self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n",
|
| 908 |
+
" \n",
|
| 909 |
+
" def forward(self, x):\n",
|
| 910 |
+
" # Encoder path\n",
|
| 911 |
+
" e1 = checkpoint(self.enc1, x)\n",
|
| 912 |
+
" e2 = checkpoint(self.enc2, self.pool(e1))\n",
|
| 913 |
+
" e3 = checkpoint(self.enc3, self.pool(e2))\n",
|
| 914 |
+
" \n",
|
| 915 |
+
" # Decoder path with skip connections\n",
|
| 916 |
+
" d3 = self.upsample(e3)\n",
|
| 917 |
+
" d3 = torch.cat([d3, e2], dim=1) # Concatenate along channels\n",
|
| 918 |
+
" d3 = checkpoint(self.dec3, d3)\n",
|
| 919 |
+
" \n",
|
| 920 |
+
" d2 = self.upsample(d3)\n",
|
| 921 |
+
" d2 = torch.cat([d2, e1], dim=1) # Concatenate along channels\n",
|
| 922 |
+
" d2 = checkpoint(self.dec2, d2)\n",
|
| 923 |
+
" \n",
|
| 924 |
+
" d1 = self.dec1(d2) # No checkpointing for final output layer\n",
|
| 925 |
+
" \n",
|
| 926 |
+
" return d1\n",
|
| 927 |
+
"\n",
|
| 928 |
+
"class Reconstructor(nn.Module):\n",
|
| 929 |
+
" def __init__(self, in_channels=1, out_channels=1):\n",
|
| 930 |
+
" super().__init__()\n",
|
| 931 |
+
" # Same UNet architecture for reconstruction\n",
|
| 932 |
+
" self.unet = UNet(in_channels=in_channels, out_channels=out_channels)\n",
|
| 933 |
+
" \n",
|
| 934 |
+
" def forward(self, x):\n",
|
| 935 |
+
" return self.unet(x)\n",
|
| 936 |
+
"\n",
|
| 937 |
+
"\n",
|
| 938 |
+
"class Denoiser(nn.Module):\n",
|
| 939 |
+
" def __init__(self, in_channels=1, out_channels=1):\n",
|
| 940 |
+
" super().__init__()\n",
|
| 941 |
+
" # Same UNet architecture for denoising\n",
|
| 942 |
+
" self.unet = UNet(in_channels=in_channels, out_channels=out_channels)\n",
|
| 943 |
+
" \n",
|
| 944 |
+
" def forward(self, x):\n",
|
| 945 |
+
" return self.unet(x)\n",
|
| 946 |
+
" \n",
|
| 947 |
+
"def train_reconstructor_and_denoiser(dicom_dir, val_dicom_dir, epochs=50, batch_size=4, grad_accumulation_steps=2):\n",
|
| 948 |
+
" # Dataset and DataLoader\n",
|
| 949 |
+
" dataset = MedicalImageDataset(dicom_dir)\n",
|
| 950 |
+
" train_dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)\n",
|
| 951 |
+
" val_dataset = MedicalImageDataset(val_dicom_dir)\n",
|
| 952 |
+
" val_dataloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)\n",
|
| 953 |
+
" \n",
|
| 954 |
+
" # Initialize both models\n",
|
| 955 |
+
" reconstructor = Reconstructor().to(device)\n",
|
| 956 |
+
" denoiser = Denoiser().to(device)\n",
|
| 957 |
+
" \n",
|
| 958 |
+
" # Loss functions for both models\n",
|
| 959 |
+
" reconstructor_criterion = nn.MSELoss()\n",
|
| 960 |
+
" denoiser_criterion = nn.MSELoss()\n",
|
| 961 |
+
" \n",
|
| 962 |
+
" # Optimizers for both models\n",
|
| 963 |
+
" reconstructor_optimizer = torch.optim.Adam(reconstructor.parameters(), lr=0.0001)\n",
|
| 964 |
+
" denoiser_optimizer = torch.optim.Adam(denoiser.parameters(), lr=0.0001)\n",
|
| 965 |
+
" \n",
|
| 966 |
+
" # Best validation loss initialization\n",
|
| 967 |
+
" best_reconstructor_val_loss = float('inf')\n",
|
| 968 |
+
" best_denoiser_val_loss = float('inf')\n",
|
| 969 |
+
" best_reconstructor_model_path = 'best_reconstructor_model.pth'\n",
|
| 970 |
+
" best_denoiser_model_path = 'best_denoiser_model.pth'\n",
|
| 971 |
+
"\n",
|
| 972 |
+
" # Training loop with tqdm\n",
|
| 973 |
+
" for epoch in range(epochs):\n",
|
| 974 |
+
" reconstructor.train()\n",
|
| 975 |
+
" denoiser.train()\n",
|
| 976 |
+
" \n",
|
| 977 |
+
" reconstructor_total_loss = 0\n",
|
| 978 |
+
" denoiser_total_loss = 0\n",
|
| 979 |
+
" \n",
|
| 980 |
+
" reconstructor_optimizer.zero_grad()\n",
|
| 981 |
+
" denoiser_optimizer.zero_grad()\n",
|
| 982 |
+
"\n",
|
| 983 |
+
" with tqdm(train_dataloader, unit=\"batch\", desc=f\"Epoch {epoch+1}/{epochs}\") as tepoch:\n",
|
| 984 |
+
" for i, (images, targets) in enumerate(tepoch):\n",
|
| 985 |
+
" images, targets = images.to(device), targets.to(device)\n",
|
| 986 |
+
" \n",
|
| 987 |
+
" # Training Reconstructor\n",
|
| 988 |
+
" reconstructor_outputs = reconstructor(images)\n",
|
| 989 |
+
" reconstructor_loss = reconstructor_criterion(reconstructor_outputs, targets)\n",
|
| 990 |
+
" reconstructor_loss.backward(retain_graph=True)\n",
|
| 991 |
+
"\n",
|
| 992 |
+
" # Gradient accumulation for reconstructor\n",
|
| 993 |
+
" if (i + 1) % grad_accumulation_steps == 0 or (i + 1) == len(tepoch):\n",
|
| 994 |
+
" reconstructor_optimizer.step()\n",
|
| 995 |
+
" reconstructor_optimizer.zero_grad()\n",
|
| 996 |
+
"\n",
|
| 997 |
+
" reconstructor_total_loss += reconstructor_loss.item()\n",
|
| 998 |
+
"\n",
|
| 999 |
+
" # Training Denoiser (using output from Reconstructor as noisy input)\n",
|
| 1000 |
+
" noisy_images = reconstructor_outputs.detach() # Detach from the computation graph to avoid in-place error\n",
|
| 1001 |
+
" denoiser_outputs = denoiser(noisy_images)\n",
|
| 1002 |
+
" denoiser_loss = denoiser_criterion(denoiser_outputs, targets)\n",
|
| 1003 |
+
" denoiser_loss.backward()\n",
|
| 1004 |
+
"\n",
|
| 1005 |
+
" # Gradient accumulation for denoiser\n",
|
| 1006 |
+
" if (i + 1) % grad_accumulation_steps == 0 or (i + 1) == len(tepoch):\n",
|
| 1007 |
+
" denoiser_optimizer.step()\n",
|
| 1008 |
+
" denoiser_optimizer.zero_grad()\n",
|
| 1009 |
+
"\n",
|
| 1010 |
+
" denoiser_total_loss += denoiser_loss.item()\n",
|
| 1011 |
+
"\n",
|
| 1012 |
+
" # Update the tqdm progress bar with current loss\n",
|
| 1013 |
+
" tepoch.set_postfix(\n",
|
| 1014 |
+
" reconstructor_loss=reconstructor_total_loss / ((i + 1) * batch_size),\n",
|
| 1015 |
+
" denoiser_loss=denoiser_total_loss / ((i + 1) * batch_size)\n",
|
| 1016 |
+
" )\n",
|
| 1017 |
+
" \n",
|
| 1018 |
+
" # Calculate validation loss for both models\n",
|
| 1019 |
+
" avg_reconstructor_train_loss = reconstructor_total_loss / len(train_dataloader)\n",
|
| 1020 |
+
" avg_denoiser_train_loss = denoiser_total_loss / len(train_dataloader)\n",
|
| 1021 |
+
" \n",
|
| 1022 |
+
" avg_reconstructor_val_loss, avg_reconstructor_val_psnr = calculate_loss_and_psnr(reconstructor, val_dataloader, reconstructor_criterion)\n",
|
| 1023 |
+
" avg_denoiser_val_loss, avg_denoiser_val_psnr = calculate_loss_and_psnr(denoiser, val_dataloader, denoiser_criterion)\n",
|
| 1024 |
+
" \n",
|
| 1025 |
+
" print(f\"Epoch [{epoch+1}/{epochs}] - \"\n",
|
| 1026 |
+
" f\"Reconstructor Train Loss: {avg_reconstructor_train_loss:.4f}, \"\n",
|
| 1027 |
+
" f\"Denoiser Train Loss: {avg_denoiser_train_loss:.4f}, \"\n",
|
| 1028 |
+
" f\"Reconstructor Val Loss: {avg_reconstructor_val_loss:.4f}, \"\n",
|
| 1029 |
+
" f\"Denoiser Val Loss: {avg_denoiser_val_loss:.4f}, \"\n",
|
| 1030 |
+
" f\"Reconstructor Validation PSNR: {avg_reconstructor_val_psnr:.4f}, \"\n",
|
| 1031 |
+
" f\"Denoiser Validation PSNR: {avg_denoiser_val_psnr:.4f}\")\n",
|
| 1032 |
+
" \n",
|
| 1033 |
+
" # Save models if validation loss is improved\n",
|
| 1034 |
+
" if avg_reconstructor_val_loss < best_reconstructor_val_loss:\n",
|
| 1035 |
+
" best_reconstructor_val_loss = avg_reconstructor_val_loss\n",
|
| 1036 |
+
" torch.save(reconstructor.state_dict(), best_reconstructor_model_path)\n",
|
| 1037 |
+
" print(f\"Reconstructor model saved with improved validation loss: {avg_reconstructor_val_loss:.4f}\")\n",
|
| 1038 |
+
" \n",
|
| 1039 |
+
" if avg_denoiser_val_loss < best_denoiser_val_loss:\n",
|
| 1040 |
+
" best_denoiser_val_loss = avg_denoiser_val_loss\n",
|
| 1041 |
+
" torch.save(denoiser.state_dict(), best_denoiser_model_path)\n",
|
| 1042 |
+
" print(f\"Denoiser model saved with improved validation loss: {avg_denoiser_val_loss:.4f}\")\n",
|
| 1043 |
+
" \n",
|
| 1044 |
+
" return reconstructor, denoiser\n",
|
| 1045 |
+
"\n",
|
| 1046 |
+
"# Example usage with train and validation directories\n",
|
| 1047 |
+
"reconstructor_model, denoiser_model = train_reconstructor_and_denoiser(\n",
|
| 1048 |
+
" r\"D:/PN_Split/train\", r\"D:/PN_Split/val\", epochs=50, batch_size=20, grad_accumulation_steps=2\n",
|
| 1049 |
+
")"
|
| 1050 |
+
]
|
| 1051 |
+
},
|
| 1052 |
+
{
|
| 1053 |
+
"cell_type": "markdown",
|
| 1054 |
+
"metadata": {},
|
| 1055 |
+
"source": [
|
| 1056 |
+
"### smallRD Single Image Inference"
|
| 1057 |
+
]
|
| 1058 |
+
},
|
| 1059 |
+
{
|
| 1060 |
+
"cell_type": "code",
|
| 1061 |
+
"execution_count": null,
|
| 1062 |
+
"metadata": {},
|
| 1063 |
+
"outputs": [],
|
| 1064 |
+
"source": [
|
| 1065 |
+
"import torch\n",
|
| 1066 |
+
"import pydicom\n",
|
| 1067 |
+
"import numpy as np\n",
|
| 1068 |
+
"import matplotlib.pyplot as plt\n",
|
| 1069 |
+
"import os\n",
|
| 1070 |
+
"\n",
|
| 1071 |
+
"# Import the models from the previous script\n",
|
| 1072 |
+
"# Assuming they are defined or imported correctly\n",
|
| 1073 |
+
"\n",
|
| 1074 |
+
"def load_dicom_image(dicom_path):\n",
|
| 1075 |
+
" \"\"\"\n",
|
| 1076 |
+
" Load and normalize a DICOM image\n",
|
| 1077 |
+
" \n",
|
| 1078 |
+
" Args:\n",
|
| 1079 |
+
" dicom_path (str): Path to the DICOM file\n",
|
| 1080 |
+
" \n",
|
| 1081 |
+
" Returns:\n",
|
| 1082 |
+
" torch.Tensor: Normalized image tensor\n",
|
| 1083 |
+
" \"\"\"\n",
|
| 1084 |
+
" # Read DICOM file\n",
|
| 1085 |
+
" dcm = pydicom.dcmread(dicom_path)\n",
|
| 1086 |
+
" image = dcm.pixel_array.astype(float)\n",
|
| 1087 |
+
" \n",
|
| 1088 |
+
" # Normalize image\n",
|
| 1089 |
+
" image = (image - image.min()) / (image.max() - image.min())\n",
|
| 1090 |
+
" \n",
|
| 1091 |
+
" # Convert to tensor\n",
|
| 1092 |
+
" image_tensor = torch.from_numpy(image).float().unsqueeze(0).unsqueeze(0) # Add batch and channel dimensions\n",
|
| 1093 |
+
" return image_tensor\n",
|
| 1094 |
+
"\n",
|
| 1095 |
+
"def calculate_psnr(output, target, max_pixel=1.0):\n",
|
| 1096 |
+
" \"\"\"\n",
|
| 1097 |
+
" Calculate Peak Signal-to-Noise Ratio (PSNR)\n",
|
| 1098 |
+
" \n",
|
| 1099 |
+
" Args:\n",
|
| 1100 |
+
" output (torch.Tensor): Reconstructed image\n",
|
| 1101 |
+
" target (torch.Tensor): Original image\n",
|
| 1102 |
+
" max_pixel (float): Maximum pixel value\n",
|
| 1103 |
+
" \n",
|
| 1104 |
+
" Returns:\n",
|
| 1105 |
+
" float: PSNR value\n",
|
| 1106 |
+
" \"\"\"\n",
|
| 1107 |
+
" # Ensure the values are in the correct range\n",
|
| 1108 |
+
" mse = torch.nn.functional.mse_loss(output, target)\n",
|
| 1109 |
+
" psnr = 20 * torch.log10(max_pixel / torch.sqrt(mse))\n",
|
| 1110 |
+
" return psnr.item()\n",
|
| 1111 |
+
"\n",
|
| 1112 |
+
"def visualize_reconstruction(original_image, reconstructed_image, psnr):\n",
|
| 1113 |
+
" \"\"\"\n",
|
| 1114 |
+
" Visualize original and reconstructed images\n",
|
| 1115 |
+
" \n",
|
| 1116 |
+
" Args:\n",
|
| 1117 |
+
" original_image (torch.Tensor): Original image tensor\n",
|
| 1118 |
+
" reconstructed_image (torch.Tensor): Reconstructed image tensor\n",
|
| 1119 |
+
" psnr (float): Peak Signal-to-Noise Ratio\n",
|
| 1120 |
+
" \"\"\"\n",
|
| 1121 |
+
" # Convert tensors to numpy for visualization\n",
|
| 1122 |
+
" original = original_image.squeeze().cpu().numpy()\n",
|
| 1123 |
+
" reconstructed = reconstructed_image.squeeze().cpu().numpy()\n",
|
| 1124 |
+
" \n",
|
| 1125 |
+
" # Create subplot\n",
|
| 1126 |
+
" fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))\n",
|
| 1127 |
+
" \n",
|
| 1128 |
+
" # Plot original image\n",
|
| 1129 |
+
" im1 = ax1.imshow(original, cmap='gray')\n",
|
| 1130 |
+
" ax1.set_title('Original Image')\n",
|
| 1131 |
+
" plt.colorbar(im1, ax=ax1)\n",
|
| 1132 |
+
" \n",
|
| 1133 |
+
" # Plot reconstructed image\n",
|
| 1134 |
+
" im2 = ax2.imshow(reconstructed, cmap='gray')\n",
|
| 1135 |
+
" ax2.set_title(f'Reconstructed Image\\nPSNR: {psnr:.2f} dB')\n",
|
| 1136 |
+
" plt.colorbar(im2, ax=ax2)\n",
|
| 1137 |
+
" \n",
|
| 1138 |
+
" plt.tight_layout()\n",
|
| 1139 |
+
" plt.show()\n",
|
| 1140 |
+
"\n",
|
| 1141 |
+
"def inference_single_image(reconstructor_model_path, denoiser_model_path, test_dicom_path):\n",
|
| 1142 |
+
" \"\"\"\n",
|
| 1143 |
+
" Perform inference on a single DICOM image using both Reconstructor and Denoiser models.\n",
|
| 1144 |
+
" \n",
|
| 1145 |
+
" Args:\n",
|
| 1146 |
+
" reconstructor_model_path (str): Path to the saved Reconstructor model weights\n",
|
| 1147 |
+
" denoiser_model_path (str): Path to the saved Denoiser model weights\n",
|
| 1148 |
+
" test_dicom_path (str): Path to the test DICOM file\n",
|
| 1149 |
+
" \"\"\"\n",
|
| 1150 |
+
" # Set device\n",
|
| 1151 |
+
" device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
|
| 1152 |
+
" \n",
|
| 1153 |
+
" # Initialize models\n",
|
| 1154 |
+
" reconstructor = Reconstructor().to(device)\n",
|
| 1155 |
+
" denoiser = Denoiser().to(device)\n",
|
| 1156 |
+
" \n",
|
| 1157 |
+
" # Load saved model weights\n",
|
| 1158 |
+
" reconstructor.load_state_dict(torch.load(reconstructor_model_path))\n",
|
| 1159 |
+
" denoiser.load_state_dict(torch.load(denoiser_model_path))\n",
|
| 1160 |
+
" \n",
|
| 1161 |
+
" reconstructor.eval()\n",
|
| 1162 |
+
" denoiser.eval()\n",
|
| 1163 |
+
" \n",
|
| 1164 |
+
" # Load and preprocess test image\n",
|
| 1165 |
+
" with torch.no_grad():\n",
|
| 1166 |
+
" test_image = load_dicom_image(test_dicom_path).to(device)\n",
|
| 1167 |
+
" \n",
|
| 1168 |
+
" # Perform reconstruction\n",
|
| 1169 |
+
" reconstructed_image = reconstructor(test_image)\n",
|
| 1170 |
+
" \n",
|
| 1171 |
+
" # Perform denoising on the reconstructed image\n",
|
| 1172 |
+
" denoised_image = denoiser(reconstructed_image)\n",
|
| 1173 |
+
" \n",
|
| 1174 |
+
" # Calculate PSNR for both original and denoised outputs\n",
|
| 1175 |
+
" psnr_reconstructed = calculate_psnr(reconstructed_image, test_image)\n",
|
| 1176 |
+
" psnr_denoised = calculate_psnr(denoised_image, test_image)\n",
|
| 1177 |
+
"\n",
|
| 1178 |
+
" print(f\"PSNR (Reconstructed): {psnr_reconstructed:.2f} dB\")\n",
|
| 1179 |
+
" print(f\"PSNR (Denoised): {psnr_denoised:.2f} dB\")\n",
|
| 1180 |
+
" \n",
|
| 1181 |
+
" # Visualize results\n",
|
| 1182 |
+
" visualize_reconstruction(test_image, reconstructed_image, psnr_reconstructed)\n",
|
| 1183 |
+
" visualize_reconstruction(test_image, denoised_image, psnr_denoised)\n",
|
| 1184 |
+
"\n",
|
| 1185 |
+
"# Example usage\n",
|
| 1186 |
+
"if __name__ == \"__main__\":\n",
|
| 1187 |
+
" # Paths to models and test image\n",
|
| 1188 |
+
" RECONSTRUCTOR_MODEL_PATH = r\"D:/VSCODE/PreSense/small_reconstructor.pth\" # Path to your saved Reconstructor model\n",
|
| 1189 |
+
" DENOISER_MODEL_PATH = r\"D:/VSCODE/PreSense/small_denoiser.pth\" # Path to your saved Denoiser model\n",
|
| 1190 |
+
" TEST_DICOM_PATH = r\"D:/VSCODE/PreSense/test2.dcm\" # Replace with actual path to test DICOM \n",
|
| 1191 |
+
" # Run inference\n",
|
| 1192 |
+
" inference_single_image(RECONSTRUCTOR_MODEL_PATH, DENOISER_MODEL_PATH, TEST_DICOM_PATH)"
|
| 1193 |
+
]
|
| 1194 |
+
},
|
| 1195 |
+
{
|
| 1196 |
+
"cell_type": "markdown",
|
| 1197 |
+
"metadata": {},
|
| 1198 |
+
"source": [
|
| 1199 |
+
"### Larger Reconstructor and Denoiser U-Net (largeRD)"
|
| 1200 |
+
]
|
| 1201 |
+
},
|
| 1202 |
+
{
|
| 1203 |
+
"cell_type": "code",
|
| 1204 |
+
"execution_count": null,
|
| 1205 |
+
"metadata": {},
|
| 1206 |
+
"outputs": [],
|
| 1207 |
+
"source": [
|
| 1208 |
+
"import torch\n",
|
| 1209 |
+
"import torch.nn as nn\n",
|
| 1210 |
+
"import torch.nn.functional as F\n",
|
| 1211 |
+
"import pydicom\n",
|
| 1212 |
+
"import numpy as np\n",
|
| 1213 |
+
"from torch.utils.data import Dataset, DataLoader\n",
|
| 1214 |
+
"import os\n",
|
| 1215 |
+
"from torch.utils.checkpoint import checkpoint\n",
|
| 1216 |
+
"from tqdm import tqdm # Import tqdm for progress bar\n",
|
| 1217 |
+
"\n",
|
| 1218 |
+
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
|
| 1219 |
+
"\n",
|
| 1220 |
+
"class MedicalImageDataset(Dataset):\n",
|
| 1221 |
+
" def __init__(self, dicom_dir):\n",
|
| 1222 |
+
" self.dicom_files = [os.path.join(dicom_dir, f) for f in os.listdir(dicom_dir) if f.endswith('.dcm')]\n",
|
| 1223 |
+
" \n",
|
| 1224 |
+
" def __len__(self):\n",
|
| 1225 |
+
" return len(self.dicom_files)\n",
|
| 1226 |
+
" \n",
|
| 1227 |
+
" def __getitem__(self, idx):\n",
|
| 1228 |
+
" # Read DICOM file and normalize\n",
|
| 1229 |
+
" dcm = pydicom.dcmread(self.dicom_files[idx])\n",
|
| 1230 |
+
" image = dcm.pixel_array.astype(float)\n",
|
| 1231 |
+
" image = (image - image.min()) / (image.max() - image.min())\n",
|
| 1232 |
+
" \n",
|
| 1233 |
+
" # Convert to tensor\n",
|
| 1234 |
+
" image_tensor = torch.from_numpy(image).float().unsqueeze(0)\n",
|
| 1235 |
+
" return image_tensor, image_tensor\n",
|
| 1236 |
+
"\n",
|
| 1237 |
+
"class UNetBlock(nn.Module):\n",
|
| 1238 |
+
" def __init__(self, in_channels, out_channels):\n",
|
| 1239 |
+
" super().__init__()\n",
|
| 1240 |
+
" self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1)\n",
|
| 1241 |
+
" self.bn1 = nn.BatchNorm2d(out_channels)\n",
|
| 1242 |
+
" self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1)\n",
|
| 1243 |
+
" self.bn2 = nn.BatchNorm2d(out_channels)\n",
|
| 1244 |
+
" self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1)\n",
|
| 1245 |
+
" self.bn2 = nn.BatchNorm2d(out_channels)\n",
|
| 1246 |
+
" \n",
|
| 1247 |
+
" def forward(self, x):\n",
|
| 1248 |
+
" x = F.relu(self.bn1(self.conv1(x)))\n",
|
| 1249 |
+
" x = F.relu(self.bn2(self.conv2(x)))\n",
|
| 1250 |
+
" return x\n",
|
| 1251 |
+
"\n",
|
| 1252 |
+
"class UNet(nn.Module):\n",
|
| 1253 |
+
" def __init__(self, in_channels=1, out_channels=1):\n",
|
| 1254 |
+
" super().__init__()\n",
|
| 1255 |
+
" # Encoder\n",
|
| 1256 |
+
" self.enc1 = UNetBlock(in_channels, 96)\n",
|
| 1257 |
+
" self.enc2 = UNetBlock(96, 192)\n",
|
| 1258 |
+
" self.enc3 = UNetBlock(192, 384)\n",
|
| 1259 |
+
" self.enc4 = UNetBlock(384, 784)\n",
|
| 1260 |
+
" \n",
|
| 1261 |
+
" # Decoder with learned upsampling (transposed convolutions)\n",
|
| 1262 |
+
" self.upconv4 = nn.ConvTranspose2d(784, 384, kernel_size=2, stride=2) # Learnable upsampling\n",
|
| 1263 |
+
" self.dec4 = UNetBlock(384 + 384, 384) # Adjust input channels after concatenation\n",
|
| 1264 |
+
"\n",
|
| 1265 |
+
" self.upconv3 = nn.ConvTranspose2d(384, 192, kernel_size=2, stride=2) # Learnable upsampling\n",
|
| 1266 |
+
" self.dec3 = UNetBlock(192 + 192, 192) # Adjust input channels after concatenation\n",
|
| 1267 |
+
"\n",
|
| 1268 |
+
" self.upconv2 = nn.ConvTranspose2d(192, 96, kernel_size=2, stride=2) # Learnable upsampling\n",
|
| 1269 |
+
" self.dec2 = UNetBlock(96 + 96, 96) # Adjust input channels after concatenation\n",
|
| 1270 |
+
"\n",
|
| 1271 |
+
" self.dec1 = UNetBlock(96, out_channels) # Final output\n",
|
| 1272 |
+
"\n",
|
| 1273 |
+
" self.pool = nn.MaxPool2d(2, 2)\n",
|
| 1274 |
+
" \n",
|
| 1275 |
+
" def forward(self, x):\n",
|
| 1276 |
+
" # Encoder path\n",
|
| 1277 |
+
" e1 = checkpoint(self.enc1, x)\n",
|
| 1278 |
+
" e2 = checkpoint(self.enc2, self.pool(e1))\n",
|
| 1279 |
+
" e3 = checkpoint(self.enc3, self.pool(e2))\n",
|
| 1280 |
+
" e4 = checkpoint(self.enc4, self.pool(e3))\n",
|
| 1281 |
+
" \n",
|
| 1282 |
+
" # Decoder path with learned upsampling and skip connections\n",
|
| 1283 |
+
" d4 = self.upconv4(e4) # Learnable upsampling\n",
|
| 1284 |
+
" d4 = torch.cat([d4, e3], dim=1) # Concatenate with encoder features\n",
|
| 1285 |
+
" d4 = checkpoint(self.dec4, d4)\n",
|
| 1286 |
+
"\n",
|
| 1287 |
+
" d3 = self.upconv3(d4) # Learnable upsampling\n",
|
| 1288 |
+
" d3 = torch.cat([d3, e2], dim=1) # Concatenate with encoder features\n",
|
| 1289 |
+
" d3 = checkpoint(self.dec3, d3)\n",
|
| 1290 |
+
"\n",
|
| 1291 |
+
" d2 = self.upconv2(d3) # Learnable upsampling\n",
|
| 1292 |
+
" d2 = torch.cat([d2, e1], dim=1) # Concatenate with encoder features\n",
|
| 1293 |
+
" d2 = checkpoint(self.dec2, d2)\n",
|
| 1294 |
+
" \n",
|
| 1295 |
+
" d1 = self.dec1(d2) # No checkpointing for final output layer\n",
|
| 1296 |
+
" \n",
|
| 1297 |
+
" return d1\n",
|
| 1298 |
+
"\n",
|
| 1299 |
+
"def calculate_loss(model, dataloader, criterion):\n",
|
| 1300 |
+
" model.eval()\n",
|
| 1301 |
+
" total_loss = 0\n",
|
| 1302 |
+
" with torch.no_grad():\n",
|
| 1303 |
+
" for images, targets in dataloader:\n",
|
| 1304 |
+
" images, targets = images.to(device), targets.to(device)\n",
|
| 1305 |
+
" outputs = model(images)\n",
|
| 1306 |
+
" loss = criterion(outputs, targets)\n",
|
| 1307 |
+
" total_loss += loss.item()\n",
|
| 1308 |
+
" return total_loss / len(dataloader)\n",
|
| 1309 |
+
"\n",
|
| 1310 |
+
"def calculate_psnr(output, target, max_pixel=1.0):\n",
|
| 1311 |
+
" # Ensure the values are in the correct range\n",
|
| 1312 |
+
" mse = F.mse_loss(output, target)\n",
|
| 1313 |
+
" psnr = 20 * torch.log10(max_pixel / torch.sqrt(mse))\n",
|
| 1314 |
+
" return psnr.item()\n",
|
| 1315 |
+
"\n",
|
| 1316 |
+
"def calculate_loss_and_psnr(model, dataloader, criterion):\n",
|
| 1317 |
+
" model.eval()\n",
|
| 1318 |
+
" total_loss = 0\n",
|
| 1319 |
+
" total_psnr = 0\n",
|
| 1320 |
+
" num_batches = len(dataloader)\n",
|
| 1321 |
+
" \n",
|
| 1322 |
+
" with torch.no_grad():\n",
|
| 1323 |
+
" for images, targets in dataloader:\n",
|
| 1324 |
+
" images, targets = images.to(device), targets.to(device)\n",
|
| 1325 |
+
" outputs = model(images)\n",
|
| 1326 |
+
" \n",
|
| 1327 |
+
" # Calculate MSE loss\n",
|
| 1328 |
+
" loss = criterion(outputs, targets)\n",
|
| 1329 |
+
" total_loss += loss.item()\n",
|
| 1330 |
+
" \n",
|
| 1331 |
+
" # Calculate PSNR\n",
|
| 1332 |
+
" psnr = calculate_psnr(outputs, targets)\n",
|
| 1333 |
+
" total_psnr += psnr\n",
|
| 1334 |
+
" \n",
|
| 1335 |
+
" avg_loss = total_loss / num_batches\n",
|
| 1336 |
+
" avg_psnr = total_psnr / num_batches\n",
|
| 1337 |
+
" \n",
|
| 1338 |
+
" return avg_loss, avg_psnr\n",
|
| 1339 |
+
"\n",
|
| 1340 |
+
"class Reconstructor(nn.Module):\n",
|
| 1341 |
+
" def __init__(self, in_channels=1, out_channels=1):\n",
|
| 1342 |
+
" super().__init__()\n",
|
| 1343 |
+
" # Same UNet architecture for reconstruction\n",
|
| 1344 |
+
" self.unet = UNet(in_channels=in_channels, out_channels=out_channels)\n",
|
| 1345 |
+
" \n",
|
| 1346 |
+
" def forward(self, x):\n",
|
| 1347 |
+
" return self.unet(x)\n",
|
| 1348 |
+
"\n",
|
| 1349 |
+
"\n",
|
| 1350 |
+
"class Denoiser(nn.Module):\n",
|
| 1351 |
+
" def __init__(self, in_channels=1, out_channels=1):\n",
|
| 1352 |
+
" super().__init__()\n",
|
| 1353 |
+
" # Same UNet architecture for denoising\n",
|
| 1354 |
+
" self.unet = UNet(in_channels=in_channels, out_channels=out_channels)\n",
|
| 1355 |
+
" \n",
|
| 1356 |
+
" def forward(self, x):\n",
|
| 1357 |
+
" return self.unet(x)\n",
|
| 1358 |
+
" \n",
|
| 1359 |
+
"def train_reconstructor_and_denoiser(dicom_dir, val_dicom_dir, epochs=50, batch_size=4, grad_accumulation_steps=2):\n",
|
| 1360 |
+
" # Dataset and DataLoader\n",
|
| 1361 |
+
" dataset = MedicalImageDataset(dicom_dir)\n",
|
| 1362 |
+
" train_dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)\n",
|
| 1363 |
+
" val_dataset = MedicalImageDataset(val_dicom_dir)\n",
|
| 1364 |
+
" val_dataloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)\n",
|
| 1365 |
+
" \n",
|
| 1366 |
+
" # Initialize both models\n",
|
| 1367 |
+
" reconstructor = Reconstructor().to(device)\n",
|
| 1368 |
+
" denoiser = Denoiser().to(device)\n",
|
| 1369 |
+
" \n",
|
| 1370 |
+
" # Loss functions for both models\n",
|
| 1371 |
+
" reconstructor_criterion = nn.MSELoss()\n",
|
| 1372 |
+
" denoiser_criterion = nn.MSELoss()\n",
|
| 1373 |
+
" \n",
|
| 1374 |
+
" # Optimizers for both models\n",
|
| 1375 |
+
" reconstructor_optimizer = torch.optim.Adam(reconstructor.parameters(), lr=0.0001)\n",
|
| 1376 |
+
" denoiser_optimizer = torch.optim.Adam(denoiser.parameters(), lr=0.0001)\n",
|
| 1377 |
+
" \n",
|
| 1378 |
+
" # Best validation loss initialization\n",
|
| 1379 |
+
" best_reconstructor_val_loss = float('inf')\n",
|
| 1380 |
+
" best_denoiser_val_loss = float('inf')\n",
|
| 1381 |
+
" best_reconstructor_model_path = 'best_reconstructor_model.pth'\n",
|
| 1382 |
+
" best_denoiser_model_path = 'best_denoiser_model.pth'\n",
|
| 1383 |
+
"\n",
|
| 1384 |
+
" # Training loop with tqdm\n",
|
| 1385 |
+
" for epoch in range(epochs):\n",
|
| 1386 |
+
" reconstructor.train()\n",
|
| 1387 |
+
" denoiser.train()\n",
|
| 1388 |
+
" \n",
|
| 1389 |
+
" reconstructor_total_loss = 0\n",
|
| 1390 |
+
" denoiser_total_loss = 0\n",
|
| 1391 |
+
" \n",
|
| 1392 |
+
" reconstructor_optimizer.zero_grad()\n",
|
| 1393 |
+
" denoiser_optimizer.zero_grad()\n",
|
| 1394 |
+
"\n",
|
| 1395 |
+
" with tqdm(train_dataloader, unit=\"batch\", desc=f\"Epoch {epoch+1}/{epochs}\") as tepoch:\n",
|
| 1396 |
+
" for i, (images, targets) in enumerate(tepoch):\n",
|
| 1397 |
+
" images, targets = images.to(device), targets.to(device)\n",
|
| 1398 |
+
" \n",
|
| 1399 |
+
" # Training Reconstructor\n",
|
| 1400 |
+
" reconstructor_outputs = reconstructor(images)\n",
|
| 1401 |
+
" reconstructor_loss = reconstructor_criterion(reconstructor_outputs, targets)\n",
|
| 1402 |
+
" reconstructor_loss.backward(retain_graph=True)\n",
|
| 1403 |
+
"\n",
|
| 1404 |
+
" # Gradient accumulation for reconstructor\n",
|
| 1405 |
+
" if (i + 1) % grad_accumulation_steps == 0 or (i + 1) == len(tepoch):\n",
|
| 1406 |
+
" reconstructor_optimizer.step()\n",
|
| 1407 |
+
" reconstructor_optimizer.zero_grad()\n",
|
| 1408 |
+
"\n",
|
| 1409 |
+
" reconstructor_total_loss += reconstructor_loss.item()\n",
|
| 1410 |
+
"\n",
|
| 1411 |
+
" # Training Denoiser (using output from Reconstructor as noisy input)\n",
|
| 1412 |
+
" noisy_images = reconstructor_outputs.detach() # Detach from the computation graph to avoid in-place error\n",
|
| 1413 |
+
" denoiser_outputs = denoiser(noisy_images)\n",
|
| 1414 |
+
" denoiser_loss = denoiser_criterion(denoiser_outputs, targets)\n",
|
| 1415 |
+
" denoiser_loss.backward()\n",
|
| 1416 |
+
"\n",
|
| 1417 |
+
" # Gradient accumulation for denoiser\n",
|
| 1418 |
+
" if (i + 1) % grad_accumulation_steps == 0 or (i + 1) == len(tepoch):\n",
|
| 1419 |
+
" denoiser_optimizer.step()\n",
|
| 1420 |
+
" denoiser_optimizer.zero_grad()\n",
|
| 1421 |
+
"\n",
|
| 1422 |
+
" denoiser_total_loss += denoiser_loss.item()\n",
|
| 1423 |
+
"\n",
|
| 1424 |
+
" # Update the tqdm progress bar with current loss\n",
|
| 1425 |
+
" tepoch.set_postfix(\n",
|
| 1426 |
+
" reconstructor_loss=reconstructor_total_loss / ((i + 1) * batch_size),\n",
|
| 1427 |
+
" denoiser_loss=denoiser_total_loss / ((i + 1) * batch_size)\n",
|
| 1428 |
+
" )\n",
|
| 1429 |
+
" \n",
|
| 1430 |
+
" # Calculate validation loss for both models\n",
|
| 1431 |
+
" avg_reconstructor_train_loss = reconstructor_total_loss / len(train_dataloader)\n",
|
| 1432 |
+
" avg_denoiser_train_loss = denoiser_total_loss / len(train_dataloader)\n",
|
| 1433 |
+
" \n",
|
| 1434 |
+
" avg_reconstructor_val_loss, _ = calculate_loss_and_psnr(reconstructor, val_dataloader, reconstructor_criterion)\n",
|
| 1435 |
+
" avg_denoiser_val_loss, _ = calculate_loss_and_psnr(denoiser, val_dataloader, denoiser_criterion)\n",
|
| 1436 |
+
" \n",
|
| 1437 |
+
" print(f\"Epoch [{epoch+1}/{epochs}] - \"\n",
|
| 1438 |
+
" f\"Reconstructor Train Loss: {avg_reconstructor_train_loss:.4f}, \"\n",
|
| 1439 |
+
" f\"Denoiser Train Loss: {avg_denoiser_train_loss:.4f}, \"\n",
|
| 1440 |
+
" f\"Reconstructor Val Loss: {avg_reconstructor_val_loss:.4f}, \"\n",
|
| 1441 |
+
" f\"Denoiser Val Loss: {avg_denoiser_val_loss:.4f}\")\n",
|
| 1442 |
+
" \n",
|
| 1443 |
+
" # Save models if validation loss is improved\n",
|
| 1444 |
+
" if avg_reconstructor_val_loss < best_reconstructor_val_loss:\n",
|
| 1445 |
+
" best_reconstructor_val_loss = avg_reconstructor_val_loss\n",
|
| 1446 |
+
" torch.save(reconstructor.state_dict(), best_reconstructor_model_path)\n",
|
| 1447 |
+
" print(f\"Reconstructor model saved with improved validation loss: {avg_reconstructor_val_loss:.4f}\")\n",
|
| 1448 |
+
" \n",
|
| 1449 |
+
" if avg_denoiser_val_loss < best_denoiser_val_loss:\n",
|
| 1450 |
+
" best_denoiser_val_loss = avg_denoiser_val_loss\n",
|
| 1451 |
+
" torch.save(denoiser.state_dict(), best_denoiser_model_path)\n",
|
| 1452 |
+
" print(f\"Denoiser model saved with improved validation loss: {avg_denoiser_val_loss:.4f}\")\n",
|
| 1453 |
+
" \n",
|
| 1454 |
+
" return reconstructor, denoiser\n",
|
| 1455 |
+
"\n",
|
| 1456 |
+
"# Example usage with train and validation directories\n",
|
| 1457 |
+
"reconstructor_model, denoiser_model = train_reconstructor_and_denoiser(\n",
|
| 1458 |
+
" r\"D:\\PN_Split\\train\", r\"D:\\PN_Split\\val\", epochs=50, batch_size=1, grad_accumulation_steps=64\n",
|
| 1459 |
+
")"
|
| 1460 |
+
]
|
| 1461 |
+
}
|
| 1462 |
+
],
|
| 1463 |
+
"metadata": {
|
| 1464 |
+
"kernelspec": {
|
| 1465 |
+
"display_name": "tf",
|
| 1466 |
+
"language": "python",
|
| 1467 |
+
"name": "python3"
|
| 1468 |
+
},
|
| 1469 |
+
"language_info": {
|
| 1470 |
+
"codemirror_mode": {
|
| 1471 |
+
"name": "ipython",
|
| 1472 |
+
"version": 3
|
| 1473 |
+
},
|
| 1474 |
+
"file_extension": ".py",
|
| 1475 |
+
"mimetype": "text/x-python",
|
| 1476 |
+
"name": "python",
|
| 1477 |
+
"nbconvert_exporter": "python",
|
| 1478 |
+
"pygments_lexer": "ipython3",
|
| 1479 |
+
"version": "3.10.11"
|
| 1480 |
+
}
|
| 1481 |
+
},
|
| 1482 |
+
"nbformat": 4,
|
| 1483 |
+
"nbformat_minor": 2
|
| 1484 |
+
}
|