preprocess.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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 numpy as np
  7. import random
  8. import torch
  9. from torch.utils.data import Dataset
  10. import pandas as pd
  11. '''
  12. Prepares CustomDatasets for training, validating, and testing CNN
  13. '''
  14. def prepare_datasets(mri_dir, xls_file, val_split=0.2, seed=50):
  15. rndm = random.Random(seed)
  16. xls_data = pd.read_csv(xls_file).set_index('Image Data ID')
  17. raw_data = glob.glob(mri_dir + "*")
  18. AD_list = []
  19. NL_list = []
  20. # TODO Check that image is in CSV?
  21. for image in raw_data:
  22. if "NL" in image:
  23. NL_list.append(image)
  24. elif "AD" in image:
  25. AD_list.append(image)
  26. rndm.shuffle(AD_list)
  27. rndm.shuffle(NL_list)
  28. train_list, val_list, test_list = get_train_val_test(AD_list, NL_list, val_split)
  29. rndm.shuffle(train_list)
  30. rndm.shuffle(val_list)
  31. rndm.shuffle(test_list)
  32. train_dataset = CustomDataset(train_list, xls_data)
  33. val_dataset = CustomDataset(val_list, xls_data)
  34. test_dataset = CustomDataset(test_list, xls_data)
  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. num_test_ad = int(len(AD_list) * val_split)
  43. num_test_nl = int(len(NL_list) * val_split)
  44. num_val_ad = int((len(AD_list) - num_test_ad) * val_split)
  45. num_val_nl = int((len(NL_list) - num_test_nl) * val_split)
  46. # Sets up ADs
  47. for image in AD_list[0:num_val_ad]:
  48. val_list.append((image, 1))
  49. for image in AD_list[num_val_ad:num_test_ad]:
  50. test_list.append((image, 1))
  51. for image in AD_list[num_test_ad:]:
  52. train_list.append((image, 1))
  53. # Sets up NLs
  54. for image in NL_list[0:num_val_nl]:
  55. val_list.append((image, 0))
  56. for image in NL_list[num_val_nl:num_test_nl]:
  57. test_list.append((image, 0))
  58. for image in NL_list[num_test_nl:]:
  59. train_list.append((image, 0))
  60. return train_list, val_list, test_list
  61. class CustomDataset(Dataset):
  62. def __init__(self, mri, xls: pd.DataFrame):
  63. self.mri_data = mri # DATA IS A LIST WITH TUPLES (image_dir, class_id)
  64. self.xls_data = xls
  65. def __len__(self):
  66. return len(self.mri_data)
  67. def _xls_to_tensor(self, xls_data: pd.Series):
  68. #Get used data
  69. #data = xls_data.loc[['Sex', 'Age (current)', 'PTID', 'DXCONFID (1=uncertain, 2= mild, 3= moderate, 4=high confidence)', 'Alz_csf']]
  70. data = xls_data.loc[['Sex', 'Age (current)']]
  71. data.replace({'M': 0, 'F': 1}, inplace=True)
  72. #Convert to tensor
  73. xls_tensor = torch.tensor(data.values.astype(float))
  74. return xls_tensor
  75. def __getitem__(self, idx): # RETURNS TUPLE WITH IMAGE AND CLASS_ID, BASED ON INDEX IDX
  76. mri_path, class_id = self.mri_data[idx]
  77. mri = nib.load(mri_path)
  78. mri_data = mri.get_fdata()
  79. xls = self.xls_data.iloc[idx]
  80. #Convert xls data to tensor
  81. xls_tensor = self._xls_to_tensor(xls)
  82. mri_tensor = torch.from_numpy(mri_data).unsqueeze(0)
  83. class_id = torch.tensor([class_id])
  84. #Convert to one-hot and squeeze
  85. class_id = torch.nn.functional.one_hot(class_id, num_classes=2).squeeze(0)
  86. return mri_tensor, xls_tensor, class_id