【问题标题】:Reshape 2d input into a 3d LSTM sequence将 2d 输入重塑为 3d LSTM 序列
【发布时间】:2016-12-08 02:56:29
【问题描述】:

我正在尝试重塑二维数组,例如。 (100000,100) 变成一个有 10 个步骤的 LSTM 序列,即。 (100000,10,100)。我正在使用以下代码:

n_input = 100
n_steps = 10 
a = np.arange(10000000).reshape(100000,100)
b = np.empty([0,n_input])
c = np.empty([0,n_steps,n_input])

for i in range(a.shape[0]-n_steps+1):
    b = np.empty([0,n_input])
    for j in range(n_steps):
        b = np.vstack((b,a[j+1,]))
    c = np.concatenate((c, b[np.newaxis,...]), axis=0)

以上内容似乎需要大量时间来处理。我可以就更有效的方式来写这篇文章寻求建议吗?

【问题讨论】:

  • 缩小问题以进行测试...即_input、n_steps和reshape中的术语之间的关系是什么?
  • 是的,使用较小的参数就可以了,但如果可能的话,我更愿意避免在 python 中使用 for 循环
  • 如果东西被换出到磁盘,将问题分成块可能会更快,这就是我所指的

标签: python numpy lstm


【解决方案1】:
import time
import numpy as np


def _2d_to_3d(X, n_steps=10):
    _X = np.zeros((X.shape[0]//n_steps,n_steps,X.shape[1]))
    for i in range(len(X)//n_steps):
        _X[i,:] = X[i*n_steps:i*n_steps+n_steps]
    return _X

def time_function():
    a = np.arange(10000000).reshape(100000,100)
    start = time.time()
    b = _2d_to_3d(a, 10)
    total = time.time() - start
    print('time: {}'.format(total))
    print('original shape: {}'.format(a.shape))
    print('new shape: {}'.format(b.shape))

time_function()
time: 0.10249948501586914
original shape: (100000, 100)
new shape: (10000, 10, 100)

【讨论】: