ValueError: Input 0 of layer sequential is incompatible with the layer

ValueError: Input 0 of layer sequential is incompatible with the layer

我正在尝试 运行 这个模型,但我一直收到这个错误。输入数据的形状有一些错误,我尝试了一下,但仍然出现这些错误。

错误:

ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 1 but received input with shape (None, 32, 32, 3)
# Image size
img_width = 32
img_height = 32

# Define X as feature variable and Y as name of the class(label)
X = []
Y = []

for features,label in data_set:
    X.append(features)
    Y.append(label)

X = np.array(X).reshape(-1,img_width,img_height,3)
Y = np.array(Y)
print(X.shape)  # Output :(4943, 32, 32, 3)
print(Y.shape)  # Output :(4943,)

# Normalize the pixels
X = X/255.0

# Build the model
cnn = Sequential()
cnn.add(keras.Input(shape = (32,32,1)))
cnn.add(Conv2D(32, (3, 3), activation = "relu", input_shape = X.shape[1:]))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(32, (3, 3), activation = "relu",input_shape = X.shape[1:]))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(64, (3,3), activation = "relu",input_shape = X.shape[1:]))
cnn.add(MaxPooling2D(pool_size = (2,2)))
cnn.add(Flatten())
cnn.add(Dense(activation = "relu", units = 150))
cnn.add(Dense(activation = "relu", units = 50))
cnn.add(Dense(activation = "relu", units = 10))
cnn.add(Dense(activation = 'softmax', units = 1))
cnn.summary()
cnn.compile(loss = 'categorical_crossentropy',optimizer = 'adam',metrics = ['accuracy'])

# Model fit
cnn.fit(X, Y, epochs = 15)e

我尝试阅读有关此问题的内容,但仍然不是很了解。

更改此行(最后一个维度):

cnn.add(keras.Input(shape = (32,32,3)))

你的输入形状应该是 (32,32,3)。 y 是你的标签矩阵。我假设它包含 N 个唯一整数值​​,其中 N 是 类 的数量。如果 N=2,您可以将其视为二元分类问题。在那种情况下,顶层的代码应该是

cnn.add(Dense(1, activation = 'sigmoid'))

你的编译代码应该是

cnn.compile(loss = 'binary_crossentropy',optimizer = 'adam',metrics = ['accuracy'])

如果你有超过 2 个 类 那么你的代码应该是

cnn.add(Dense(N, activation = 'softmax'))
cnn.compile(loss = 'sparse_categorical_crossentropy',optimizer = 'adam',metrics = ['accuracy'])

其中N是类,

的个数