将 tf.keras.metrics.Precision 添加到 TensorFlow 中的模型指标时出现 ValueError

问题描述 投票:0回答:1

我正在尝试使用 MobileNet 在自定义数据集上应用迁移学习。我的代码工作正常,直到我将 tf.keras.metrics.Precision(name=" precision") 添加到模型的指标中。添加此指标后,我在 model.fit 期间遇到以下错误:

update_confusion_matrix_variables y_pred.shape.assert_is_compatible_with(y_true.shape) ValueError: Shapes (None, 4) and (None, 1) are incompatible 

相关代码块:

import tensorflow as tf
from tensorflow.keras.utils import image_dataset_from_directory as get_dataset

img_size = (224, 224)
preprocessing_layer = tf.keras.applications.mobilenet.preprocess_input
img_shape = img_size + (3,)

base_model = tf.keras.applications.MobileNet(
    input_shape=img_shape,
    include_top=False,
    weights='imagenet',
)

batch_size = 32
train_set = get_dataset(
    'some path',
    shuffle=True,
    batch_size=batch_size,
    image_size=img_size,
)

class_names = train_set.class_names
num_classes = len(class_names)

base_model.trainable = False
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()

inputs = tf.keras.Input(shape=img_shape)
k = preprocessing_layer(inputs)
k = base_model(k, training=False)
k = global_average_layer(k)
k = tf.keras.layers.Dropout(0.2)(k)

prediction_layer = tf.keras.layers.Dense(
    num_classes,
    activation="softmax"
)
outputs = prediction_layer(k)

model = tf.keras.Model(inputs, outputs)

model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(),
    metrics=[
        tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'),
        tf.keras.metrics.Precision(name="precision"),
    ]
)

AUTOTUNE = tf.data.AUTOTUNE

train_set = train_set.prefetch(buffer_size=AUTOTUNE)

epochs = 1
history = model.fit(
    train_set,
    epochs=epochs,
)

数据集被组织成子目录,其中每个子目录名称是类标签。有四个类别标签。

数据集加载和预处理似乎工作正常,因为模型在没有

tf.keras.metrics.Precision
指标的情况下进行训练。

这个问题在添加精度指标时特别出现。

出于实验目的,特意将

epochs
设置为
1

tensorflow precision tf.keras
1个回答
0
投票

问题是您的类标签稀疏,并且

Precision
无法使用它。最简单的解决方法是对标签进行一次性编码,并将稀疏损失和度量更改为非稀疏版本。

你可以改变

train_set = get_dataset(
    'some path',
    shuffle=True,
    batch_size=batch_size,
    image_size=img_size,
)
""" [more code from you ...] """

model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(),
    metrics=[
        tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'),
        tf.keras.metrics.Precision(name="precision"),
    ]
)

train_set = get_dataset(
    'some path',
    label_mode='categorical',
    shuffle=True,
    batch_size=batch_size,
    image_size=img_size,
)
""" [more code from you ...] """

model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
    loss=tf.keras.losses.CategoricalCrossentropy(),
    metrics=[
        tf.keras.metrics.CategoricalAccuracy(name='accuracy'),
        tf.keras.metrics.Precision(name="precision"),
    ]
)

使用

label_mode='categorical'
,您可以获得 one-hot 编码标签,它适用于 keras 的大多数指标。您必须将损失和准确性更改为非稀疏版本,如上面的代码示例所示。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.