Nameerror name keras is not defined

The nameerror name keras is not defined error message usually experienced when working with Python.

It happens when a Python script tries to use a name that was not defined or imported.

So, if this is your case, keep on reading!

This article discusses how to fix the nameerror: name ‘keras’ is not defined error message.

You will also understand why this error appeared in your code.

What is keras ?

Keras is a deep learning API, written in Python and capable of running on top of the machine learning platform TensorFlow, CNTK, or Theano.

In addition to that, keras library provides essential abstractions and building blocks for developing and shipping machine learning solutions with high iteration velocity.

What is “nameerror: name ‘keras’ is not defined”?

The nameerror name ‘keras’ is not defined occurs when you’re trying to use the keras library without importing it first, or there are some instances that you did not install the library.

For example:

import tensorflow as tf
import numpy as np

# Load the MNIST dataset
mnist = keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# Preprocess the data
x_train = x_train.reshape(60000, 784).astype('float32') / 255.0
x_test = x_test.reshape(10000, 784).astype('float32') / 255.0
y_train = keras.utils.to_categorical(y_train)
y_test = keras.utils.to_categorical(y_test)

# Define and compile the model
model = keras.Sequential([
    keras.layers.Dense(10, activation='relu', input_shape=(784,)),
    keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

# Train the model
model.fit(x_train, y_train, epochs=5, batch_size=32, verbose=1)

# Evaluate the model
loss, accuracy = model.evaluate(x_test, y_test, verbose=0)
print('Test accuracy:', accuracy)

As a result, it throws a NameError indicating that the name ‘keras’ is not defined.

This error indicates that you’re trying to use a variable or function named keras, but Python do not know what keras is because it is not defined or imported.

Why does “nameerror name keras is not defined” occur?

This error message can occur due to several reasons, such as:

Keras is not installed on your system.

❌ Forget to import the keras library.

❌ Misspelled the name of the library when trying to import it.

How to fix the “nameerror name keras is not defined”?

To fix the nameerror: name ‘keras’ is not defined, ensure that you have installed the keras library and imported it correctly in your code.

Here are the different ways where it can help you to resolve the error.

Solution 1: Install Keras

When you haven’t installed the Keras library yet on your system, you will need to do so before you can use it in your Python code.

You can easily install Keras using “pip” or “conda,” depending on Python environment you are currently using.

Here’s an example using pip:

pip install keras

You can also use pip3 if you are using Python 3.

pip3 install keras

To install Keras in a Conda environment, you have to execute the following steps:

  1. Open your terminal or Anaconda Prompt and you have to activate your desired Conda environment.
✅ conda activate my_environment

  1. Install the TensorFlow package, which is required for Keras.
✅ conda install tensorflow

  1. Now, you can simply install Keras using pip within your Conda environment.
✅ pip install keras

Solution 2: Import Keras

After successfully installing the keras, you may now use it, you just have to ensure that you have imported the keras library correctly in your code.

You can do this by adding the line from tensorflow import keras at the top or beginning of your Python script.

 from tensorflow import keras

Here’s the complete code:

import tensorflow as tf
✅ from tensorflow import keras
import numpy as np

# Load the MNIST dataset
mnist = keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# Preprocess the data
x_train = x_train.reshape(60000, 784).astype('float32') / 255.0
x_test = x_test.reshape(10000, 784).astype('float32') / 255.0
y_train = keras.utils.to_categorical(y_train)
y_test = keras.utils.to_categorical(y_test)

# Define and compile the model
model = keras.Sequential([
    keras.layers.Dense(10, activation='relu', input_shape=(784,)),
    keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

# Train the model
model.fit(x_train, y_train, epochs=5, batch_size=32, verbose=1)

# Evaluate the model
loss, accuracy = model.evaluate(x_test, y_test, verbose=0)
print('Test accuracy:', accuracy)

Output:

Epoch 1/5
1875/1875 [==============================] - 2s 969us/step - loss: 0.4932 - accuracy: 0.8615
Epoch 2/5
1875/1875 [==============================] - 2s 960us/step - loss: 0.2905 - accuracy: 0.9183
Epoch 3/5
1875/1875 [==============================] - 2s 955us/step - loss: 0.2671 - accuracy: 0.9251
Epoch 4/5
1875/1875 [==============================] - 2s 952us/step - loss: 0.2531 - accuracy: 0.9286
Epoch 5/5
1875/1875 [==============================] - 2s 952us/step - loss: 0.2408 - accuracy: 0.9325
Test accuracy: 0.9337000250816345

Solution 3: Check for typos

Ensure that you haven’t misspelled the name of the keras library when you are trying to import it.

Conclusion

The nameerror name ‘keras’ is not defined occurs when you’re trying to use the keras library without importing it first, or there are some instances that you did not install the library.

This article explores what this error is all about and already provides solutions to help you fix this error.

You could also check out other “nameerror” articles that may help you in the future if you encounter them.

We are hoping that this article helps you fix the error. Thank you for reading itsourcecoders 😊

Leave a Comment