Solving ImportError: cannot import name ‘to_categorical’ from ‘keras.utils’ (/usr/local/lib/python3.7/dist-packages/keras/utils/

When I started my work in Python, an error called ImportError: cannot import name ‘to_categorical’ from ‘keras.utils’ (/usr/local/lib/python3.7/dist-packages/keras/utils/ appeared and made the application fails.

The following article will help explain the problem and advise the possible solutions. Let’s start!

When the ImportError: cannot import name ‘to_categorical’ from ‘keras.utils’ (/usr/local/lib/python3.7/dist-packages/keras/utils/ occurs?

We received the following error from the import that used to run well a while ago before failing.

ImportError                               Traceback (most recent call last)
<ipython-input-33-4c52b67c20bf> in <module>()
      1 import keras
----> 2 from keras.utils import to_categorical
ImportError: cannot import name 'to_categorical' from 'keras.utils' (/usr/local/lib/python3.7/dist-packages/keras/utils/
NOTE: If your import fails due to a missing package, you can
manually install dependencies using either! pip or! apt.
To view examples of installing some common dependencies, click the
"Open Examples" button below.

Solve The Error

It would be best to import to_categorical from tensorflow.keras.utils when you want to apply it instead of keras.utils.

It would help if you tried to remove the following line from your application.

from keras.utils import to_categorical

Instead, you should use this command.

from tensorflow.keras.utils import to_categorical


The ImportError: cannot import name ‘to_categorical’ from ‘keras.utils’ (/usr/local/lib/python3.7/dist-packages/keras/utils/ is a relatively common error that can be caused by importing the wrong package.

The easiest way to solve it is to uninstall and reinstall keras.utils by adding tensorflow before the code. If you need further explanation, feel free to notify us. We will be happy to help you solve your problem. Thank you!

Scroll to Top