Python嵌套,嵌套FOR循环,混合



那里。

也许我看不到森林里的树木,或者完全融入了这件事。但是我想要具有(120, 68,815)形状的阵列x

epochs = 120
channels = 68
samples = 815

我想为每个历元计算每个通道和每个通道,因此:Epoch 1:Channel 1 with 1 with 2 with 3,依此类推。每个时代都一样。

当我像下面解释的那样运行代码时,我总是为每个epoch获得相同的值。我认为循环中有一个错误,但我找不到。有没有经验丰富的人能找到它?

Rxy = np.zeros((n_epochs, channels, channels, n_freqs), dtype=complex)
Rxx = np.zeros((n_epochs, channels, channels, n_freqs))
Ryy = np.zeros((n_epochs, channels, channels, n_freqs))
for i in range(0, n_epochs):
    print('Computed Epoch %s'%(i+1))
    for j in xrange(0, channels):
        for k in xrange(0, channels):
            Rxy[i,j,k], freqs = mlab.csd(x[j], x[k], NFFT=nfft, Fs=sfreq)
            Rxx[i,j,k], _____ = mlab.psd(x[j], NFFT=nfft, Fs=sfreq)
            Ryy[i,j,k], _____ = mlab.psd(x[k], NFFT=nfft, Fs=sfreq)
    Rxy_mean = np.mean(Rxy, axis=0, dtype=np.float32)
    Rxx_mean = np.mean(Rxx, axis=0, dtype=np.float32)
    Ryy_mean = np.mean(Ryy, axis=0, dtype=np.float32)

谢谢。

所以我只是改变了函数中的数组形式,不计算函数中所有相互交叉的通道,而是在函数外部使用itertool。它创建了68个通道的所有可能组合,并在每个组合上运行计算[…]-函数,将其存储在适当的阵列形式中

def compute_mean_psd_csd(x, y, n_epochs, nfft, sfreq):
    '''Computes mean of PSD and CSD for signals.'''
    Rxy = np.zeros((n_epochs, n_freqs), dtype=np.complex)
    Rxx = np.zeros((n_epochs, n_freqs), dtype=np.complex)
    Ryy = np.zeros((n_epochs, n_freqs), dtype=np.complex)
    for i in range(n_epochs):
        Rxy[i], freqs = mlab.csd(x[i], y[i], NFFT=nfft, Fs=sfreq)
        Rxx[i], _ = mlab.psd(x[i], NFFT=nfft, Fs=sfreq)
        Ryy[i], _ = mlab.psd(y[i], NFFT=nfft, Fs=sfreq)
    Rxy_mean = np.mean(Rxy, axis=0)
    Rxx_mean = np.mean(Rxx, axis=0)
    Ryy_mean = np.mean(Ryy, axis=0)
    return freqs, Rxy, Rxy_mean, np.real(Rxx_mean), np.real(Ryy_mean)
import itertools
comb = itertools.combinations(range(channels), 2)
for m, n in comb:
    freqs, Rxy, Rxy_mean, Rxx_mean, Ryy_mean = compute_mean_psd_csd(x[:, n, :], x[:, m, :], n_epochs, nfft, sfreq)
    assert len(freqs) == n_freqs, 'n_freqs do not match. Check nfft values provided.'

这些变化确实将我的跑步时间减少到了"仅"250秒。有什么问题吗?!

相关内容

  • 没有找到相关文章