cannot import name ‘to_categorical’ from ‘keras.utils’

Total
0
Shares
cannot import name 'to_categorical' from 'keras.utils' python tensorflow error

Python Tensorflow throws error “cannot import name ‘to_categorical’ from ‘keras.utils’” when you are using Tensorflow version 2 but implementing the older syntax.

Solution

Instead of using this syntax for importing keras library –

from keras.utils import to_categorical

use this syntax –

from tf.keras.utils import to_categorical

Why this error occurred?

Because when Tensorflow upgraded from V1 to V2, Keras library got integrated into it too. So, in order to access to_categorical form keras.utils, we need to use tf.keras.utils.

Code Example

from tf.keras.utils import to_categorical

a = to_categorical([0, 1, 2, 3], num_classes=4)
a = tf.constant(a, shape=[4, 4])
print(a)

The output of above code will be –

tf.Tensor(
  [[1. 0. 0. 0.]
   [0. 1. 0. 0.]
   [0. 0. 1. 0.]
   [0. 0. 0. 1.]], shape=(4, 4), dtype=float32)

Conclusion

keras is the part of tensorflow library from version 2. So, to access any method within it, we need to use tf.keras now.