我在一个基本的CNN中遇到了这个错误:
AttributeError: 'SparseCategoricalCrossentropy' object has no attribute 'name'
我以为你可以在model.compile()
中设置loss=tf.metrics.SparseCategoricalCrossentropy()
import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np
import matplotlib.pyplot as plt
tf.random.set_seed(42)
train, test = tfds.load('fashion_mnist', split=['train', 'test'], as_supervised=True)
train = train.map(lambda x, y: (tf.divide(x, 255), y)).batch(8)
test = test.map(lambda x, y: (tf.divide(x, 255), y)).batch(8)
custom_model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, kernel_size=3, activation='relu'),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
tf.keras.layers.Conv2D(64, kernel_size=3, activation='relu'),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')])
custom_model.compile(loss=tf.metrics.SparseCategoricalCrossentropy(),
optimizer=tf.optimizers.Adam(),
metrics=[tf.metrics.SparseCategoricalAccuracy()])
early_stopping = [tf.keras.callbacks.EarlyStopping(patience=5)]
conv_dropout_history = custom_model.fit(train, validation_data=test,
epochs=100, callbacks=early_stopping)
是否有任何方法在model.compile()
中使用这个对象,或者我应该只使用tf.metrics.sparse_categorical_crossentropy
(或字符串形式)?
你正在使用度量作为损失函数。
尝试替换这个:
tf.metrics.SparseCategoricalCrossentropy()
与这个:
tf.keras.losses.SparseCategoricalCrossentropy()
度量不能被Keras优化器最小化,所以你必须使用损失函数。