Nicolas Gervais
Nicolas Gervais

Reputation: 36604

AttributeError: 'SparseCategoricalCrossentropy' object has no attribute '__name__'

I encountered this error in a basic CNN:

AttributeError: 'SparseCategoricalCrossentropy' object has no attribute 'name'

I thought you could set loss=tf.metrics.SparseCategoricalCrossentropy() in model.compile()?

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)

Is there any way to use this object in model.compile() or should I only ever use tf.metrics.sparse_categorical_crossentropy (or the string form)?

Upvotes: 0

Views: 665

Answers (1)

DapperDuck
DapperDuck

Reputation: 2876

You are using a metric as a loss function.

Try replacing this:

tf.metrics.SparseCategoricalCrossentropy()

With this:

tf.keras.losses.SparseCategoricalCrossentropy()

The metric can't be minimized by the Keras optimizer, so you have to use the loss function.

Upvotes: 1

Related Questions