输入形状总是与图层不兼容

时间:2021-05-26 13:27:37

标签: python tensorflow machine-learning input shapes

我很困惑我的模型需要输入的形状是什么样的。我的训练数据看起来像这样 (2834, 270, 1),其中我有 2834 个样本,每个样本包含 270 个单独的值。我的目标是每个值(例如数字 2),我想训练我的模型以准确预测给定样本的目标值(其中包含 270 个单独的值)这是我目前拥有的代码:

train_data = np.asarray(train_data).astype('float32')
train_data = train_data.reshape(2834, 270, 1)
train_labels = train_labels.reshape(2834)
train_data = tf.cast(train_data, dtype='float32')
train_labels = tf.cast(train_labels, dtype='float32')
print(train_data.shape)
print(train_labels.shape)

model = models.Sequential()
model.add(layers.Conv1D(64, 5, activation='relu', input_shape=(train_data.shape)))
model.add(layers.MaxPooling1D(2))
model.add(layers.Conv1D(32, 5, activation='relu'))
model.add(layers.MaxPooling1D(2))
model.add(layers.Dropout(0.2))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='linear'))
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-05), loss=tf.keras.losses.MeanSquaredError())
history = model.fit(train_data, train_labels, epochs=10, batch_size=1)
print(model.summary)

我有一个 1d 神经网络(因为我认为我的训练数据是一维的,可能是错误的)应该输出一个值,但是当我尝试拟合我的模型时出现错误。它说我的其中一个图层的输入形状不正确。完整的错误:

   ValueError: Input 0 of layer max_pooling1d_6 is incompatible with the layer: expected ndim=3, found ndim=4. Full shape received: (None, 2834, 266, 64)

1 个答案:

答案 0 :(得分:0)

改变这个:

model.add(layers.Conv1D(64, 5, activation='relu', input_shape=(train_data.shape)))

到:

model.add(layers.Conv1D(64, 5, activation='relu', input_shape=(266, 64)))