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 submodule ) but in 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 is 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 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 high-level library and does not provide full control on code. In the opposite place, TensorFlow 1.0 version, we can create session and layer 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 –
The above error has also the same base root cause. Everywhere we import Keras standalone module in the place of TensorFlow module, we get this error. Anyways give 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.