代码之家  ›  专栏  ›  技术社区  ›  Mornor

Keras model.evaluate()失败

  •  0
  • Mornor  · 技术社区  · 6 年前

    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)
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Dr. Snoopy    6 年前

    错误表明目标(y)的形状应该是一个热编码的,每个样本有10个元素。你证明了yèu测试的形状(10000,),它不是一个热编码的。

    您可以通过以下方式完成此操作:

    y_test = kera.utils.np_utils.to_categorical(y_test)