12

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
2
  • 3
    Maybe import keras? Or from keras.utils import to_categorical? Commented May 18, 2017 at 17:24
  • @devforfu Both work! Please post as an answer I can image I wont be the only one having this problem. Commented May 18, 2017 at 17:29

4 Answers 4

25
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
Sign up to request clarification or add additional context in comments.

1 Comment

Adding tensorflow. keyword before all keras es, solved all the errors for me, in Tensorflow 2.
10

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

Comments

8

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

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.