CNN.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import torch
  2. # import talos
  3. from torch import device, cuda, cat, stack
  4. import torch.nn as nn
  5. import utils.CNN_Layers as CustomLayers
  6. class CNN_Net(nn.Module): # , talos.utils.TorchHistory):
  7. def __init__(self, prps, final_layer_size=5):
  8. super(CNN_Net, self).__init__()
  9. self.final_layer_size = final_layer_size
  10. self.device = device('cuda:0' if cuda.is_available() else 'cpu')
  11. print("CNN Initialized. Using: " + str(self.device))
  12. # LAYERS
  13. print(f"CNN Model Initialization")
  14. self.conv1 = CustomLayers.Conv_elu_maxpool_drop(1, 192, (11, 13, 11), stride=(4,4,4), pool=True, prps=prps)
  15. self.conv2 = CustomLayers.Conv_elu_maxpool_drop(192, 384, (5, 6, 5), stride=(1,1,1), pool=True, prps=prps)
  16. self.conv3_mid_flow = CustomLayers.Mid_flow(384, 384, prps=prps)
  17. self.conv4_sepConv = CustomLayers.Conv_elu_maxpool_drop(384, 96,(3, 4, 3), stride=(1,1,1), pool=True, prps=prps,
  18. sep_conv=True)
  19. self.conv5_sepConv = CustomLayers.Conv_elu_maxpool_drop(96, 48, (3, 4, 3), stride=(1, 1, 1), pool=True,
  20. prps=prps, sep_conv=True)
  21. self.fc1 = CustomLayers.Fc_elu_drop(113568, 10, prps=prps, softmax=False) # TODO, concatenate clinical data after this
  22. self.fc2 = CustomLayers.Fc_elu_drop(20, final_layer_size, prps=prps, softmax=True) # For now this works as output layer, though may be incorrect
  23. self.fc_clinical1 = CustomLayers.Fc_elu_drop(2, 30, prps=prps, softmax=False)
  24. self.fc_clinical2 = CustomLayers.Fc_elu_drop(30,10, prps=prps, softmax=False)
  25. # FORWARDS
  26. def forward(self, x):
  27. clinical_data = x[1].to(torch.float32)
  28. x = x[0]
  29. x = self.conv1(x)
  30. x = self.conv2(x)
  31. x = self.conv3_mid_flow(x)
  32. x = self.conv4_sepConv(x)
  33. x = self.conv5_sepConv(x)
  34. # FLATTEN x
  35. flatten_size = x.size(1) * x.size(2) * x.size(3) * x.size(4)
  36. x = x.view(-1, flatten_size)
  37. x = self.fc1(x)
  38. # Clinical
  39. clinical_data = torch.transpose(clinical_data, 0, 1)
  40. clinical_data = self.fc_clinical1(clinical_data)
  41. clinical_data = self.fc_clinical2(clinical_data)
  42. x = cat((x, clinical_data), dim=1)
  43. x = self.fc2(x)
  44. return x