datasets.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. # NEEDS TO BE FINISHED
  2. # TODO CHECK ABOUT IMAGE DIMENSIONS
  3. # TODO ENSURE ITERATION WORKS
  4. import glob
  5. import nibabel as nib
  6. import random
  7. import torch
  8. from torch.utils.data import Dataset
  9. import pandas as pd
  10. from torch.utils.data import DataLoader
  11. import math
  12. """
  13. Prepares CustomDatasets for training, validating, and testing CNN
  14. """
  15. def prepare_datasets(
  16. mri_dir, xls_file, val_split=0.2, seed=50, device=torch.device("cpu")
  17. ):
  18. rndm = random.Random(seed)
  19. xls_data = pd.read_csv(xls_file).set_index("Image Data ID")
  20. raw_data = glob.glob(mri_dir + "*")
  21. AD_list = []
  22. NL_list = []
  23. # TODO Check that image is in CSV?
  24. for image in raw_data:
  25. if "NL" in image:
  26. NL_list.append(image)
  27. elif "AD" in image:
  28. AD_list.append(image)
  29. rndm.shuffle(AD_list)
  30. rndm.shuffle(NL_list)
  31. train_list, val_list, test_list = get_train_val_test(AD_list, NL_list, val_split)
  32. rndm.shuffle(train_list)
  33. rndm.shuffle(val_list)
  34. rndm.shuffle(test_list)
  35. train_dataset = ADNIDataset(train_list, xls_data, device=device)
  36. val_dataset = ADNIDataset(val_list, xls_data, device=device)
  37. test_dataset = ADNIDataset(test_list, xls_data, device=device)
  38. return train_dataset, val_dataset, test_dataset
  39. # TODO Normalize data? Later add / Exctract clinical data? Which data?
  40. """
  41. Returns train_list, val_list and test_list in format [(image, id), ...] each
  42. """
  43. def get_train_val_test(AD_list, NL_list, val_split):
  44. train_list, val_list, test_list = [], [], []
  45. # For the purposes of this split, the val_split constitutes the validation and testing split, as they are divided evenly
  46. # get the overall length of the data
  47. AD_len = len(AD_list)
  48. NL_len = len(NL_list)
  49. # First, determine the length of each of the sets
  50. AD_val_len = int(math.ceil(AD_len * val_split * 0.5))
  51. NL_val_len = int(math.ceil(NL_len * val_split * 0.5))
  52. AD_test_len = int(math.floor(AD_len * val_split * 0.5))
  53. NL_test_len = int(math.floor(NL_len * val_split * 0.5))
  54. AD_train_len = AD_len - AD_val_len - AD_test_len
  55. NL_train_len = NL_len - NL_val_len - NL_test_len
  56. # Add the data to the sets
  57. for i in range(AD_train_len):
  58. train_list.append((AD_list[i], 1))
  59. for i in range(NL_train_len):
  60. train_list.append((NL_list[i], 0))
  61. for i in range(AD_train_len, AD_train_len + AD_val_len):
  62. val_list.append((AD_list[i], 1))
  63. for i in range(NL_train_len, NL_train_len + NL_val_len):
  64. val_list.append((NL_list[i], 0))
  65. for i in range(AD_train_len + AD_val_len, AD_len):
  66. test_list.append((AD_list[i], 1))
  67. for i in range(NL_train_len + NL_val_len, NL_len):
  68. test_list.append((NL_list[i], 0))
  69. return train_list, val_list, test_list
  70. class ADNIDataset(Dataset):
  71. def __init__(self, mri, xls: pd.DataFrame, device=torch.device("cpu")):
  72. self.mri_data = mri # DATA IS A LIST WITH TUPLES (image_dir, class_id)
  73. self.xls_data = xls
  74. self.device = device
  75. def __len__(self):
  76. return len(self.mri_data)
  77. def _xls_to_tensor(self, xls_data: pd.Series):
  78. # Get used data
  79. # data = xls_data.loc[['Sex', 'Age (current)', 'PTID', 'DXCONFID (1=uncertain, 2= mild, 3= moderate, 4=high confidence)', 'Alz_csf']]
  80. data = xls_data.loc[["Sex", "Age (current)"]]
  81. data.replace({"M": 0, "F": 1}, inplace=True)
  82. # Convert to tensor
  83. xls_tensor = torch.tensor(data.values.astype(float))
  84. return xls_tensor
  85. def __getitem__(
  86. self, idx
  87. ): # RETURNS TUPLE WITH IMAGE AND CLASS_ID, BASED ON INDEX IDX
  88. mri_path, class_id = self.mri_data[idx]
  89. mri = nib.load(mri_path)
  90. mri_data = mri.get_fdata()
  91. xls = self.xls_data.iloc[idx]
  92. # Convert xls data to tensor
  93. xls_tensor = self._xls_to_tensor(xls)
  94. mri_tensor = torch.from_numpy(mri_data).unsqueeze(0)
  95. class_id = torch.tensor([class_id])
  96. # Convert to one-hot and squeeze
  97. class_id = torch.nn.functional.one_hot(class_id, num_classes=2).squeeze(0)
  98. # Convert to float
  99. mri_tensor = mri_tensor.float().to(self.device)
  100. xls_tensor = xls_tensor.float().to(self.device)
  101. class_id = class_id.float().to(self.device)
  102. return (mri_tensor, xls_tensor), class_id
  103. def initalize_dataloaders(
  104. training_data,
  105. val_data,
  106. test_data,
  107. batch_size=64,
  108. ):
  109. train_dataloader = DataLoader(training_data, batch_size=batch_size, shuffle=True)
  110. test_dataloader = DataLoader(test_data, batch_size=(batch_size // 4), shuffle=True)
  111. val_dataloader = DataLoader(val_data, batch_size=batch_size, shuffle=True)
  112. return train_dataloader, val_dataloader, test_dataloader