main.py 5.1 KB

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