close

[Solved] keras.utils.to_categorical() – name keras not defined

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error keras.utils.to_categorical() – name keras not defined in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How keras.utils.to_categorical() – name keras not defined Error Occurs?

Today I get the following error keras.utils.to_categorical() – name keras not defined in python.

How To Solve keras.utils.to_categorical() – name keras not defined Error ?

  1. How To Solve keras.utils.to_categorical() – name keras not defined Error ?

    To Solve keras.utils.to_categorical() – name keras not defined Error import urllib does not necessarily import urllib.request because if there are so many big submodules, it's inefficient to import all of its submodules every time.

  2. keras.utils.to_categorical() – name keras not defined

    To Solve keras.utils.to_categorical() – name keras not defined Error import urllib does not necessarily import urllib.request because if there are so many big submodules, it's inefficient to import all of its submodules every time.

Solution 1

from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD

From above, you only imported following submodules in keras

  • keras.models
  • keras.layers
  • keras.optimizers

But this does not automatically import the outer module like keras or other submodules keras.utils

So, you can do either one

import keras
import keras.utils
from keras import utils as np_utils

but from keras import utils as np_utils is the most widely used.

Especially import keras is not a good practice because importing the higher module does not necessarily import its submodules (though it works in Keras)

For example,

import urllib does not necessarily import urllib.request because if there are so many big submodules, it’s inefficient to import all of its submodules every time.

EDIT: With the introduction of Tensorflow 2, keras submodules such as keras.utils should now be imported as

from tensorflow.keras import utils as np_utils

Solution 2


General way:

from keras.utils import to_categorical
Y_train = to_categorical(y_train, num_classes)

Concrete way:

from keras.utils import to_categorical

print(to_categorical(1, 2))
print(to_categorical(0, 2))

Will output

[0. 1.]
[1. 0.]

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read