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 😊

Frequently Asked Questions

What is Python NameError and what causes it?

NameError is raised when Python encounters a name (variable, function, class) that hasn’t been defined in the current scope. Most common causes: typo in variable name, using a variable before assigning it, missing import, or referencing a variable that was defined inside a function but accessed outside it.

How do I fix ‘name X is not defined’?

Check three things: (1) Is the name a typo? Compare with the spelling where you defined it. (2) Did you import it? Add ‘from module import X’ or ‘import module’ at the top. (3) Is X defined in a different scope (inside a function, conditional branch, or with-block) that hasn’t executed yet at the point you’re using it? Move the definition before the use.

Why does my variable work in one cell but not another (Jupyter)?

Jupyter kernels keep state between cells. If you defined X in cell 5 and run cell 3 later, X exists. But after Kernel-Restart, only the cells you re-run define their variables. Always run cells top-to-bottom on a fresh kernel before submitting. Use ‘Restart and Run All’ to verify your notebook is reproducible.

What is the difference between NameError and AttributeError?

NameError: the name itself doesn’t exist anywhere in scope (typo, missing import, scope issue). AttributeError: the name exists and points to an object, but that object has no such attribute/method (typo on method name, wrong object type). NameError is about the variable; AttributeError is about what’s inside it.

Where can I find more NameError fixes?

Browse the NameError reference hub for 49+ specific fixes (NumPy, pandas, Jupyter, Python 2 to 3 migration). For Python scope rules see the Python Tutorial hub. For attribute-level errors see AttributeError.

Caren Bautista

Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel  · View all posts by Caren Bautista →

Leave a Comment