如何将滑动窗口的3d阵列扁平化为2d阵列?

时间:2019-06-26 07:00:57

标签: python arrays numpy lstm sliding-window

我正在python(Keras)中使用自动编码器LSTM。我有一个多元输入,并且我使用滑动窗口方法将其转换为LSTM输入的正确格式。最后,我得到与窗口形状相同的输出。 然后,我想将此数组转换为原始输入形状。谁能帮我该怎么做?

这是我的代码,用于在多变量信号上放置滑动窗口:


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]]])

1 个答案:

答案 0 :(得分:0)

您可以使用此:

注意:步幅与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]])