main.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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. model_filepath = '/data/data_wnx1/rschuurs/Pytorch_CNN-RNN'
  40. CNN_filepath = '/data/data_wnx1/rschuurs/Pytorch_CNN-RNN/cnn_net.pth' # cnn_net.pth
  41. # small dataset
  42. # mri_datapath = '/data/data_wnx1/rschuurs/Pytorch_CNN-RNN/PET_volumes_customtemplate_float32/' # Small Test
  43. # big dataset
  44. mri_datapath = '/data/data_wnx1/_Data/AlzheimersDL/CNN+RNN-2class-1cnn+data/PET_volumes_customtemplate_float32/' # Real data
  45. csv_datapath = 'LP_ADNIMERGE.csv'
  46. # annotations_file = pd.read_csv(annotations_datapath) # DataFrame
  47. # show_image(17508)
  48. # TODO: Datasets include multiple labels, such as medical info
  49. training_data, val_data, test_data = prepare_datasets(mri_datapath, csv_datapath, val_split, seed)
  50. # Create data loaders
  51. train_dataloader = DataLoader(training_data, batch_size=properties['batch_size'], shuffle=True, drop_last=True)
  52. val_dataloader = DataLoader(val_data, batch_size=properties['batch_size'], shuffle=True) # Used during training
  53. test_dataloader = DataLoader(test_data, batch_size=properties['batch_size'], shuffle=True) # Used at end for graphs
  54. # loads a few images to test
  55. x = 0
  56. while x < 0:
  57. train_features, train_labels = next(iter(train_dataloader))
  58. # print(f"Feature batch shape: {train_features.size()}")
  59. img = train_features[0].squeeze()
  60. print(f"Feature batch shape: {img.size()}")
  61. image = img[:, :, 40]
  62. print(f"Feature batch shape: {image.size()}")
  63. label = train_labels[0]
  64. print(f"Label: {label}")
  65. plt.imshow(image, cmap="gray")
  66. # plt.savefig(f"./Image{x}_IS:{label}.png")
  67. plt.show()
  68. x = x+1
  69. roc = True
  70. CNN = CNN_Net(prps=properties, final_layer_size=2)
  71. CNN.cuda()
  72. # train(CNN, train_dataloader, val_dataloader, CNN_filepath, properties, graphs=True)
  73. load(CNN, CNN_filepath)
  74. # evaluate(CNN, test_dataloader)
  75. # predict(CNN, test_dataloader)
  76. print(CNN)
  77. CNN.eval()
  78. guided_gc = GuidedGradCam(CNN, CNN.conv5_sepConv) # Performed on LAST convolution layer
  79. # input = torch.randn(1, 1, 91, 109, 91, requires_grad=True).cuda()
  80. # TODO MAKE BATCH SIZE 1 FOR THIS TO WORK??
  81. train_features, train_labels = next(iter(train_dataloader))
  82. while(train_labels[0] == 0):
  83. train_features, train_labels = next(iter(train_dataloader))
  84. attr = guided_gc.attribute(train_features.cuda(), 0) #, interpolate_mode="area")
  85. # draw the attributes
  86. attr = attr.unsqueeze(0)
  87. attr = attr.cpu().detach().numpy()
  88. attr = np.clip(attr, 0, 1)
  89. plt.imshow(attr)
  90. plt.show()
  91. print("Done w/ attributions")
  92. print(attr)
  93. # EXTRA
  94. # # PREDICT MODE TO TEST INDIVIDUAL IMAGES
  95. # if(predict):
  96. # on = True
  97. # print("---- Predict mode ----")
  98. # print("Integer for image")
  99. # print("x or X for exit")
  100. #
  101. # while(on):
  102. # inp = input("Next image: ")
  103. # if(inp == None or inp.lower() == 'x' or not inp.isdigit()): on = False
  104. # else:
  105. # dataloader = DataLoader(prepare_predict(mri_datapath, [inp]), batch_size=params['batch_size'], shuffle=True)
  106. # prediction = CNN.predict(dataloader)
  107. #
  108. # features, labels = next(iter(dataloader), )
  109. # img = features[0].squeeze()
  110. # image = img[:, :, 40]
  111. # print(f"Expected class: {labels}")
  112. # print(f"Prediction: {prediction}")
  113. # plt.imshow(image, cmap="gray")
  114. # plt.show()
  115. #
  116. # print("--- END ---")
  117. # params = {
  118. # "target_rows": 91,
  119. # "target_cols": 109,
  120. # "depth": 91,
  121. # "axis": 1,
  122. # "num_clinical": 2,
  123. # "CNN_drop_rate": 0.3,
  124. # "RNN_drop_rate": 0.1,
  125. # # "CNN_w_regularizer": regularizers.l2(2e-2),
  126. # # "RNN_w_regularizer": regularizers.l2(1e-6),
  127. # "CNN_batch_size": 10,
  128. # "RNN_batch_size": 5,
  129. # "val_split": 0.2,
  130. # "final_layer_size": 5
  131. # }
  132. '''
  133. params_dict = { 'CNN_w_regularizer': CNN_w_regularizer, 'RNN_w_regularizer': RNN_w_regularizer,
  134. 'CNN_batch_size': CNN_batch_size, 'RNN_batch_size': RNN_batch_size,
  135. 'CNN_drop_rate': CNN_drop_rate, 'epochs': 30,
  136. 'gpu': "/gpu:0", 'model_filepath': model_filepath,
  137. 'image_shape': (target_rows, target_cols, depth, axis),
  138. 'num_clinical': num_clinical,
  139. 'final_layer_size': final_layer_size,
  140. 'optimizer': optimizer, 'RNN_drop_rate': RNN_drop_rate,}
  141. params = Parameters(params_dict)
  142. # WHAT WAS THIS AGAIN?
  143. seeds = [np.random.randint(1, 5000) for _ in range(1)]
  144. # READ THIS TO UNDERSTAND TRAIN VS VALIDATION DATA
  145. def evaluate_net (seed):
  146. n_classes = 2
  147. data_loader = DataLoader((target_rows, target_cols, depth, axis), seed = seed)
  148. 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)
  149. print('Length Val Data[0]: ',len(val_data[0]))
  150. '''