Reputation: 192
Below image shows part of the code to train a simple deep CNN(Convolutional Neural Network), on CIFAR small images data set. I have imported, import keras.utils ( Highlighted in red)
However, I still get the below error:
Upvotes: 3
Views: 6721
Reputation: 458
Try importing np_utils
from keras.utils
and use like this
from keras.utils import np_utils
np_utils.to_categorical(y_train, num_classes)
Upvotes: 1
Reputation: 167
You're following a wrong practice of importing python modules. You should go for either of the following practices:
from keras.utils.np_utils import to_categorical
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)
OR
from keras.utils import np_utils
y_train = np_utils.to_categorical(y_train, num_classes)
y_test = np_utils.to_categorical(y_test, num_classes)
You can call only the module/function that you've imported. Say, if you use,
from keras.utils.np_utils import to_categorical
that means you're importing to_categorical function from keras.utils.np_utils package. So, you can only call to_categorical function. But you're trying to call keras.utils.to_categorical, which is not imported. Also, you can't directly import
to_categorical from utils without importing np_utils first.
Rule of thumb: If you type from X import Y, that means you've to call Y() as it is and not X.Y(). Doing that is redundant as well as wrong.
Tip: You don't need to mention num_classes as a parameter in to_categorical. Python interpreter will intelligently do that for you.
Upvotes: -1
Reputation: 11917
You can import to_categorical
in keras like shown below.
from keras.utils.np_utils import to_categorical
It can be used like shown below.
Y = [1, 2, 1, 2, 3, 4, 1]
Y = to_categorical(Y)
print(Y)
# output
array([[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.],
[0., 1., 0., 0., 0.]], dtype=float32)
Upvotes: 5