How to Fix AttributeError: module ‘keras.utils’ has no attribute ‘to_categorical’

AttributeError: module ‘keras.utils’ has no attribute ‘to_categorical’ error occurs when you try to “access the to_categorical from the keras.utils module, which does not exist in the latest version of TensorFlow.”

To fix the AttributeError: module ‘keras.utils’ has no attribute ‘to_categorical’ error, import to_categorical from keras.utils.np_utils module instead of the ‘keras.utils’ module.

Newer versions of keras==2.4.0 and tensorflow==2.3.0 would work as follows, so use

from keras.utils.np_utils import to_categorical

Then, you can use to_categorical in your code:

categorical_labels = to_categorical(int_labels, num_classes=None)

Please replace int_labels with your array of integer labels and num_classes with the total number of classes. If num_classes is None or not defined, then the number of classes will be inferred from the highest integer in int_labels.

That’s it.

Further reading

AttributeError: module ‘keras.utils’ has no attribute ‘plot_model’

AttributeError: module ‘keras.utils’ has no attribute ‘sequence’

AttributeError: module ‘keras.engine’ has no attribute ‘layer’

AttributeError: module ‘keras.preprocessing.image’ has no attribute ‘load_img’

AttributeError: module ‘keras.utils’ has no attribute ‘get_file’

AttributeError: module ‘keras.utils’ has no attribute ‘get_value’

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.