123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- # Second-level deep neural network
- # Version 1 12-05-2022, GV Anguelova
- # 05-02-2023: aanpassing splitsing train en test set, zodat het aparte EEG's zijn; tevens wegingsfactor aangepast
- # 12-02-2023: complexer maken model met extra hidden layer: model.add(Dense(50, activation='relu'))
- # 20-02-2023: complexer maken model met extra Conv2D layer: model.add(Conv2D(25, (3, 3), activation='relu')), met zeropadding, maxpooling en droput
- #Import libraries
- import numpy
- import numpy as np
- import tensorflow as tf
- import scipy.io as sio
- import time
- import os
- from keras.models import Sequential
- from keras.layers import Dense
- from keras.layers import Dropout
- from keras.layers import Flatten
- from keras.constraints import maxnorm
- from tensorflow.keras.optimizers import SGD
- from keras.layers.convolutional import Conv2D
- from keras.layers.convolutional import MaxPooling2D
- from keras.utils import np_utils
- from keras import backend as K
- K.set_image_data_format('channels_last')
- from tensorflow.keras.layers import ZeroPadding2D
- from tensorflow.keras.optimizers import Adam
- from sklearn.metrics import confusion_matrix
- from sklearn.metrics import classification_report
- from sklearn.utils import class_weight
- # Select EEG directories
- BaseDir = '/Users/galiaanguelova/Downloads/tryout/' # directory of the EEG
- filename = 'Ambulatory_Epi' # EEG file
- EEGdir = (BaseDir + filename) # + "/Selectie/")
- #print(EEGdir)
- # fix random seed for reproducibility
- seed = 7
- numpy.random.seed(seed)
- # Load data: selected EEG epochs uit first-level deep neural network
- EEGfile = os.path.join(EEGdir, 'train_test_1483_2023_02_05')
- EEGdata = sio.loadmat(EEGfile)
- EEG_input_train = EEGdata['seizureLocation_selectie_input_train_2023_02_05'] # name variable uit matlab
- EEG_input_test = EEGdata['seizureLocation_selectie_input_test_2023_02_05'] # name variable uit matlab
- EEG_output_file = os.path.join(EEGdir, 'train_test_1483_2023_02_05')
- EEG_output_data = sio.loadmat(EEG_output_file)
- EEG_output_train = EEG_output_data['EEG_output_train_2023_02_05']
- EEG_output_test = EEG_output_data['EEG_output_test_2023_02_05']
- # Reshape input variable
- 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')
- 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')
- input_dim = (EEG_input_train.shape[1], EEG_input_train.shape[2], 1) # (250, 18, 1)
- # Weight factor
- EEG_output_train_cat = np_utils.to_categorical(EEG_output_train)
- weight_epil = 2493/1136
- class_weight = {0: 1, 1: weight_epil}
- EEG_output_test_cat = np_utils.to_categorical(EEG_output_test)
- # Create model
- def baseline_model():
- model = Sequential()
- model.add(Conv2D(25, (3, 3), activation='relu', input_shape=input_dim, padding='same'))
- model.add(ZeroPadding2D(padding=1))
- model.add(MaxPooling2D(pool_size=(2, 2)))
- model.add(Dropout(0.2))
- ## model.add(Conv2D(25, (3, 3), activation='relu'))
- ## model.add(ZeroPadding2D(padding=1))
- ## model.add(MaxPooling2D(pool_size=(2, 2)))
- ## model.add(Dropout(0.2))
- model.add(Flatten())
- model.add(Dense(100, activation='relu'))
- #model.add(Dense(50, activation='relu'))
- model.add(Dense(2, activation='softmax'))
- # Compile model
- model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
- print(model.summary())
- return model
- # Evaluate model
- model = baseline_model()
- model.fit(EEG_input_train_reshaped, EEG_output_train_cat, validation_split=0.2, epochs=10, batch_size=50, class_weight=class_weight)
- scores = model.evaluate(EEG_input_train_reshaped, EEG_output_train_cat, verbose=0)
- print("Accuracy_train: %.2f%%" % (scores[1]*100))
- scores = model.evaluate(EEG_input_test_reshaped, EEG_output_test_cat, verbose=0)
- print("Accuracy_test: %.2f%%" % (scores[1]*100))
- # Save probabilities in mat-file
- EEG_pred = model.predict(EEG_input_test_reshaped)
- print(EEG_pred) # y_pred
- sio.savemat('Ambulatory_Epi/EEG_pred_2023_02_20_v2.mat', {'EEG_pred':EEG_pred}) # ! adjust name and date in file name
- # Create classification labels and adjust EEG_pred for calculation confusion matrix
- EEG_pred_afgerond = np.argmax(EEG_pred, axis=1)
- label = np.argmax(EEG_output_test_cat, axis=1)
- print(label) # y_true/y_test
- # Confusion matrix
- cm1 = confusion_matrix(label, EEG_pred_afgerond)
- print(cm1)
- # Confusion matrix, Accuracy, sensitivity and specificity
- total1=sum(sum(cm1))
- accuracy1=(cm1[0,0]+cm1[1,1])/total1
- print('Accuracy : ', accuracy1)
- sensitivity1 = cm1[0,0]/(cm1[0,0]+cm1[0,1])
- print('Sensitivity : ', sensitivity1)
- specificity1 = cm1[1,1]/(cm1[1,0]+cm1[1,1])
- print('Specificity : ', specificity1)
|