使用Numpy计算EEG频带FFT的值错误



首先,我对这些事情很陌生。我正在尝试将FFT算法应用于EEG波段获得的一些值。我找到了以下代码,但无法使其正常工作。将numpy导入为np

fs = 200                                
#data = np.random.uniform(0, 100, 1024)  # 2 sec of data b/w 0.0-100.0
data = np.array([(-0.27,-0.09,0.16,0.01,0.67,0.65,-1.59,0.11,-0.36,0.69,0.94,0.43,-0.53,-0.57,0.98,-0.97),(-0.74,-0.56,0.76,0.58,1.79,2.22,-4.96,-0.25,-1.19,1.57,2.95,1.47,-1.00,-1.06,2.97,-3.43),
(-0.89,-1.50,1.76,1.72,2.09,4.04,-7.97,-1.30,-2.09,1.11,4.82,2.57,-0.01,0.05,4.64,-6.44),
(-0.84,-2.78,3.00,2.88,2.00,6.36,-11.46,-2.36,-3.22,-0.01,6.96,3.84,1.85,2.11,6.64,-10.31),
(-0.39,-4.27,4.26,4.57,1.09,8.77,-14.78,-4.09,-4.40,-1.87,9.03,5.12,4.86,5.31,8.76,-14.77)])
print("After data")
# Get real amplitudes of FFT (only in postive frequencies)
fft_vals = np.absolute(np.fft.rfft(data))
print("After fft_vales")
print(fft_vals)
# Get frequencies for amplitudes in Hz
fft_freq = np.fft.rfftfreq(len(data), 1.0/fs)
print("After fft_freq")
print(fft_freq)
# Define EEG bands
eeg_bands = {'Delta': (0, 4),
'Theta': (4, 8),
'Alpha': (8, 12),
'Beta': (12, 30),
'Gamma': (30, 45)}
# Take the mean of the fft amplitude for each EEG band
eeg_band_fft = dict()
for band in eeg_bands:  
freq_ix = np.where((fft_freq >= eeg_bands[band][0]) & 
(fft_freq <= eeg_bands[band][1]))[0]
eeg_band_fft[band] = np.mean(fft_vals[freq_ix])
print(eeg_band_fft)

当它进入for时,我得到了以下错误。

/home/xxxx/.local/lib/python3.8/site-packages/numpy/core/fromnumeric.py:3372: RuntimeWarning: Mean of empty slice.
return _methods._mean(a, axis=axis, dtype=dtype,
/home/xxxx/.local/lib/python3.8/site-packages/numpy/core/_methods.py:170: RuntimeWarning: invalid value encountered in double_scalars
ret = ret.dtype.type(ret / rcount)

我错过了什么或出了什么问题?

正如我上面所说,我对这件事很陌生,所以请尽可能简单地解释一切。

编辑1

这是我得到的结果:

band        val
0  Delta  64.642945
1  Theta        NaN
2  Alpha        NaN
3   Beta        NaN
4  Gamma  25.851368

您只是有一个拼写错误,请更改此代码:

# Take the mean of the fft amplitude for each EEG band
eeg_band_fft = dict()
for band in eeg_bands:  
freq_ix = np.where((fft_freq >= eeg_bands[band][0]) & 
(fft_freq <= eeg_bands[band][1]))[0]
eeg_band_fft[band] = np.mean(fft_vals[freq_ix])
print(eeg_band_fft)

读取

# Take the mean of the fft amplitude for each EEG band
eeg_band_fft = dict()
for band in eeg_bands:  
freq_ix = np.where((fft_freq >= eeg_bands[band][0]) & 
(fft_freq <= eeg_bands[band][1]))[0]
eeg_band_fft[band] = np.mean(fft_vals[freq_ix])
print(eeg_band_fft)

注意一行的缩进。这样,您应该可以看到输出:

{'Alpha': nan,
'Beta': nan,
'Delta': 2.0749711266314317,
'Gamma': 6.3502280534780855,
'Theta': nan}

请注意,nan的和出现错误是因为对于某些频带,fft_vals[freq_ix]是空的。您可以通过打印每个波段的fft_vals[freq_ix]值来确认这一点。

还要注意,numpy只会打印一次这样的错误/警告,即使您有多次出现。

最新更新