keras 中 RNN 的输入形状
Input shape for a RNN in keras
我的数据集具有以下形状:
y_train.shape,y_val.shape
((265, 2), (10, 2))
x_train.shape, x_val.shape
((265, 4), (10, 4))
我正在尝试使用简单的 RNN 模型
model=models.Sequential([layers.SimpleRNN(20,input_shape=(None,4),return_sequences=True),
layers.SimpleRNN(20,return_sequences=True),
layers.SimpleRNN(2),
])
model.compile(optimizer="Adam",
loss=tf.keras.losses.MeanSquaredError(),
metrics=["accuracy"])
当我用数据拟合模型时出现问题:
history=model.fit(x_train,y_train,
epochs=20,
validation_data=(x_val,y_val),
verbose=2)
我收到以下错误:
ValueError: Input 0 of layer sequential_12 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 4)
我认为这与输入有关...但我不明白是什么。
首先输入的应该是 3D 形状 [batch, timesteps, feature]
。
x_train
和 x_val
不遵循此规则。您可以通过以下方式轻松扩展他们的暗淡:
x_train = np.expand_dims(x_train, axis = -1) # (265, 4, 1)
x_val= np.expand_dims(x_val, axis = -1) # (10, 4, 1)
另一个问题是input_shape
。根据x_train
和x_val
的新形状需要input_shape=(4,1)
。所以正确的定义应该是:
model=models.Sequential([layers.SimpleRNN(20,input_shape=(4,1),return_sequences=True),
layers.SimpleRNN(20,return_sequences=True),
layers.SimpleRNN(2),
])
如果你想在 input_shape
中包含 None
那么你应该传递 batch_input_shape
.
model= tf.keras.Sequential([tf.keras.layers.SimpleRNN(20,batch_input_shape=(None, 4,1),
return_sequences=True),
tf.keras.layers.SimpleRNN(20,return_sequences=True),
tf.keras.layers.SimpleRNN(2),
])
这表示模型接受任何批量大小。
注意:如果您指定 batch_input_shape
,例如 batch_input_shape=(32, 4,1)
,那么如果剩余批次的大小小于 32
,它将抛出错误。
我的数据集具有以下形状:
y_train.shape,y_val.shape
((265, 2), (10, 2))
x_train.shape, x_val.shape
((265, 4), (10, 4))
我正在尝试使用简单的 RNN 模型
model=models.Sequential([layers.SimpleRNN(20,input_shape=(None,4),return_sequences=True),
layers.SimpleRNN(20,return_sequences=True),
layers.SimpleRNN(2),
])
model.compile(optimizer="Adam",
loss=tf.keras.losses.MeanSquaredError(),
metrics=["accuracy"])
当我用数据拟合模型时出现问题:
history=model.fit(x_train,y_train,
epochs=20,
validation_data=(x_val,y_val),
verbose=2)
我收到以下错误:
ValueError: Input 0 of layer sequential_12 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 4)
我认为这与输入有关...但我不明白是什么。
首先输入的应该是 3D 形状 [batch, timesteps, feature]
。
x_train
和 x_val
不遵循此规则。您可以通过以下方式轻松扩展他们的暗淡:
x_train = np.expand_dims(x_train, axis = -1) # (265, 4, 1)
x_val= np.expand_dims(x_val, axis = -1) # (10, 4, 1)
另一个问题是input_shape
。根据x_train
和x_val
的新形状需要input_shape=(4,1)
。所以正确的定义应该是:
model=models.Sequential([layers.SimpleRNN(20,input_shape=(4,1),return_sequences=True),
layers.SimpleRNN(20,return_sequences=True),
layers.SimpleRNN(2),
])
如果你想在 input_shape
中包含 None
那么你应该传递 batch_input_shape
.
model= tf.keras.Sequential([tf.keras.layers.SimpleRNN(20,batch_input_shape=(None, 4,1),
return_sequences=True),
tf.keras.layers.SimpleRNN(20,return_sequences=True),
tf.keras.layers.SimpleRNN(2),
])
这表示模型接受任何批量大小。
注意:如果您指定 batch_input_shape
,例如 batch_input_shape=(32, 4,1)
,那么如果剩余批次的大小小于 32
,它将抛出错误。