0
$\begingroup$

I am running a MNIST example in a Jupyter notebook running in an Anaconda virtual environment. I have tried to run the code below (not yet finished, I was testing it) when it comes up with an error (can be seen below the code).

(X_train, y_train), (X_test, y_test) = mnist.load_data()

#print("X_train shape", X_train.shape)
#print ("y_train shape", y_train.shape)
#print("X_test shape", X_test.shape)
#print ("y_test shape", y_test.shape)

from keras.models import Sequential #imports the sequential model
from keras.layers import Dense, Dropout, Conv2D, MaxPool2D
from keras.utils import np_utils

#flattens the images from the 28x28 pixels to 1D 787 pixels
X_train = X_train.reshape (60000, 784) #flattening the image into 28x28 pixels, so into an array of 784.
X_test = X_test.reshape (10000, 784)
X_train = X_train.astype('float32') #using a 32-bit precision when training the neural network. This is most commonly used.
X_test = X_test.astype('float32')

X_train /=255 #Used for normalisation. Each image has a 'degree' of darkness within the range of 0-255 so you need to reduce that range to 0-1 for your Neural Network
X_test /=255

#one-hot encoding using keras' numpy-related utilities
n_classes=10
print ("Shape before one-hot encoding: ", y_train.shape)
Y_train = np.utils.to_categorical(y_train, n_classes)
Y_test = np.utils.to_categorical(y_test, n_classes)
print ("Shape after one-hot encoding:", Y_train.shape)

Error:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-0063f366d5bd> in <module>
     22 n_classes=10
     23 print ("Shape before one-hot encoding: ", y_train.shape)
---> 24 Y_train = np.utils.to_categorical(y_train, n_classes)
     25 Y_test = np.utils.to_categorical(y_test, n_classes)
     26 print ("Shape after one-hot encoding:", Y_train.shape)

NameError: name 'np' is not defined

I guess I need to define np somewhere, but the practise code on the website I am using doesn't actually define np anywhere. Any suggestions?

Many thanks

$\endgroup$
1

1 Answer 1

1
$\begingroup$
Y_train = np_utils.to_categorical(y_train, n_classes)
Y_test = np_utils.to_categorical(y_test, n_classes)

please update code line as np_utils not np.utils

$\endgroup$
1
  • $\begingroup$ Excellent! Thank you. I'll accept the answer as it worked $\endgroup$
    – Jack
    Commented Mar 17, 2021 at 14:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.