본문 바로가기
Brain Engineering/MNE Python

Machine Learning : Group-Level Analysis (Part - 2) (3)

by goatlab 2022. 4. 5.
728x90
반응형
SMALL

Part - 2

 

모든 데이터는 모델을 구축하는 데 사용한다.

 
#Load and prepare dataset
data_folder = '../../study1/study1_eeg/epochdata/'
files = [data_folder+f for f in listdir(data_folder) if isfile(join(data_folder, f)) and '.DS_Store' not in f]
ids = [int(f[-6:-4]) for f in files]

numberOfEpochs = np.zeros((len(ids), 3))
# Read the EEG epochs:
epochs_all_UN, epochs_all_UP, epochs_all_NP = [], [], []
for f in range(len(files)):
    epochs = mne.read_epochs(files[f], verbose='error')
    epochs_UN = epochs['FU', 'FN']
    epochs_UP = epochs['FU', 'FP']
    epochs_NP = epochs['FN', 'FP']
    numberOfEpochs[f,0] = int(len(epochs_UN.events))
    numberOfEpochs[f,1] = int(len(epochs_UP.events))
    numberOfEpochs[f,2] = int(len(epochs_NP.events))
    UN, UP, NP = [ids[f]], [ids[f]], [ids[f]]
    UN.append(epochs_UN)
    UP.append(epochs_UP)
    NP.append(epochs_NP)
    epochs_all_UN.append(UN)
    epochs_all_UP.append(UP)
    epochs_all_NP.append(NP)

#print(numberOfEpochs)
epochs_all_UN = np.array(epochs_all_UN)
epochs_all_UP = np.array(epochs_all_UP)
epochs_all_NP = np.array(epochs_all_NP)

 

각 데이터 세트의 데이터, 레이블 및 ID를 구분하는 함수를 정의한다.

 

def getData_labels(epochs):
    data, labels, ids = [], [], []
    for p in epochs:
        tmp_epoch = p[1]
        tmp_labels = tmp_epoch.events[:,-1]
        labels.extend(tmp_labels)
        tmp_id = p[0]
        ids.extend([tmp_id]*len(tmp_labels))
        data.extend(tmp_epoch.get_data())
        
    data = np.array(data)
    labels = np.array(labels)
    ids = np.array(ids)
    return data, labels, ids
 

Example : Classification between Unpleasant and Neutral Events

 

data_UN, labels_UN, ids_UN = getData_labels(epochs_all_UN)

 

1부에서 했던 것처럼 LDA와 로지스틱 회귀 모델을 만든다. 그러나 이번에는 총 2개의 모델만 있을 것이다.

 

#Linear Discriminant Analysis
clf_lda_pip = make_pipeline(Vectorizer(), StandardScaler(), LinearDiscriminantAnalysis(solver='svd'))
#Logistic Regression
clf_lr_pip = make_pipeline(Vectorizer(), StandardScaler(), LogisticRegression(penalty='l1', random_state=42))

models = [ clf_lr_pip, clf_lda_pip]
model_names = [ 'LR', 'LDA']
kfold = StratifiedKFold(n_splits=3, random_state=42)
results = applyCrossValidation(models, model_names, data_UN, labels_UN, kfold)

 

다음으로 각 모델에 대한 교차 검증 점수의 평균과 표준 편차를 계산한다.

 

mean_CVaccuracies, std_CVaccuracies = [], []
print('Results UP: {}'.format(results))
mean_CVaccuracies_UN, std_CVaccuracies_UN = [], []
for i in range(len(results)):
    mean_CVaccuracies_UN.append(statistics.mean(results[i]))
    std_CVaccuracies_UN.append(statistics.stdev(results[i]))
print('Mean cv accuracies UP: {}'.format(mean_CVaccuracies_UN))
print('Std cv accuracies UP: {}'.format(std_CVaccuracies_UN))
print('\n')
mean_CVaccuracies.append(mean_CVaccuracies_UN)
std_CVaccuracies.append(std_CVaccuracies_UN)
print('Mean cv accuracies: {}'.format(mean_CVaccuracies))
print('Std cv accuracies: {}'.format(std_CVaccuracies))
Results UP: [array([0.50332284, 0.4926522 , 0.53918824]), array([0.50052466, 0.50174948, 0.52274318])]
Mean cv accuracies UP: [0.5117210960065134, 0.5083391037253356]
Std cv accuracies UP: [0.024378243617145648, 0.012489317029433022]

Mean cv accuracies: [[0.5117210960065134, 0.5083391037253356]]
Std cv accuracies: [[0.024378243617145648, 0.012489317029433022]]

 

상자 그림은 주어진 데이터 세트가 데이터의 평균 주위에 어떻게 분포되어 있는지 보여주고 이상값을 강조 표시한다.

 

import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline

def plotModelComparison(results, model_names):
    fig = plt.figure()
    fig.suptitle('Model Comparison')
    ax = fig.add_subplot(111)
    plt.boxplot(results)
    ax.set_xticklabels(model_names)
    plt.show()
    
plotModelComparison(results, model_names)

 

eeg 데이터의 그룹 수준 분석의 일부로 LR 및 LDA는 단일 참가자 분석에서와 같이 생성 되지만, 이번에는 그룹 수준에서 가지고 있는 많은 양의 데이터를 감안할 때 계산하는 데 몇 시간이 필요하기 때문에 SVM은 생략된다.

위의 상자 그림은 불쾌하고 중립적인 이벤트를 분류하는 작업에 대한 LDA 및 로지스틱 회귀 분석에 대한 교차 검증 점수의 분포를 보여준다. Unpleasant와 Neutral 이벤트를 분류하는 동안 두 모델 모두 약 50%의 정확도를 보인다. 이것은 모든 참가자를 함께 고려하는 것이 좋은 결과를 제공하지 않는다는 결론에 이르게 합니다. 가능한 이유는 참가자 간의 차이일 수 있다.

 

https://neuro.inf.unibe.ch/AlgorithmsNeuroscience/Tutorial_files/ApplyingMachineLearningMethods_2.html

 

Group-Level Analysis

Group-Level Analysis Tutorial #5: Applying Machine Learning Methods to EEG Data on Group Level In this tutorial, we are performing the same classi...

neuro.inf.unibe.ch

 

728x90
반응형
LIST