【问题标题】:Keras: expected dense_5 to have shape (None, 1) but got array with shape (60000, 10)Keras:期望dense_5具有形状(无,1)但得到形状为(60000、10)的数组
【发布时间】:2019-09-15 16:57:01
【问题描述】:

我在 python 3.6 上运行以下代码:

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float')/255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float')/255
train_labels = ku.to_categorical(train_labels)
test_labels = ku.to_categorical(test_labels)
filepath = 'my_model_file.hdf5' # define where the model is saved
callbacks_list = [
        keras.callbacks.EarlyStopping(
            monitor = 'val_loss', # Use accuracy to monitor the model
            patience = 1 # Stop after one step with lower accuracy
        ),
        keras.callbacks.ModelCheckpoint(
            filepath = filepath, # file where the checkpoint is saved
            monitor = 'val_loss', # Don't overwrite the saved model unless val_loss is worse
            save_best_only = True # Only save model if it is the best
        )
]
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu', kernel_regularizer=l2(0.001)))
model.add(Dropout(0.5))
model.add(layers.Dense(10, activation='softmax'))
model.summary()
## Compile the model
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])

## Now fit the model
nr.seed(2356)
set_random_seed(2333)
history = model.fit(train_images, train_labels, epochs=40, batch_size = 128, callbacks = callbacks_list, validation_data = (test_images, test_labels))  # Call backs argument here)

并得到以下错误:

ValueError: Error when checking target: expected dense_5 to have shape (None, 1) but got array with shape (60000, 10)

我之前看到的关于数据标签的帖子应该转换为分类数据,但已经完成了。实际上大部分代码都是从张量流教程中复制过去的,所以很难看出哪里出了问题。

【问题讨论】:

    标签: python-3.x tensorflow keras conv-neural-network


    【解决方案1】:

    使用损失函数 categorical_crossentropy

    loss='categorical_crossentropy'

    因为您的标签编码在

    train_labels = ku.to_categorical(train_labels)

    PS。 如果您的标签是 endcoded(one-hot 编码),请使用 categorical_crossentropy 例如:

    [1,0,0] [0,1,0] [0,0,1]

    但如果您的目标是整数,请使用 sparse_categorical_crossentropy 例如:

    [1,2,3]

    【讨论】:

    • 这里有更多背景知识或您认为这是正确方法的原因吗?
    • 如果你的标签是 endcoded(one-hot 编码)使用 categorical_crossentropy 但是如果你的目标是整数,使用 sparse_categorical_crossentropy
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 2020-12-20
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多