dataset.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. import math
  2. import pathlib as pl
  3. import random
  4. import re
  5. from typing import Callable, Dict, Iterator, List, Tuple
  6. import nibabel as nib
  7. import pandas as pd
  8. import torch
  9. import torch.utils.data as data
  10. from jaxtyping import Float
  11. from torch.utils.data import DataLoader, Subset
  12. from util.seeding import torch_generator
  13. # Tokens that appear in MRI filenames to indicate the diagnostic class.
  14. # On disk the cognitively-normal class is spelled "NL" (not "CN").
  15. CLASS_TOKENS: Dict[str, torch.Tensor] = {
  16. "AD": torch.tensor([1.0, 0.0]),
  17. "NL": torch.tensor([0.0, 1.0]),
  18. }
  19. def _row_to_float_tensor(row: pd.DataFrame, *, image_id: int) -> torch.Tensor:
  20. values = row.drop(columns=["Image Data ID"]).iloc[0]
  21. numeric = pd.to_numeric(values, errors="coerce")
  22. if numeric.isna().any(): # pyright: ignore
  23. bad_columns = [column for column, value in numeric.items() if pd.isna(value)] # pyright: ignore
  24. raise ValueError(
  25. f"Non-numeric Excel values for Image Data ID {image_id}: {bad_columns}"
  26. )
  27. return torch.tensor(numeric.to_numpy(dtype="float32")) # pyright: ignore
  28. def xls_pre(df: pd.DataFrame) -> pd.DataFrame:
  29. """
  30. Preprocess the Excel DataFrame.
  31. This function can be customized to filter or modify the DataFrame as needed.
  32. Returns a DataFrame with columns [Image Data ID, Sex, Age (current)] where
  33. Sex is encoded 0/1. "Image Data ID" is deliberately kept as a column (not an
  34. index) because downstream lookups filter on it directly
  35. (``xls_values["Image Data ID"] == img_id``).
  36. """
  37. # Work on an explicit copy so column assignment writes back reliably instead
  38. # of raising SettingWithCopyWarning against a view of ``df``.
  39. data = df[["Image Data ID", "Sex", "Age (current)"]].copy()
  40. data["Sex"] = data["Sex"].str.strip()
  41. data = data.replace({"M": 0, "F": 1})
  42. return data
  43. class ADNIDataset(data.Dataset): # type: ignore
  44. """
  45. A PyTorch Dataset class for loading
  46. and processing MRI and Excel data from the ADNI dataset.
  47. """
  48. def __init__(
  49. self,
  50. mri_data: Float[torch.Tensor, "n_samples channels width height depth"],
  51. xls_data: Float[torch.Tensor, "n_samples features"],
  52. expected_classes: Float[
  53. torch.Tensor, " classes"
  54. ], # leading space is necessary so pyright doesn't complain
  55. filename_ids: List[int],
  56. device: str = "cuda",
  57. ):
  58. """
  59. Args:
  60. mri_data (torch.Tensor): 5D tensor of MRI data with shape (n_samples, channels, width, height, depth).
  61. xls_data (torch.Tensor): 2D tensor of Excel data with shape (n_samples, features).
  62. """
  63. # Keep full datasets on CPU and move only active batches to accelerator.
  64. # This avoids loading the entire training corpus into VRAM.
  65. self.mri_data = mri_data.float().cpu()
  66. self.xls_data = xls_data.float().cpu()
  67. self.expected_classes = expected_classes.float().cpu()
  68. self.filename_ids = filename_ids
  69. def __len__(self) -> int:
  70. """
  71. Returns the number of samples in the dataset.
  72. """
  73. return self.mri_data.shape[0] # 0th dimension is the number of samples
  74. def __getitem__(
  75. self, idx: int
  76. ) -> Tuple[
  77. Float[torch.Tensor, "channels width height depth"],
  78. Float[torch.Tensor, " features"],
  79. Float[torch.Tensor, " classes"],
  80. int,
  81. ]:
  82. """
  83. Returns a sample from the dataset at the given index.
  84. Args:
  85. idx (int): Index of the sample to retrieve.
  86. Returns:
  87. tuple: A tuple containing the MRI data and Excel data for the sample.
  88. """
  89. # Slices the data on the 0th dimension, corresponding to the sample index
  90. mri_sample = self.mri_data[idx]
  91. xls_sample = self.xls_data[idx]
  92. # Assuming expected_classes is a tensor of classes, we return it as well
  93. expected_classes = self.expected_classes[idx]
  94. filename_id = self.filename_ids[idx]
  95. return mri_sample, xls_sample, expected_classes, filename_id
  96. def load_adni_data_from_file(
  97. mri_files: Iterator[pl.Path], # List of nibablel files
  98. xls_file: pl.Path, # Path to the Excel file
  99. device: str = "cuda",
  100. xls_preprocessor: Callable[[pd.DataFrame], pd.DataFrame] = lambda x: x,
  101. ) -> ADNIDataset:
  102. """
  103. Loads MRI and Excel data from the ADNI dataset.
  104. Args:
  105. mri_files (List[pl.Path]): List of paths to the MRI files.
  106. xls_file (pl.Path): Path to the Excel file.
  107. Returns:
  108. ADNIDataset: The loaded dataset.
  109. """
  110. # Load the Excel data
  111. xls_values = xls_preprocessor(pd.read_csv(xls_file)) # type: ignore
  112. # Load the MRI data
  113. mri_data_unstacked: List[torch.Tensor] = []
  114. expected_classes_unstacked: List[torch.Tensor] = []
  115. xls_data_unstacked: List[torch.Tensor] = []
  116. img_ids: List[int] = []
  117. for file in mri_files:
  118. filename = file.stem
  119. match re.search(r".+?(?=_I)_I(\d+).+", filename):
  120. case None:
  121. raise ValueError(
  122. f"Filename {filename} does not match expected pattern."
  123. )
  124. case m:
  125. img_id = int(m.group(1))
  126. file_mri_data = torch.from_numpy(nib.load(file).get_fdata()) # type: ignore # type checking does not work well with nibabel
  127. # Read the filename to determine the expected class. On disk the classes
  128. # are spelled "AD" and "NL"; see CLASS_TOKENS.
  129. file_expected_class: torch.Tensor | None = None
  130. for token, one_hot in CLASS_TOKENS.items():
  131. if token in filename:
  132. file_expected_class = one_hot.clone()
  133. break
  134. if file_expected_class is None:
  135. raise ValueError(
  136. f"Filename {filename} does not contain a valid class identifier "
  137. f"({' or '.join(CLASS_TOKENS)})."
  138. )
  139. mri_data_unstacked.append(file_mri_data)
  140. expected_classes_unstacked.append(file_expected_class)
  141. # Extract the corresponding row from the Excel data using the img_id
  142. xls_row = xls_values.loc[xls_values["Image Data ID"] == img_id]
  143. if xls_row.empty:
  144. raise ValueError(
  145. f"No matching row found in Excel data for Image Data ID {img_id}."
  146. )
  147. elif len(xls_row) > 1:
  148. raise ValueError(
  149. f"Multiple rows found in Excel data for Image Data ID {img_id}."
  150. )
  151. file_xls_data = _row_to_float_tensor(xls_row, image_id=img_id)
  152. xls_data_unstacked.append(file_xls_data)
  153. img_ids.append(img_id)
  154. mri_data = torch.stack(mri_data_unstacked).unsqueeze(1)
  155. # Stack the list of tensors into a single tensor and unsqueeze along the channel dimension
  156. xls_data = torch.stack(
  157. xls_data_unstacked
  158. ) # Stack the list of tensors into a single tensor
  159. expected_classes = torch.stack(
  160. expected_classes_unstacked
  161. ) # Stack the list of expected classes into a single tensor
  162. return ADNIDataset(mri_data, xls_data, expected_classes, img_ids, device=device)
  163. def divide_dataset(
  164. dataset: ADNIDataset,
  165. ratios: Tuple[float, float, float],
  166. seed: int,
  167. ) -> List[data.Subset[ADNIDataset]]:
  168. """
  169. Divides the dataset into training, validation, and test sets.
  170. Args:
  171. dataset (ADNIDataset): The dataset to divide.
  172. train_ratio (float): The ratio of the training set.
  173. val_ratio (float): The ratio of the validation set.
  174. test_ratio (float): The ratio of the test set.
  175. Returns:
  176. Result[List[data.Subset[ADNIDataset]], str]: A Result object containing the subsets or an error message.
  177. """
  178. if not math.isclose(sum(ratios), 1.0, rel_tol=1e-9, abs_tol=1e-9):
  179. raise ValueError(f"Ratios must sum to 1.0, got {ratios} (sum={sum(ratios)}).")
  180. # Set the random seed for reproducibility
  181. gen = torch.Generator().manual_seed(seed)
  182. return data.random_split(dataset, ratios, generator=gen)
  183. def initalize_dataloaders(
  184. datasets: List[Subset[ADNIDataset]],
  185. batch_size: int = 64,
  186. seed: int | None = None,
  187. ) -> List[DataLoader[ADNIDataset]]:
  188. """
  189. Initializes the DataLoaders for the [train, val, test] datasets.
  190. The three splits are configured differently:
  191. - train: shuffled (for SGD) with a seeded generator for reproducibility,
  192. and ``drop_last=True`` so a size-1 final batch cannot crash BatchNorm1d.
  193. - val / test: NOT shuffled, so sample order is stable. Stable order is
  194. required for evaluation, where saved model outputs must align with a
  195. fixed sample axis (see the netCDF evaluation schema).
  196. Args:
  197. datasets: Subsets in ``[train, val, test]`` order.
  198. batch_size: The batch size for the DataLoaders.
  199. seed: Seed for the training shuffle generator. ``None`` leaves shuffling
  200. to global RNG state.
  201. Returns:
  202. List[DataLoader[ADNIDataset]]: DataLoaders in the same order as ``datasets``.
  203. """
  204. loader_configs = [
  205. {"shuffle": True, "drop_last": True}, # train
  206. {"shuffle": False, "drop_last": False}, # val
  207. {"shuffle": False, "drop_last": False}, # test
  208. ]
  209. if len(datasets) != len(loader_configs):
  210. raise ValueError(
  211. f"Expected 3 datasets ([train, val, test]), got {len(datasets)}."
  212. )
  213. pin_memory = torch.cuda.is_available()
  214. loaders: List[DataLoader[ADNIDataset]] = []
  215. for dataset, cfg in zip(datasets, loader_configs):
  216. generator = torch_generator(seed) if cfg["shuffle"] else None
  217. loaders.append(
  218. DataLoader(
  219. dataset,
  220. batch_size=batch_size,
  221. shuffle=cfg["shuffle"],
  222. drop_last=cfg["drop_last"],
  223. pin_memory=pin_memory,
  224. generator=generator,
  225. )
  226. )
  227. return loaders
  228. def divide_dataset_by_patient_id(
  229. dataset: ADNIDataset,
  230. ptids: List[Tuple[int, str]],
  231. ratios: Tuple[float, float, float],
  232. seed: int,
  233. ) -> List[data.Subset[ADNIDataset]]:
  234. """
  235. Divides the dataset into training, validation, and test sets based on patient IDs.
  236. Ensures that all samples from the same patient are in the same set.
  237. Args:
  238. dataset (ADNIDataset): The dataset to divide.
  239. ptids (List[Tuple[int, str]]): A list of tuples containing image file IDs and their corresponding patient IDs.
  240. ratios (Tuple[float, float, float]): The ratios for training, validation, and test sets.
  241. seed (int): The random seed for reproducibility.
  242. Returns:
  243. List[data.Subset[ADNIDataset]]: A list of subsets for training, validation, and test sets.
  244. Notes:
  245. This split is grouped by PTID, so all images from the same patient are assigned
  246. to exactly one partition to avoid patient-level leakage across train/val/test.
  247. """
  248. if not math.isclose(sum(ratios), 1.0, rel_tol=1e-9, abs_tol=1e-9):
  249. raise ValueError(f"Ratios must sum to 1.0, got {ratios} (sum={sum(ratios)}).")
  250. if not ptids:
  251. raise ValueError("ptids list cannot be empty.")
  252. image_to_patient: Dict[int, str] = {}
  253. for image_id, patient_id in ptids:
  254. image_id_int = int(image_id)
  255. patient_id_str = str(patient_id).strip()
  256. if not patient_id_str or patient_id_str.lower() == "nan":
  257. raise ValueError(f"Invalid PTID for Image Data ID {image_id_int}.")
  258. if (
  259. image_id_int in image_to_patient
  260. and image_to_patient[image_id_int] != patient_id_str
  261. ):
  262. raise ValueError(
  263. f"Conflicting PTIDs for Image Data ID {image_id_int}: "
  264. f"{image_to_patient[image_id_int]} vs {patient_id_str}."
  265. )
  266. image_to_patient[image_id_int] = patient_id_str
  267. patient_to_indices: Dict[str, List[int]] = {}
  268. for idx, image_id in enumerate(dataset.filename_ids):
  269. if image_id not in image_to_patient:
  270. raise ValueError(
  271. f"Missing PTID mapping for dataset Image Data ID {image_id}."
  272. )
  273. patient_id = image_to_patient[image_id]
  274. if patient_id not in patient_to_indices:
  275. patient_to_indices[patient_id] = []
  276. patient_to_indices[patient_id].append(idx)
  277. shuffled_patients = list(patient_to_indices.keys())
  278. random.Random(seed).shuffle(shuffled_patients)
  279. train_cutoff = int(len(shuffled_patients) * ratios[0])
  280. val_cutoff = train_cutoff + int(len(shuffled_patients) * ratios[1])
  281. train_patients = shuffled_patients[:train_cutoff]
  282. val_patients = shuffled_patients[train_cutoff:val_cutoff]
  283. test_patients = shuffled_patients[val_cutoff:]
  284. train_patient_set = set(train_patients)
  285. val_patient_set = set(val_patients)
  286. test_patient_set = set(test_patients)
  287. if (
  288. train_patient_set & val_patient_set
  289. or train_patient_set & test_patient_set
  290. or val_patient_set & test_patient_set
  291. ):
  292. raise ValueError("Patient separation violated across train/val/test splits.")
  293. all_patients = set(patient_to_indices.keys())
  294. if train_patient_set | val_patient_set | test_patient_set != all_patients:
  295. raise ValueError("Not all patients were assigned to a split.")
  296. train_indices = [
  297. idx for patient_id in train_patients for idx in patient_to_indices[patient_id]
  298. ]
  299. val_indices = [
  300. idx for patient_id in val_patients for idx in patient_to_indices[patient_id]
  301. ]
  302. test_indices = [
  303. idx for patient_id in test_patients for idx in patient_to_indices[patient_id]
  304. ]
  305. train_index_set = set(train_indices)
  306. val_index_set = set(val_indices)
  307. test_index_set = set(test_indices)
  308. if (
  309. train_index_set & val_index_set
  310. or train_index_set & test_index_set
  311. or val_index_set & test_index_set
  312. ):
  313. raise ValueError("Sample index overlap detected across train/val/test splits.")
  314. all_split_indices = train_index_set | val_index_set | test_index_set
  315. expected_indices = set(range(len(dataset)))
  316. if all_split_indices != expected_indices:
  317. raise ValueError(
  318. "Split coverage check failed: not all dataset samples are assigned exactly once."
  319. )
  320. return [
  321. Subset(dataset, train_indices),
  322. Subset(dataset, val_indices),
  323. Subset(dataset, test_indices),
  324. ]