Issue
I am trying to implement a Common Average Reference function in python. The idea is to compute the average of the signal at all EEG channels and subtract it from the EEG signal at every channels for every time point. The input of this function is a NumPy array called trials. Trials is a 3D array that contains EEG data in this form: (trials x time x channels). for example:
trials.shape is (240, 2048, 17)
The output will be the processed signal array. This is my current code:
# Common Average Reference
import numpy as np
def car(trials):
signal = []
for tr in trials:
tr = np.subtract(tr,(np.dot(np.mean(tr, axis=1), np.ones((0, np.size(tr, axis=1))))))
signal.append(tr)
return signal
Bnd it returns this error:
ValueError: shapes (2048,) and (0,17) not aligned: 2048 (dim 0) != 0 (dim 0)
Do you have any suggestions on how to solve this? Thank you in advance!
Solution
WHOOPS - I didn't understand the definition of Common Average Reference. As pointed out in Warren Weckesser's comment, the CAR is the value at each electrode, not over time. So the average should be calculated over the channels dimension. Use keepdims=True
to make the shape compatible so that the subtraction can still be done with broadcasting:
>>> car = np.mean(trials, axis=2, keepdims=True)
>>> car.shape
(240, 2048, 1)
You can take advantage of NumPy's broadcasting
>>> import numpy as np
>>> trials = np.random.random((240, 2048, 17))
(WRONG) >>> car = np.mean(trials, axis=0) # calculate the Common Average Reference across all the trials for each channel
>>> car.shape
(2048, 17)
>>> tnew = trials - car
Answered By - mtrw
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.