Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

keras

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
like image 722
xjtc55 Avatar asked May 18 '17 17:05

xjtc55


2 Answers

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
like image 87
R.K Avatar answered Sep 21 '22 22:09

R.K


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
like image 40
Mo... Avatar answered Sep 19 '22 22:09

Mo...