Tensorflow – Received a label value of 99 which is outside the valid range of [0, 10)

Issue

I was trying to make a cifar100 model. When I was beginning to train the model, I got this error

Node: ‘sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits’
Received a label value of 99 which is outside the valid range of [0, 10). Label values: 1 47 23 85 26 78 60 78 26 85 11 13 24 60 1 65 97 7 14 59 20 35 94 65 79 43 24 78 47 41 0 91 56 2 63 78 32 96 87 32 62 71 2 16 79 60 61 37 82 92 28 55 7 71 14 14 85 69 12 48 3 26 18 26 96 69 10 34 28 96 88 13 99 17 69 65 12 92 46 89 41 93 23 13 2 93 87 83 72 27 49 7 65 48 39 73 51 79 22 22
[[{{node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]] [Op:__inference_train_function_657]

My code is

import tensorflow as tf
import tensorflow.keras.datasets as datasets
import numpy as np
import matplotlib.pyplot as plt

dataset = datasets.cifar100

(training_images, training_labels), (validation_images, validation_labels) = dataset.load_data()

training_images = training_images / 255.0
validation_images = validation_images / 255.0

model = tf.keras.Sequential([
                                    tf.keras.layers.Flatten(input_shape=(32,32,3)),
                                    tf.keras.layers.Dense(500, activation='relu'),
                                    tf.keras.layers.Dense(300, activation='relu'),
                                    tf.keras.layers.Dense(10, activation= 'softmax')
                                    ])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(),
              metrics=['accuracy'])

history = model.fit(training_images,
                    training_labels,
                    batch_size=100,
                    epochs=10,
                    validation_data = (validation_images, validation_labels)
                    )

I am on Ubuntu 22.04

Solution

Your dataset is made up of 100 different classes and not 10, hence the 100 in "cifar100". So just change this line in your code:

 tf.keras.layers.Dense(100, activation= 'softmax')

and it will work.

Answered By – AloneTogether

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published