简体   繁体   English

如何将三维滑动窗口阵列展平为二维阵列?

[英]How to flatten a 3d array of sliding window into 2d array?

I'm using an Autoencoder LSTM in python(Keras). 我在python(Keras)中使用Autoencoder LSTM。 I have a multivariate input and I use a sliding window approach to convert it to the proper format of LSTM input. 我有一个多变量输入,我使用滑动窗口方法将其转换为正确的LSTM输入格式。 In the end, I get the output with the same shape as the window. 最后,我得到的输出形状与窗口相同。 Then I want to convert this array to the original input shape. 然后我想将此数组转换为原始输入形状。 Can anyone help me how should I do this? 任何人都可以帮我,我该怎么做?

This is my code to put a sliding window on a multivariate signal: 这是我在多变量信号上放置滑动窗口的代码:


def window(samples, windows_size, step):
    m, n = samples.shape 
    print("\nold shape: ", m, "*", n)
    num_signals = n    
    num_samples = (samples.shape[0] - windows_size) // step + 1
    aa = np.empty([num_samples, windows_size, num_signals])

    for j in range(num_samples):
        for i in range(num_signals):
            aa[j, :, i] = samples[(j * step):(j * step + windows_size), i]
    samples = aa
    m ,n, k = samples.shape
    print("new shape: ", m, "*", n, "*", k)
    return samples

x = np.asarray([[1,0.1,0.1],[2,0.2,0.2],[3,0.3,0.3],[4,0.4,0.4],
                [5,0.5,0.5],[6,0.6,0.6],[7,0.7,0.7],[8,0.8,0.8]])

window(x, 3, 2)

old shape:  8 * 3
new shape:  3 * 3 * 3
Out[65]: 
array([[[1. , 0.1, 0.1],
        [2. , 0.2, 0.2],
        [3. , 0.3, 0.3]],

       [[3. , 0.3, 0.3],
        [4. , 0.4, 0.4],
        [5. , 0.5, 0.5]],

       [[5. , 0.5, 0.5],
        [6. , 0.6, 0.6],
        [7. , 0.7, 0.7]]])

You can use this: 你可以用这个:

Note: stride is the same concept as in CNNs, number of elements you skip to get the next window. 注意:stride与CNN中的概念相同,是您跳过以获取下一个窗口的元素数。

inp = np.array([[[1. , 0.1, 0.1],
        [2. , 0.2, 0.2],
        [3. , 0.3, 0.3]],

       [[3. , 0.3, 0.3],
        [4. , 0.4, 0.4],
        [5. , 0.5, 0.5]],

       [[5. , 0.5, 0.5],
        [6. , 0.6, 0.6],
        [7. , 0.7, 0.7]]])
def restitch(array, stride):
    flat = array.flatten().reshape(-1,array.shape[2])
    keep = [i for i in range(len(flat)) if not(i%(stride+1)==0 and i>0)]
    return flat[keep]

restitch(inp, 2)
array([[1. , 0.1, 0.1],
       [2. , 0.2, 0.2],
       [3. , 0.3, 0.3],
       [4. , 0.4, 0.4],
       [5. , 0.5, 0.5],
       [6. , 0.6, 0.6],
       [7. , 0.7, 0.7]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM