Search code examples
tensorflowmachine-learningkerasmulticlass-classificationtf.keras

How can I define custom labels value when using sparse_categorical_crossentropy?


my model is compiled with this code

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['sparse_categorical_accuracy'])

During training, I got this error

tensorflow.python.framework.errors_impl.InvalidArgumentError: Received a label value of 5 which is outside the valid range of [0, 5).

My label are 1,2,3,4,5 which is [1,5] not [0, 5). How can I set labels for this model?


Solution

  • You need to encode your labels into [0, 4], which is zero-based, not one-based. This is because to recover class indices, the argmax function is used, for which the array index corresponding to the maximum value is returned, which will be zero-based.