Keras:ValueError:图层sequence_1的输入0与该图层不兼容:预期的ndim = 3,找到的ndim = 2

时间:2020-10-09 16:24:51

标签: python tensorflow keras

我有一个形状为X: (1146165, 19, 22)Y: (1146165,)的数据集。这是我的模型代码:

import tensorflow as tf

train_data = tf.data.Dataset.from_tensor_slices((x_train, y_train))
valid_data = tf.data.Dataset.from_tensor_slices((x_valid, y_valid))

def create_model(shape=(19, 22)):
    tfkl = tf.keras.layers
    model = tf.keras.Sequential([
        tfkl.LSTM(128, return_sequences=True, input_shape=shape),
        tfkl.LSTM(64),
        tfkl.Dropout(0.3),
        tfkl.Dense(64, activation="linear"),
        tfkl.Dense(1)
    ])
    
    model.compile(loss='mean_absolute_error', optimizer="adam")
    return model

model = create_model()
model.summary()

您可以看到input_shape(19, 22),这是正确的,但是当我使用fit时出现错误ValueError: Input 0 of layer sequential_15 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [19, 22]
我在Stack上搜索了一些答案,但是大多数答案是因为输入维是(a, b)而不是(a,b,c)。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

如果您想用tf.data.Dataset来拟合模型,则需要确保在model.fit中使用它之前对它进行批处理。对于您选择的batch_size,请尝试

train_data = train_data.batch(batch_size)
model.fit(train_data)