compilation step in keras sequential model throwing the error "ValueError: Input 0 of layer sequential_9 is incompatible with the layer:

compilation step in keras sequential model throwing the error "ValueError: Input 0 of layer sequential_9 is incompatible with the layer:

我正在尝试开发两个 类 的分类器。我按如下方式实现了模型:

model = keras.models.Sequential() #using tensorflow's version of keras
model.add(keras.layers.InputLayer(input_shape = X_train_scaled[:,1].shape))
model.add(keras.layers.Dense(250,activation="relu"))
model.add(keras.layers.Dense(50,activation="relu"))
model.add(keras.layers.Dense(2,activation="softmax"))
model.summary()

# Compile the model
model.compile(loss = 'sparse_categorical_crossentropy',
             optimizer = "sgd",
             metrics = ["accuracy"])

输入的大小是

X_train_scaled[:,1].shape, y_train.shape
((552,), (552,))

整个错误信息是:

ValueError: Input 0 of layer sequential_9 is incompatible with the layer:
expected axis -1 of input shape to have value 552 but received input with shape (None, 1)

我做错了什么?

错误消息说您定义了一个模型,该模型期望输入形状为 (batch_size, 552) 并且您正试图为其提供形状为 (batch_size, 的数组1).

问题最有可能发生在

input_shape = X_train_scaled[:,1].shape)

这很可能是:

input_shape = X_train_scaled.shape[1:]

即您想要将模型的形状定义为特征的形状(没有示例数量)。然后将该模型以小批量的形式提供......例如如果你调用 model.fit(X_train_scaled, ...) keras 将创建小批量(默认为 32 个示例)并更新每个小批量的模型权重。

此外,请注意您将模型定义为 return 形状 (batch_size, 2)。所以 y_train 的形状必须是 (X_train.shape[0], 2).

佩德罗回答了这个问题