为什么“metrics=tf.keras.metrics.accurity()”会给出错误,而“metrics=['accurity']”不会给出错误?

2024-05-17 03:19:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在fashion_mnist数据集上使用给定的代码示例。它包含metrics="accuracy"并贯穿。每当我将其更改为metrics=tf.keras.metrics.Accuracy()时,它会给出以下错误:

ValueError: Shapes (32, 10) and (32, 1) are incompatible

我做错了什么?Accuracy()函数是否不同

import tensorflow as tf

fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
train_images = train_images / 255.
test_images = test_images / 255.

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation=tf.keras.activations.relu),
    tf.keras.layers.Dense(10)])

model.compile(
    optimizer=tf.keras.optimizers.Adam(),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=['accuracy'])


model.fit(train_images, train_labels, epochs=10)

Tags: 数据testlabelsmodellayerstftrainkeras
1条回答
网友
1楼 · 发布于 2024-05-17 03:19:57

根据文件here

When you pass the strings "accuracy" or "acc", we convert this to one of tf.keras.metrics.BinaryAccuracy, tf.keras.metrics.CategoricalAccuracy, tf.keras.metrics.SparseCategoricalAccuracy based on the loss function used and the model output shape.

因此,当您传递"accuracy"时,它将自动转换为SparseCategoricalAccuracy()

因此,您可以按如下方式传递它:

model.compile(
    optimizer=tf.keras.optimizers.Adam(),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])
# or
model.compile(
    optimizer=tf.keras.optimizers.Adam(),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=['accuracy'])

相关问题 更多 >