dataset.py 12 KB

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