You are on page 1of 49

EEG 数据的特征主要有三种:时域特征、频域特征与空域特

征,不同的特征需要采取不同的特征提取方法,如空域特
征一般采用空域滤波器(共同空间模式,CSP)进行提取,频域
特 征 一 般 采 用 傅 立 叶 变 换 、 小 波 变 换 或 自 回 归 (Auto-
Regressive, AR)模型获取。
共空间模式(CSP): 一种对两分类任务下的空域滤波特

征提取算法,能够从多通道的脑机接口数据里面提取出每
一类的空间分布成分。
共空间模式算法的基本原理: 利用矩阵的对角化,找到一
组最优空间滤波器进行投影,使得两类信号的方差值差异
最大化,从而得到具有较高区分度的特征向量。
共空间模式算法旨在: 设计空间滤波器使得两组脑电时空
信号矩阵滤波后,方差值差异最大化,从而得到具有较高
区分度的特征向量。用于下一步将特征向量送入分类器进
行分类。

CSP 算法目标就是要设计空间滤波器 F1 和 F2 得到空间因子


function CSPMatrix = learnCSP(EEGSignals,classLabels)

%Input:

%EEGSignals: the training EEG signals, composed of 2 classes.

These signals

%are a structure such that:

% EEGSignals.x: the EEG signals as a [Ns * Nc * Nt] Matrix

where

% Ns: number of EEG samples per trial

% Nc: number of channels (EEG electrodes)

% nT: number of trials

% EEGSignals.y: a [1 * Nt] vector containing the class labels for

each trial
% EEGSignals.s: the sampling frequency (in Hz)

%Output:

%CSPMatrix: the learnt CSP filters (a [Nc*Nc] matrix with the

filters as rows)

%See also: extractCSPFeatures

%check and initializations

nbChannels = size(EEGSignals.x,2); % 通道

nbTrials = size(EEGSignals.x,3); % 实验次数

nbClasses = length(classLabels); % 类别
if nbClasses ~= 2

disp('ERROR! CSP can only be used for two classes');

return;

end

covMatrices = cell(nbClasses,1); %the covariance matrices for

each class

%% Computing the normalized covariance matrices for each

trial

%% 为每个试验计算标准化的协方差矩阵。

trialCov = zeros(nbChannels,nbChannels,nbTrials);

for t=1:nbTrials
E = EEGSignals.x(:,:,t)'; %note the transpose

EE = E * E';

trialCov(:,:,t) = EE ./ trace(EE);

end

clear E;

clear EE;

%computing the covariance matrix for each class

for c=1:nbClasses

%EEGSignals.y==classLabels(c) returns the indeces

corresponding to the class labels

covMatrices{c} = mean(trialCov(:,:,EEGSignals.y ==

classLabels(c)),3);
end

%the total covariance matrix

covTotal = covMatrices{1} + covMatrices{2};

%whitening transform of total covariance matrix

%caution: the eigenvalues are initially in increasing order 注意:

特征值最初是递增的

[Ut Dt] = eig(covTotal);

eigenvalues = diag(Dt);

[eigenvalues egIndex] = sort(eigenvalues, 'descend');

Ut = Ut(:,egIndex);

P = diag(sqrt(1./eigenvalues)) * Ut';
%transforming covariance matrix of first class using P

%用 P 变换第一类协方差矩阵

transformedCov1 = P * covMatrices{1} * P';

%EVD of the transformed covariance matrix 变换协方差矩阵的

EVD

[U1 D1] = eig(transformedCov1);

eigenvalues = diag(D1);

[eigenvalues egIndex] = sort(eigenvalues, 'descend');

U1 = U1(:, egIndex);

CSPMatrix = U1' * P;

function features = extractCSP(EEGSignals, CSPMatrix,


nbFilterPairs)

%extract features from an EEG data set using the Common

Spatial Patterns (CSP) algorithm

%Input:

%EEGSignals: the EEGSignals from which extracting the CSP

features. These signals

%are a structure such that:

% EEGSignals.x: the EEG signals as a [Ns * Nc * Nt] Matrix

where

% Ns: number of EEG samples per trial

% Nc: number of channels (EEG electrodes)


% nT: number of trials

% EEGSignals.y: a [1 * Nt] vector containing the class labels for

each trial

% EEGSignals.s: the sampling frequency (in Hz)

%CSPMatrix: the CSP projection matrix, learnt previously (see

function learnCSP)

%nbFilterPairs: number of pairs of CSP filters to be used. The

number of

% features extracted will be twice the value of this parameter.

The

% filters selected are the one corresponding to the lowest and

highest
% eigenvalues

%Output:

%features: the features extracted from this EEG data set

% as a [Nt * (nbFilterPairs*2 + 1)] matrix, with the class labels

as the

% last column

%initializations

nbTrials = size(EEGSignals.x,3);

features = zeros(nbTrials, 2*nbFilterPairs+1);

Filter = CSPMatrix([1:nbFilterPairs (end-nbFilterPairs+1):end],:);


%extracting the CSP features from each trial

for t=1:nbTrials

%projecting the data onto the CSP filters

projectedTrial = Filter * EEGSignals.x(:,:,t)';

%generating the features as the log variance of the

projectedsignals

variances = var(projectedTrial,0,2);

for f=1:length(variances)

features(t,f) = log(1+variances(f));

end
end

% Extract Common Spatial Pattern (CSP) Feature


close all; clear; clc;

load dataset_BCIcomp1.mat

EEGSignals.x=x_train;
EEGSignals.y=y_train;
Y=y_train;

classLabels = unique(EEGSignals.y);
CSPMatrix = learnCSP(EEGSignals,classLabels);
nbFilterPairs = 1;

X = extractCSP(EEGSignals, CSPMatrix, nbFilterPairs);


EEGSignals.x=x_test;
T = extractCSP(EEGSignals, CSPMatrix, nbFilterPairs);

save dataCSP.mat X Y T
color_L = [0 102 255] ./ 255;
color_R = [255, 0, 102] ./ 255;

pos = find(Y==1);
plot(X(pos,1),X(pos,2),'x','Color',color_L,'LineWidth',2);

hold on
pos = find(Y==2);
plot(X(pos,1),X(pos,2),'o','Color',color_R,'LineWidth',2);

legend('Left Hand','Right Hand')


xlabel('C3','fontweight','bold')
ylabel('C4','fontweight','bold')

%%主函数(main):

clc;clear;

%% 读取数据并对数据预处理

Subjects = 9; %被试数
Fs = 250; %采样率
windowLength = 4; %单次采样时间
chanSelect = [8,10,12]; %通道选择 c3,c4,cz
totalFlt = [4 40]; %总的滤波频段选择

load rawdata1.mat
[Data_train,label_train] =
preProccess(Fs,windowLength,EEG,chanSelect,totalFlt);
%preProccess 执行数据提取、分段、滤波处理

load rawdata2.mat
[Data_test,label_test] =
preProccess(Fs,windowLength,EEG,chanSelect,totalFlt);

%% CSP 特征提取

EEGSignals.x = Data_train;
EEGSignals.y = label_train;
Y = label_train;

classLabels = unique(EEGSignals.y);
CSPMatrix = learnCSP(EEGSignals,classLabels);
nbFilterPairs = 1;
X = extractCSP(EEGSignals, CSPMatrix, nbFilterPairs);

EEGSignals_test.x=Data_test;
EEGSignals_test.y=label_test;
T = extractCSP(EEGSignals_test, CSPMatrix, nbFilterPairs);

save dataCSP.mat X Y T

color_L = [0 102 255] ./ 255;


color_R = [255, 0, 102] ./ 255;

pos = find(Y==1);
plot(X(pos,1),X(pos,2),'x','Color',color_L,'LineWidth',2);

hold on
pos = find(Y==2);
plot(X(pos,1),X(pos,2),'o','Color',color_R,'LineWidth',2);

legend('Left Hand','Right Hand')


xlabel('C3','fontweight','bold')
ylabel('C4','fontweight','bold')
%%CSP 算法:

function CSPMatrix = learnCSP(EEGSignals,classLabels)


%
%Input:
%EEGSignals: the training EEG signals, composed of 2 classes.
These signals
%are a structure such that:
% EEGSignals.x: the EEG signals as a [Ns * Nc * Nt] Matrix
where
% Ns: number of EEG samples per trial
% Nc: number of channels (EEG electrodes)
% nT: number of trials
% EEGSignals.y: a [1 * Nt] vector containing the class labels for
each trial
% EEGSignals.s: the sampling frequency (in Hz)
%
%Output:
%CSPMatrix: the learnt CSP filters (a [Nc*Nc] matrix with the
filters as rows)
%
%See also: extractCSPFeatures

%check and initializations


nbChannels = size(EEGSignals.x,2);
nbTrials = size(EEGSignals.x,3);
nbClasses = length(classLabels);

if nbClasses ~= 2
disp('ERROR! CSP can only be used for two classes');
return;
end

covMatrices = cell(nbClasses,1); %the covariance matrices for


each class

%% Computing the normalized covariance matrices for each


trial
trialCov = zeros(nbChannels,nbChannels,nbTrials);
for t=1:nbTrials
E = EEGSignals.x(:,:,t)'; %note the transpose
EE = E * E';
trialCov(:,:,t) = EE ./ trace(EE);
end
clear E;
clear EE;

%computing the covariance matrix for each class


for c=1:nbClasses
covMatrices{c} = mean(trialCov(:,:,EEGSignals.y ==
classLabels(c)),3); %EEGSignals.y==classLabels(c) returns the
indeces corresponding to the class labels
end

%the total covariance matrix


covTotal = covMatrices{1} + covMatrices{2};

%whitening transform of total covariance matrix


[Ut Dt] = eig(covTotal); %caution: the eigenvalues are initially in
increasing order
eigenvalues = diag(Dt);
[eigenvalues egIndex] = sort(eigenvalues, 'descend');
Ut = Ut(:,egIndex);
P = diag(sqrt(1./eigenvalues)) * Ut';
%transforming covariance matrix of first class using P
transformedCov1 = P * covMatrices{1} * P';

%EVD of the transformed covariance matrix


[U1 D1] = eig(transformedCov1);
eigenvalues = diag(D1);
[eigenvalues egIndex] = sort(eigenvalues, 'descend');
U1 = U1(:, egIndex);
CSPMatrix = U1' * P;
脑电数据 1 预处理
加载数据

绘制 2D 图

此时图像
重参考(平均参考)

滤波(0.5-45)
此时图像

跑 ica
去眼电
此时图像

分段 2 8 分段
叠加平均看 PZ,在 300 处

时频分析 看通道 17 的
横轴时间 纵轴频率

绘制 ERP 图像
脑电数据 2 预处理分析
加载数据

该数据集包含 154 个事件,共有两种类


型该实验中,有两种类型的事件"square" 和"rt"。“square“事件对应的是显显示器中绿色正
方形的外观,"rt"对应于受试者的反映时间的事件
1 数据预览
电压刻度调整至 50 微伏滚动时间窗口为 10s

调整通道数为 16 -----------------------------------------

\\
绘制脑电头皮图可视化通道位置(显示通道名 显示通道号)
绘制通道光谱图(采样 15%和 100%的效果图)

绘制所选通道的头皮位置(通道 1)
\\
滤波(下边缘频率 10hz,上边缘频率 50hz)

重新参考数据操作(平均参考)

选用平均参考
重参考及滤波后的图

提取数据 epoch
提取数据 epoch 移除基线值

在头皮图单轴绘制 ERP 数据

默认绘制 ERP 方差最大时刻的地形图,


本图在 289ms
在地形矩阵中绘制 ERP 轨迹
绘制一些列的 2D ERP scalp maps(输入需要的 epoch 延迟)

输入所需的延迟 0:100:500

绘制一些列的 3D ERP scalp maps


\\
选择 epoch 并绘制数据平均值
创建两种两种时间段,一半的目标刺激呈现在位置 1,另一半的目标刺激呈现在位置 2
4 5 指的是输入数据集的索引
绘制 ERP 图像(输入通道 27,输入 smoothing(平滑) 1 表示在临近的 epochs 进行平滑绘
图的时候,所取的值)

图中最上面的为电极的头皮位置,中间部分为 ERP 图,下面部分为电极的 ERP.


绘制平滑的 ERP(平滑宽度设置为 10)
对 ERP image 的 trial 进行排序
eeglab 默认按照 trial 在实验过程中出现的顺序排列。在 pop_erpimage.m 界面上点击 Epoch-
sorting field 按钮并选择 Latency,点击 Event type 选择 rt。并在 Event time range 输入-200
800 ms
在 pop_erpimage.m 界面上点击 Epoch-sorting field 按钮并选择 Latency,点击 Event type 选择
rt。并在 Event time range 输入-200 800 ms。Align 设置为 inf

\\
在 ERP 中按 Phase Value 对 Trials 进行排序
eeglab 默认按照 trial 在实验过程中出现的顺序排列。在 pop_erpimage.m 界面上,清除
Epoch-sorting field、Event type、Align 和 Event time range。在 Sort trials by phase section 中
Frequency 中输入 10(Hz),在 Window Center 输入 0
在 ERP 中按 Phase Value 对 Trials 进行排序
输入如下参数
上图的最上方子图的 ERP image。倒数第二个子图是 ERSP(Event Related Spectral Power),
表示的是功率的平均变化(单位为 dB)。在这个子图中,曲线没有超出蓝色区域,表示在
选择的频率 10.13Hz(见右下角)相对基线水平(25.93dB),功率没有显著变化。最下方
的子图的 ITC。它表示的相对刺激呈现而言,相位同步化的程度。10.13Hz 表示选择分析的
频段。可以看出在 300Hz 附近相位同步化显著增强

Eeglab 默认按照 trial 在实验过程中出现的顺序排列


\\
ICA 分解数据
Run ica
绘制 2-D Component Scalp Maps(绘制 1:12 个独立成分)

绘制 Component headplots(1:12)
学习和删除 ICA 组件

绘制 component spectra and maps

估计独立成分的贡献,假设考察 27 号
绘制独立成分 ERPs

\\
绘制独立成分 ERP 贡献

上图中黑色包络线是各个时间点的所有 channel 的最大值和最小值,彩线是各个独立成分


的的 ERP。如果只想要了解对 200-500ms 数据 ERP 贡献最大的独立成分,可进行下列操作
绘制 Component ERP-image
\\
Decomposing channel data
为了检测 ERSP(event-related spectral perturbation)和 ITC(inter-trial coherence
得到的结果分为两个子图,上方是 ERSP 子图,下方是 ITC 子图。
ERSP 子图:该子图左方的 panel 是基线的平均功率谱,而各个时间点的 ERSP 包络线。而
top image 是相对基线,每个时间点、每个频率的频谱功率改变(event-related changes in
spectral power (from pre-stimulus baseline) at each time during the epoch and at each frequency
(< 50 Hz))。
ITC 子图:A significant ITC indicates that the EEG activity at a given time and frequency in single
trials becomes phase-locked (not phase-random with respect to the time-locking experimental
event).

Computing component time/frequency transforms


由于各个独立成分更可能直接反应大脑的 EEG source,因此这里将对独立成分进行时频分解。
这步操作选择 FFT,是因为相对 wavelets 而言,选择 FFT 可以计算更低的频率。

数据 3 预处理
加载数据
电极定位

重参考(双侧乳突)FCZ 作为参考

滤波(0.1-30)
插值坏导(FP1)
没降采样率

跑 ICA 后(去毛刺)

去伪迹(手动)
数据 3 数据分析
创建事件清单

Assign.bin
ERP 分段(-200 800)与基线校正
ERPLAB 去伪迹
计算平均波幅

计算峰值

You might also like