importerror: cannot import name ‘to_categorical’ from ‘keras.utils’ error occurs because of importing keras.utils in the place of tensorflow.keras.utils package. In this article, we will understand this error in detail with context. We will also see the easiest way to fix this error.
Importerror: cannot import name ‘to_categorical’ from ‘keras.utils’ ( Cause ) –
TensorFlow has officially announced that Keras is a high-level library for deep learning in Tensorflow. Hence we can import Keras as a submodule in TensorFlow 2.0 version. But now the problem is .0developer or data scientist like you are taking some code reference of TensorFlow 2.0 (Keras as a submodule ) but in an import statement, they are using this syntax –
from keras.utils import to_categorical
cannot import name ‘to_categorical’ from ‘keras.utils’ ( Solution )-
The root cause itself is too clear to find the solution for this error. Here we will modify the import statement and import keras like below –
from tensorflow.keras.utils import to_categorical
If we run the above statement, It will not through any error. Let’s check with the output-
About TensorFlow 2.0 & Keras –
I Keras, we can build the neural network in 7-10 lines of code. This really helps data scientists to initiate model building in just one hour. But the only problem with Keras is that it is a high-level library and does not provide full control of code. In the opposite place, TensorFlow 1.0 version, we can create sessions and layers fully customize. Hence Google TensorFlow Team decided to officially take over the keras and provide the full solution in one package. That is TensorFlow 2.0 version.
Similar Error –
importerror: cannot import name ‘adam’ from ‘keras.optimizers’
importerror: cannot import name ‘normalize’ from ‘keras.utils’
The above error has also the same base root cause. Everywhere we import Keras standalone module in the place of the TensorFlow module, we get this error. Anyways give this a try at this article to understand the concept in depth.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.