brainflow-dev / brainflow

BrainFlow is a library intended to obtain, parse and analyze EEG, EMG, ECG and other kinds of data from biosensors
https://brainflow.org/
MIT License
1.28k stars 327 forks source link

Implement Common Spatial Patterns algorithm #110

Closed Andrey1994 closed 3 years ago

Andrey1994 commented 3 years ago

https://en.wikipedia.org/wiki/Common_spatial_pattern

Andrey1994 commented 3 years ago

Python reference impl:

def train_CSP(epo, mrk_class):
"""
Usage:W, d = trainCSP(epo, mrk_class)Parameters:epo: a 3D array of segmented signals (samples x channels x epochs)mrk_class: a 1D array that assigns markers to classes (0, 1)Returns:W: matrix of spatial filtersd: vector of generalized Eigenvalues
"""
C=epo.shape[1]
X1=np.reshape(np.transpose(epo[:,:,mrk_class==0], (1,0,2)), (C,-1))
S1=np.cov(X1)
X2=np.reshape(np.transpose(epo[:,:,mrk_class==1], (1,0,2)), (C,-1))
S2=np.cov(X2)
d,W=scipy.linalg.eigh(a=S1, b=S1+S2)
return W,d

W is a matrix of filters and d are the corresponding eigenvalues. In this version of CSP, an EV of 0.5 means explained variances equal in both classes (no discriminability) and 1.0 100% for class mrk_class==0 and 0.0 for the other class.

You would then have to select relevant csps, so e.g. the 2-3 best for each class (highest/lowest EVs) or the 3-6 largest EVs in deviation from 0.5.

Tutorial:

https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&ved=2ahUKEwj91IGxhubsAhXMGewKHflIB6AQFjAAegQIARAC&url=http%3A%2F%2Fdoc.ml.tu-berlin.de%2Fbbci%2Fpublications%2FBlaTomLemKawMue08.pdf&usg=AOvVaw3rSEI1KATdOZl8gjGLlI2y

github-actions[bot] commented 3 years ago

Stale issue, need to tale a look

Div12345 commented 3 years ago

Is this to be implemented in Python?

Andrey1994 commented 3 years ago

No, python version here just for reference. Should be in Cpp like everything else

Div12345 commented 3 years ago

Could you give me some pointers as to how to start going about this? Like where this would come under, etc.