keras.utils.to_categorical() - name keras not defined

Viewed 70749

I am running the test script from the Keras website for Multilayer Perceptron (MLP) for multi-class softmax classification. Running in the jupyter notebook I get the error "name 'keras' is not defined". This may be a simple python syntax problem that I am not keen to, however this code comes straight from keras so I expect it should work as is. I have run other neural nets using keras, so I am pretty sure that I have installed everything (installed keras using anaconda). Can anyone help? I have included both the code and the error at the bottom. Thanks!

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

# Generate dummy data
import numpy as np
x_train = np.random.random((1000, 20))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(1000, 1)), num_classes=10)
x_test = np.random.random((100, 20))
y_test = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)

model = Sequential()
# Dense(64) is a fully-connected layer with 64 hidden units.
# in the first layer, you must specify the expected input data shape:
# here, 20-dimensional vectors.
model.add(Dense(64, activation='relu', input_dim=20))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
              optimizer=sgd,
              metrics=['accuracy'])

model.fit(x_train, y_train,
          epochs=20,
          batch_size=128)
score = model.evaluate(x_test, y_test, batch_size=128)

This is the error message:

NameError                                 Traceback (most recent call last)
<ipython-input-1-6d8174e3cf2a> in <module>()
      6 import numpy as np
      7 x_train = np.random.random((1000, 20))
----> 8 y_train = keras.utils.to_categorical(np.random.randint(10, size=(1000, 1)), num_classes=10)
      9 x_test = np.random.random((100, 20))
     10 y_test = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)

NameError: name 'keras' is not defined
4 Answers

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.]

Although this is an old question but yet updating the latest approach to access to_categorical function.

This function has now been packed in np_utils.

The correct way to access it is:

from keras.utils.np_utils import to_categorical

This works for me:

import tensorflow as tf
from keras import utils as np_utils 

 y_train =  tf.keras.utils.to_categorical(y_train, num_classes)
 y_test = tf.keras.utils.to_categorical(y_test, num_classes)
Related