datasets.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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(mri_dir, xls_file, val_split=0.2, seed=50, device=None):
  16. if device is None:
  17. device = torch.device('cpu')
  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. train_dataset = ADNIDataset(train_list, xls_data, device=device)
  33. val_dataset = ADNIDataset(val_list, xls_data, device=device)
  34. test_dataset = ADNIDataset(test_list, xls_data, device=device)
  35. return train_dataset, val_dataset, test_dataset
  36. # TODO Normalize data? Later add / Exctract clinical data? Which data?
  37. """
  38. Returns train_list, val_list and test_list in format [(image, id), ...] each
  39. """
  40. def get_train_val_test(AD_list, NL_list, val_split):
  41. train_list, val_list, test_list = [], [], []
  42. # For the purposes of this split, the val_split constitutes the validation and testing split, as they are divided evenly
  43. # get the overall length of the data
  44. AD_len = len(AD_list)
  45. NL_len = len(NL_list)
  46. # First, determine the length of each of the sets
  47. AD_val_len = int(math.ceil(AD_len * val_split * 0.5))
  48. NL_val_len = int(math.ceil(NL_len * val_split * 0.5))
  49. AD_test_len = int(math.floor(AD_len * val_split * 0.5))
  50. NL_test_len = int(math.floor(NL_len * val_split * 0.5))
  51. AD_train_len = AD_len - AD_val_len - AD_test_len
  52. NL_train_len = NL_len - NL_val_len - NL_test_len
  53. # Add the data to the sets
  54. for i in range(AD_train_len):
  55. train_list.append((AD_list[i], 1))
  56. for i in range(NL_train_len):
  57. train_list.append((NL_list[i], 0))
  58. for i in range(AD_train_len, AD_train_len + AD_val_len):
  59. val_list.append((AD_list[i], 1))
  60. for i in range(NL_train_len, NL_train_len + NL_val_len):
  61. val_list.append((NL_list[i], 0))
  62. for i in range(AD_train_len + AD_val_len, AD_len):
  63. test_list.append((AD_list[i], 1))
  64. for i in range(NL_train_len + NL_val_len, NL_len):
  65. test_list.append((NL_list[i], 0))
  66. return train_list, val_list, test_list
  67. class ADNIDataset(Dataset):
  68. def __init__(self, mri, xls: pd.DataFrame, device=torch.device('cpu')):
  69. self.mri_data = mri # DATA IS A LIST WITH TUPLES (image_dir, class_id)
  70. self.xls_data = xls
  71. self.device = device
  72. def __len__(self):
  73. return len(self.mri_data)
  74. def _xls_to_tensor(self, xls_data: pd.Series):
  75. # Get used data
  76. # data = xls_data.loc[['Sex', 'Age (current)', 'PTID', 'DXCONFID (1=uncertain, 2= mild, 3= moderate, 4=high confidence)', 'Alz_csf']]
  77. data = xls_data.loc[['Sex', 'Age (current)']]
  78. data.replace({'M': 0, 'F': 1}, inplace=True)
  79. # Convert to tensor
  80. xls_tensor = torch.tensor(data.values.astype(float))
  81. return xls_tensor
  82. def __getitem__(
  83. self, idx
  84. ): # RETURNS TUPLE WITH IMAGE AND CLASS_ID, BASED ON INDEX IDX
  85. mri_path, class_id = self.mri_data[idx]
  86. mri = nib.load(mri_path)
  87. mri_data = mri.get_fdata()
  88. xls = self.xls_data.iloc[idx]
  89. # Convert xls data to tensor
  90. xls_tensor = self._xls_to_tensor(xls)
  91. mri_tensor = torch.from_numpy(mri_data).unsqueeze(0)
  92. class_id = torch.tensor([class_id])
  93. # Convert to one-hot and squeeze
  94. class_id = torch.nn.functional.one_hot(class_id, num_classes=2).squeeze(0)
  95. # Convert to float
  96. mri_tensor = mri_tensor.float().to(self.device)
  97. xls_tensor = xls_tensor.float().to(self.device)
  98. class_id = class_id.float().to(self.device)
  99. return (mri_tensor, xls_tensor), class_id
  100. def initalize_dataloaders(
  101. training_data,
  102. val_data,
  103. test_data,
  104. batch_size=64,
  105. ):
  106. train_dataloader = DataLoader(training_data, batch_size=batch_size, shuffle=True)
  107. test_dataloader = DataLoader(test_data, batch_size=(batch_size // 4), shuffle=True)
  108. val_dataloader = DataLoader(val_data, batch_size=batch_size, shuffle=True)
  109. return train_dataloader, val_dataloader, test_dataloader