我创建了一个类似于以下内容的ConvNet:
model = Sequential()
optimizer = Adam()
model.add(Lambda(lambda x: x / 127.5 - 1., input_shape=(28, 28, 1)))
model.add(Convolution2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(NUM_CLASSES, activation='softmax'))
model.compile(optimizer=optimizer, loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])
我正在使用形状数据进行训练
X_train.shape = (48000, 28, 28, 1)
X_val.shape = (12000, 28, 28, 1)
而且效果很好。
但是,我现在想使用keras.evaluate()
函数测试模型:
score = trained_model.evaluate(X_test, y_test, batch_size=128)
# X_test.shape = (10000, 28, 28, 1)
# y_test.shape (10000,)
导致以下错误:
ValueError: Error when checking target: expected dense_2 to have shape (10,) but got array with shape (1,)
鉴于我对训练,验证和测试集使用相同的形状,因此我不太理解此错误。
您介意解释我的错误是什么,以及如何解决该错误吗?
非常感谢!
编辑:输出trained_model.summary()
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
lambda_1 (Lambda) (None, 28, 28, 1) 0
_________________________________________________________________
conv2d_1 (Conv2D) (None, 26, 26, 64) 640
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 13, 13, 64) 0
_________________________________________________________________
dropout_1 (Dropout) (None, 13, 13, 64) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 10816) 0
_________________________________________________________________
dense_1 (Dense) (None, 128) 1384576
_________________________________________________________________
dropout_2 (Dropout) (None, 128) 0
_________________________________________________________________
dense_2 (Dense) (None, 10) 1290
=================================================================
Total params: 1,386,506
Trainable params: 1,386,506
Non-trainable params: 0
评论中给出的解决方案
我忘记了一次热更新我的y_train
,y_val
和y_test
数据。
解决:
from keras.utils.np_utils import to_categorical
y_train = to_categorical(y_train)
答案 0 :(得分:1)
该错误表明目标(y)的形状应为单热编码,每个样本包含10个元素。您证明y_test的形状为(10000,),不是一次性编码。
您可以执行以下操作:
y_test = kera.utils.np_utils.to_categorical(y_test)