main.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. from symbol import parameters
  2. import torch
  3. # FOR DATA
  4. from utils.preprocess import prepare_datasets
  5. from utils.train_methods import train, load, evaluate, predict
  6. from utils.CNN import CNN_Net
  7. from torch.utils.data import DataLoader
  8. from torchvision import datasets
  9. from sklearn.model_selection import KFold
  10. # GENERAL PURPOSE
  11. import pandas as pd
  12. import numpy as np
  13. import matplotlib.pyplot as plt
  14. import platform
  15. import time
  16. current_time = time.localtime()
  17. # INTERPRETABILITY
  18. from captum.attr import GuidedGradCam
  19. print(time.strftime("%Y-%m-%d_%H:%M", current_time))
  20. print("--- RUNNING ---")
  21. print("Pytorch Version: " + torch. __version__)
  22. print("Python Version: " + platform.python_version())
  23. # LOADING DATA
  24. val_split = 0.2 # % of val and test, rest will be train
  25. seed = 12 # TODO Randomize seed
  26. properties = {
  27. "batch_size":32,
  28. "padding":0,
  29. "dilation":1,
  30. "groups":1,
  31. "bias":True,
  32. "padding_mode":"zeros",
  33. "drop_rate":0,
  34. "epochs": 20,
  35. "lr": [1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6], # Unused
  36. 'momentum':[0.99, 0.97, 0.95, 0.9], # Unused
  37. 'weight_decay':[1e-3, 1e-4, 1e-5, 0] # Unused
  38. }
  39. roc = True # If True, will make ROC curve
  40. model_filepath = '/data/data_wnx1/rschuurs/Pytorch_CNN-RNN' # TODO, MUST UPDATE BEFORE RUNNING!
  41. CNN_filepath = '/data/data_wnx1/rschuurs/Pytorch_CNN-RNN/cnn_net.pth' # cnn_net.pth
  42. # small dataset
  43. # mri_datapath = '/data/data_wnx1/rschuurs/Pytorch_CNN-RNN/PET_volumes_customtemplate_float32/' # Small Test
  44. # big dataset
  45. mri_datapath = '/data/data_wnx1/_Data/AlzheimersDL/CNN+RNN-2class-1cnn+data/PET_volumes_customtemplate_float32/' # Real data
  46. csv_datapath = 'LP_ADNIMERGE.csv'
  47. # annotations_file = pd.read_csv(annotations_datapath) # DataFrame
  48. # show_image(17508)
  49. # Datasets include multiple labels, such as medical info
  50. training_data, val_data, test_data = prepare_datasets(mri_datapath, csv_datapath, val_split, seed)
  51. # Create data loaders
  52. train_dataloader = DataLoader(training_data, batch_size=properties['batch_size'], shuffle=True, drop_last=True)
  53. val_dataloader = DataLoader(val_data, batch_size=properties['batch_size'], shuffle=True) # Used during training
  54. test_dataloader = DataLoader(test_data, batch_size=properties['batch_size'], shuffle=True) # Used at end for graphs
  55. # loads a few images to test
  56. x = 0
  57. while x < 1:
  58. train_features, train_labels = next(iter(train_dataloader))
  59. # print(f"Feature batch shape: {train_features.size()}")
  60. img = train_features[0].squeeze()
  61. print(f"Feature batch shape: {img.size()}")
  62. image = img[:, :, 40]
  63. print(f"Feature batch shape: {image.size()}")
  64. label = train_labels[0]
  65. print(f"Label: {label}")
  66. plt.imshow(image, cmap="gray")
  67. # plt.savefig(f"./Image{x}_IS:{label}.png")
  68. plt.show()
  69. x = x+1
  70. CNN = CNN_Net(prps=properties, final_layer_size=2)
  71. CNN.cuda()
  72. # UNCOMMENT THE METHODS TO BE PERFORMED
  73. # train(CNN, train_dataloader, val_dataloader, CNN_filepath, properties, graphs=True)
  74. load(CNN, CNN_filepath)
  75. # evaluate(CNN, test_dataloader)
  76. # predict(CNN, test_dataloader)
  77. print(CNN)
  78. CNN.eval()
  79. # EXTRA TESTS AND IMPLEMENTATION ATTEMPTS, CAN BE IGNORED
  80. # # PREDICT MODE TO TEST INDIVIDUAL IMAGES
  81. # if(predict):
  82. # on = True
  83. # print("---- Predict mode ----")
  84. # print("Integer for image")
  85. # print("x or X for exit")
  86. #
  87. # while(on):
  88. # inp = input("Next image: ")
  89. # if(inp == None or inp.lower() == 'x' or not inp.isdigit()): on = False
  90. # else:
  91. # dataloader = DataLoader(prepare_predict(mri_datapath, [inp]), batch_size=params['batch_size'], shuffle=True)
  92. # prediction = CNN.predict(dataloader)
  93. #
  94. # features, labels = next(iter(dataloader), )
  95. # img = features[0].squeeze()
  96. # image = img[:, :, 40]
  97. # print(f"Expected class: {labels}")
  98. # print(f"Prediction: {prediction}")
  99. # plt.imshow(image, cmap="gray")
  100. # plt.show()
  101. #
  102. # print("--- END ---")
  103. # params = {
  104. # "target_rows": 91,
  105. # "target_cols": 109,
  106. # "depth": 91,
  107. # "axis": 1,
  108. # "num_clinical": 2,
  109. # "CNN_drop_rate": 0.3,
  110. # "RNN_drop_rate": 0.1,
  111. # # "CNN_w_regularizer": regularizers.l2(2e-2),
  112. # # "RNN_w_regularizer": regularizers.l2(1e-6),
  113. # "CNN_batch_size": 10,
  114. # "RNN_batch_size": 5,
  115. # "val_split": 0.2,
  116. # "final_layer_size": 5
  117. # }
  118. '''
  119. params_dict = { 'CNN_w_regularizer': CNN_w_regularizer, 'RNN_w_regularizer': RNN_w_regularizer,
  120. 'CNN_batch_size': CNN_batch_size, 'RNN_batch_size': RNN_batch_size,
  121. 'CNN_drop_rate': CNN_drop_rate, 'epochs': 30,
  122. 'gpu': "/gpu:0", 'model_filepath': model_filepath,
  123. 'image_shape': (target_rows, target_cols, depth, axis),
  124. 'num_clinical': num_clinical,
  125. 'final_layer_size': final_layer_size,
  126. 'optimizer': optimizer, 'RNN_drop_rate': RNN_drop_rate,}
  127. params = Parameters(params_dict)
  128. # WHAT WAS THIS AGAIN?
  129. seeds = [np.random.randint(1, 5000) for _ in range(1)]
  130. # READ THIS TO UNDERSTAND TRAIN VS VALIDATION DATA
  131. def evaluate_net (seed):
  132. n_classes = 2
  133. data_loader = DataLoader((target_rows, target_cols, depth, axis), seed = seed)
  134. train_data, val_data, test_data,rnn_HdataT1,rnn_HdataT2,rnn_HdataT3,rnn_AdataT1,rnn_AdataT2,rnn_AdataT3, test_mri_nonorm = data_loader.get_train_val_test(val_split, mri_datapath)
  135. print('Length Val Data[0]: ',len(val_data[0]))
  136. '''
  137. # Failed attempt, to be ignored
  138. # guided_gc = GuidedGradCam(CNN, CNN.conv5_sepConv) # Performed on LAST convolution layer
  139. # input = torch.randn(1, 1, 91, 109, 91, requires_grad=True).cuda()
  140. # train_features, train_labels = next(iter(train_dataloader))
  141. # while(train_labels[0] == 0):
  142. # train_features, train_labels = next(iter(train_dataloader))
  143. # attr = guided_gc.attribute(train_features.cuda(), 0) #, interpolate_mode="area")
  144. # # draw the attributes
  145. # attr = attr.unsqueeze(0)
  146. # attr = attr.cpu().detach().numpy()
  147. # attr = np.clip(attr, 0, 1)
  148. # plt.imshow(attr)
  149. # plt.show()
  150. # print("Done w/ attributions")
  151. # print(attr)