modelAn_EEG_2024_02_14.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. # Second-level deep neural network
  2. # Version 1 12-05-2022, GV Anguelova
  3. # 05-02-2023: aanpassing splitsing train en test set, zodat het aparte EEG's zijn; tevens wegingsfactor aangepast
  4. # 12-02-2023: complexer maken model met extra hidden layer: model.add(Dense(50, activation='relu'))
  5. # 20-02-2023: complexer maken model met extra Conv2D layer: model.add(Conv2D(25, (3, 3), activation='relu')), met zeropadding, maxpooling en droput
  6. #Import libraries
  7. import numpy
  8. import numpy as np
  9. import tensorflow as tf
  10. import scipy.io as sio
  11. import time
  12. import os
  13. from keras.models import Sequential
  14. from keras.layers import Dense
  15. from keras.layers import Dropout
  16. from keras.layers import Flatten
  17. from keras.constraints import maxnorm
  18. from tensorflow.keras.optimizers import SGD
  19. from keras.layers.convolutional import Conv2D
  20. from keras.layers.convolutional import MaxPooling2D
  21. from keras.utils import np_utils
  22. from keras import backend as K
  23. K.set_image_data_format('channels_last')
  24. from tensorflow.keras.layers import ZeroPadding2D
  25. from tensorflow.keras.optimizers import Adam
  26. from sklearn.metrics import confusion_matrix
  27. from sklearn.metrics import classification_report
  28. from sklearn.utils import class_weight
  29. # Select EEG directories
  30. BaseDir = '/Users/galiaanguelova/Downloads/tryout/' # directory of the EEG
  31. filename = 'Ambulatory_Epi' # EEG file
  32. EEGdir = (BaseDir + filename) # + "/Selectie/")
  33. #print(EEGdir)
  34. # fix random seed for reproducibility
  35. seed = 7
  36. numpy.random.seed(seed)
  37. # Load data: selected EEG epochs uit first-level deep neural network
  38. EEGfile = os.path.join(EEGdir, 'train_test_1483_2023_02_05')
  39. EEGdata = sio.loadmat(EEGfile)
  40. EEG_input_train = EEGdata['seizureLocation_selectie_input_train_2023_02_05'] # name variable uit matlab
  41. EEG_input_test = EEGdata['seizureLocation_selectie_input_test_2023_02_05'] # name variable uit matlab
  42. EEG_output_file = os.path.join(EEGdir, 'train_test_1483_2023_02_05')
  43. EEG_output_data = sio.loadmat(EEG_output_file)
  44. EEG_output_train = EEG_output_data['EEG_output_train_2023_02_05']
  45. EEG_output_test = EEG_output_data['EEG_output_test_2023_02_05']
  46. # Reshape input variable
  47. EEG_input_train_reshaped = EEG_input_train.reshape(EEG_input_train.shape[0], EEG_input_train.shape[1], EEG_input_train.shape[2], -1).astype('float32')
  48. EEG_input_test_reshaped = EEG_input_test.reshape(EEG_input_test.shape[0], EEG_input_test.shape[1], EEG_input_test.shape[2], -1).astype('float32')
  49. input_dim = (EEG_input_train.shape[1], EEG_input_train.shape[2], 1) # (250, 18, 1)
  50. # Weight factor
  51. EEG_output_train_cat = np_utils.to_categorical(EEG_output_train)
  52. weight_epil = 2493/1136
  53. class_weight = {0: 1, 1: weight_epil}
  54. EEG_output_test_cat = np_utils.to_categorical(EEG_output_test)
  55. # Create model
  56. def baseline_model():
  57. model = Sequential()
  58. model.add(Conv2D(25, (3, 3), activation='relu', input_shape=input_dim, padding='same'))
  59. model.add(ZeroPadding2D(padding=1))
  60. model.add(MaxPooling2D(pool_size=(2, 2)))
  61. model.add(Dropout(0.2))
  62. ## model.add(Conv2D(25, (3, 3), activation='relu'))
  63. ## model.add(ZeroPadding2D(padding=1))
  64. ## model.add(MaxPooling2D(pool_size=(2, 2)))
  65. ## model.add(Dropout(0.2))
  66. model.add(Flatten())
  67. model.add(Dense(100, activation='relu'))
  68. #model.add(Dense(50, activation='relu'))
  69. model.add(Dense(2, activation='softmax'))
  70. # Compile model
  71. model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
  72. print(model.summary())
  73. return model
  74. # Evaluate model
  75. model = baseline_model()
  76. model.fit(EEG_input_train_reshaped, EEG_output_train_cat, validation_split=0.2, epochs=10, batch_size=50, class_weight=class_weight)
  77. scores = model.evaluate(EEG_input_train_reshaped, EEG_output_train_cat, verbose=0)
  78. print("Accuracy_train: %.2f%%" % (scores[1]*100))
  79. scores = model.evaluate(EEG_input_test_reshaped, EEG_output_test_cat, verbose=0)
  80. print("Accuracy_test: %.2f%%" % (scores[1]*100))
  81. # Save probabilities in mat-file
  82. EEG_pred = model.predict(EEG_input_test_reshaped)
  83. print(EEG_pred) # y_pred
  84. sio.savemat('Ambulatory_Epi/EEG_pred_2023_02_20_v2.mat', {'EEG_pred':EEG_pred}) # ! adjust name and date in file name
  85. # Create classification labels and adjust EEG_pred for calculation confusion matrix
  86. EEG_pred_afgerond = np.argmax(EEG_pred, axis=1)
  87. label = np.argmax(EEG_output_test_cat, axis=1)
  88. print(label) # y_true/y_test
  89. # Confusion matrix
  90. cm1 = confusion_matrix(label, EEG_pred_afgerond)
  91. print(cm1)
  92. # Confusion matrix, Accuracy, sensitivity and specificity
  93. total1=sum(sum(cm1))
  94. accuracy1=(cm1[0,0]+cm1[1,1])/total1
  95. print('Accuracy : ', accuracy1)
  96. sensitivity1 = cm1[0,0]/(cm1[0,0]+cm1[0,1])
  97. print('Sensitivity : ', sensitivity1)
  98. specificity1 = cm1[1,1]/(cm1[1,0]+cm1[1,1])
  99. print('Specificity : ', specificity1)