Home > Enterprise >  Python Numpy CAR implementation - ValueError: shapes not aligned
Python Numpy CAR implementation - ValueError: shapes not aligned

Time:02-05

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!

CodePudding user response:

You can take advantage of NumPy's broadcasting

>>> import numpy as np
>>> trials = np.random.random((240, 2048, 17))
>>> 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
  •  Tags:  
  • Related