我有一个由 51 个时间序列向量组成的矩阵(形状:m x 51), 每个向量都有m个样本。我想训练两个自动编码器,一个使用 CNN,另一个使用 LSTM 网络。我想将 2D 矩阵重塑为 3D 矩阵,使其包含51 个变量中的每一个的m_new序列,并且每个序列都是w长的,并且重叠了lap样本。
我设法做到了这一点,但没有重叠部分。有没有一种有效的方法来做到这一点?
W = 20 #window size
m_new = int(np.floor(m/W))
m_trct = int(m_new*W)
X_raw_trct = X_raw[0:m_trct,:]
X = np.reshape(X_raw_trct,(m_new,W,X_raw_trct.shape[1]))
如下所示,生成的序列重叠 lap = w-1。
**更新** 参考Split Python sequence (time series/array) into subsequences with overlay中的答案,使用函数subsequences将 1D 数组拆分为w-1重叠的w长子序列(步幅of 1) 生成形状为 ( m_new, w ) 的二维数组。在下面的代码 2 中,我必须使用循环将 51 个变量的每个向量作为 1D 数组处理,然后附加 2D 数组的结果以生成最终的 3D 形状数组 ( m_new, w, 51 )。但是,循环需要很长时间才能执行。
**code 2**
def subsequences(ts, window):
## ts is of shape (m,)
shape = (ts.size - window + 1, window)
strides = ts.strides * 2
return np.lib.stride_tricks.as_strided(ts, shape=shape, strides=strides)
# rescaledX_raw.shape is (m,51)
n = rescaledX_raw.shape[1]
# n = 51
a = rescaledX_raw[:,0]
# a.shape is (m,)
Xaa = subsequences(a,W)
X = ones(Xaa.shape)*-1
# X.shape is (m_new, W)
for kk in range(n):
## a is of shape (m,)
a = rescaledX_raw[:,kk]
Xaa = subsequences(a,W)
X = np.dstack((X, Xaa))
X_nn = np.delete(X, 0, axis=2)
# X_nn.shape is (m_new, W, 51)
此外,我尝试使用代码 3中的函数将其作为完整的 2D 形状数组( m x 51)转换为 3D 形状数组(m_new,w ,51)
**code 3**
def rolling_window(a, window):
## a is of shape (51,m)
shape = (a.shape[-1] - window + 1,window,a.shape[0])
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
但生成的 3D 矩阵不是正确的。请参考下面的演示。另外,如何将步幅添加为可以更改的变量。在上面的脚本中,步幅为 1(意味着重叠为w-1)

