我正在跟踪一个使用keras创建LSTM神经网络的教程。 我有1270行和26个特征的数组。 我这样分割数据:
train_ind = int(0.8 * X.shape[0])
X_train = X[:train_ind]
X_test = X[train_ind:]
y_train = y[:train_ind]
y_test = y[train_ind:]
我正在尝试使用以下方法为lstm重塑它:
num_steps = 4
X_train_shaped = np.reshape(X_train_sc, newshape=(-1, num_steps, 26))
y_train_shaped = np.reshape(y_train_sc, newshape=(-1, num_steps, 26))
assert X_train_shaped.shape[0] == y_train_shaped.shape[0]
但是,我遇到此错误:
ValueError: cannot reshape array of size 1016 into shape (4,26)
答案 0 :(得分:3)
好吧,4 x 26 = 104,并且1270无法被104整除,因此np.reshape()
不能选择整数行(-1
)来使其适合数组。您需要更改num_steps
或num_features
(26),以使num_steps * num_features
平均除以1270。不幸的是,对于num_features = 26
,这是不可能的,因为13不会除以1270。另一种选择是选择其他总数的行,例如1040或1144,它们都可以被104整除。
因此,与其设置train_ind = int(0.8 * X.shape[0])
,不如尝试train_id = 1040
或较小的104倍。但是,请注意,您的测试数据还必须具有相当数量的行,以便对其进行整形以同样的方式。
答案 1 :(得分:1)
首先,您不需要重新设计数组的形状。 numpy数组的shape属性仅确定如何向您显示基础数据以及如何访问数据。更改形状实际上并不会移动任何数据。
同样,我们注意到人们无法将形状更改为不可能的形状。例如,如果数组的大小为(100,5,6),则不能将其更改为(100,5,7)。通常,轴必须倍数到正确的值。 100 * 5 * 6不等于100 * 5 * 7。
在您的情况下,您听起来好像想使用LSTM,这通常意味着您只需要简单地添加一个附加轴,即可获得大小为1的输入向量。可以使用无添加一个新轴。 numpy中的条目。像这样:
X_train = X[:train_ind,:,None] #The axes are Batch, Time, and the Input Vector.
形状现在应该是(1016,26,1)。