简体   繁体   English

为深度学习重塑 np 数组

[英]reshape np array for deep learning

I want to use keras to apply a neural network to my time-series data.我想使用 keras 将神经网络应用于我的时间序列数据。 TO improve the model I want to have 50 time states of input per output.为了改进模型,我希望每个输出有 50 个时间状态的输入。 The final input should have 951 samples with 50 time points of 10 features (951, 50, 10)最终输入应该有 951 个样本,有 10 个特征的 50 个时间点 (951, 50, 10)

Therefore, I have to reshape my data.因此,我必须重塑我的数据。 I do that doing a for loop, but is awfully slow.我这样做是为了循环,但速度非常慢。 Is there a way to improve the code and making it faster?有没有办法改进代码并使其更快?

Example:例子:

import numpy as np
X = np.ones((1000,10))

for i in range(50, int(X.shape[0]) + 1):
     if i == 50:
        z = 0
        X2 = np.array(X[z:i, :]).reshape((1, 50, X.shape[1]))
     else:
        X2 = np.concatenate([X2, np.array(X[z:i, :]).reshape((1, 50, X.shape[1]))])
     z = z + 1

We can leverage np.lib.stride_tricks.as_strided based scikit-image's view_as_windows to get sliding windows.我们可以利用基于np.lib.stride_tricks.as_stridedscikit-image's view_as_windows来获得滑动窗口。 More info on use of as_strided based view_as_windows .有关使用基于view_as_windowsas_strided的更多信息

from skimage.util.shape import view_as_windows

X2 = view_as_windows(X,(50,10))[:,0]

It's simply a view into the input and hence virtually free on runtime -它只是输入的视图,因此在运行时几乎是免费的 -

In [17]: np.shares_memory(X,view_as_windows(X,(50,10))[:,0])
Out[17]: True

In [18]: %timeit view_as_windows(X,(50,10))[:,0]
10000 loops, best of 3: 32.8 µs per loop

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

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