main.py 4.9 KB

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