Python嵌套,嵌套FOR LOOP,混淆了

时间:2015-07-28 12:03:58

标签: python for-loop numpy multidimensional-array nested-loops

那里。

也许我看不到森林里的树木,或者完全混淆了这个东西。 但我希望数组x的形状为(120, 68,815)

epochs = 120
channels = 68
samples = 815

我想为每个频道的每个频道计算每个频道,所以: 时代1:通道1与1与2与3等等。 每个时代都是如此。

当我运行如下所述的代码时,我总是得到相同的值,每个时代。 我认为循环中有一个错误,但我找不到它。 有经验的人有没有找到它?

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)

谢谢。

1 个答案:

答案 0 :(得分:0)

所以我只是在我的函数中更改了数组形式,以便不计算函数中相互交叉的所有通道,但是在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秒 有问题吗?!