Fix ModuleNotFoundError: No Module Named ‘tensorflow.keras.utils.np_utils’

When I was working on a deep learning project last week, I encountered a frustrating error: ModuleNotFoundError: No module named ‘tensorflow.keras.utils.np_utils’. This error typically appears when you’re trying to use the older TensorFlow 1.x syntax in a TensorFlow 2.x environment.

In this article, I’ll show you exactly how to fix this common error with several practical solutions. I’ve been working with TensorFlow for over 8 years, and this is one of the most frequent migration issues I see developers struggle with.

Let’s get into how you can resolve this issue and get your deep learning models working properly.

The Error

The error ModuleNotFoundError: No module named 'tensorflow.keras.utils.np_utils' occurs because of a structural change in TensorFlow 2.x. In TensorFlow 1.x, you could access this module, but in TensorFlow 2.x, the location has changed.

This typically happens when:

  • You’re using code written for TensorFlow 1.x in a TensorFlow 2.x environment
  • You’re following an outdated tutorial
  • You’ve upgraded TensorFlow but haven’t updated your code

Solution 1: Update Your Import Statement

The simplest solution is to update your import statement to use the correct path in TensorFlow 2.x.

Old code (TensorFlow 1.x):

from tensorflow.keras.utils import np_utils

New code (TensorFlow 2.x):

from tensorflow.keras.utils import to_categorical

Here’s a complete example showing how to convert class labels to one-hot encoded format:

import numpy as np
from tensorflow.keras.utils import to_categorical

# Example data - let's say we're classifying US states by region (0-3)
# 0: Northeast, 1: Midwest, 2: South, 3: West
state_regions = np.array([2, 3, 0, 1, 2, 3, 0, 1])

# Convert to one-hot encoding
one_hot_regions = to_categorical(state_regions)
print(one_hot_regions)

The output will be:

[[0. 0. 1. 0.]
 [0. 0. 0. 1.]
 [1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]
 [1. 0. 0. 0.]
 [0. 1. 0. 0.]]

You can see the output in the screenshot below.

modulenotfounderror no module named 'keras.utils.np_utils'

Read AttributeError: Module ‘tensorflow’ has no attribute ‘sparse_tensor_to_dense’

Solution 2: Use tf.keras Instead of keras

If you’re working in a TensorFlow 2.x environment, it’s generally recommended to use tf.keras rather than standalone keras. This ensures compatibility and access to the latest TensorFlow features.

import tensorflow as tf

# Sales performance categories: 0 = Poor, ..., 3 = Excellent
sales_performance = tf.constant([1, 3, 2, 0, 3, 1])

# Define number of categories (0, 1, 2, 3 → 4 classes)
num_classes = 4

# One-hot encode with explicit num_classes
one_hot_sales = tf.keras.utils.to_categorical(sales_performance, num_classes=num_classes)

# Print result
print(one_hot_sales) 

The output will be:

[[0. 1. 0. 0.]
 [0. 0. 0. 1.]
 [0. 0. 1. 0.]
 [1. 0. 0. 0.]
 [0. 0. 0. 1.]
 [0. 1. 0. 0.]], shape=(6, 4), dtype=float32)

You can see the output in the screenshot below.

modulenotfounderror no module named 'keras.utils.vis_utils'

Check out Module ‘tensorflow’ has no attribute ‘sparse_placeholder’

Solution 3: Install the Correct TensorFlow Version

If you need to use the old syntax, you can install TensorFlow 1.x. However, I strongly recommend updating your code instead, as TensorFlow 1.x is no longer actively maintained.

# Install TensorFlow 1.15 (not recommended for new projects)
pip uninstall tensorflow
pip install tensorflow==1.15

Then you could use the old syntax:

from tensorflow.keras.utils import np_utils

# Example data
categories = [0, 1, 2, 0, 1]

# Using old np_utils
one_hot = np_utils.to_categorical(categories)

Read Module ‘tensorflow’ has no attribute ‘optimizers’

Solution 4: Use NumPy Directly

If you just need one-hot encoding functionality, you can implement it directly with NumPy:

import numpy as np

def to_categorical(y, num_classes=None):
    """Convert a class vector to binary class matrix."""
    y = np.array(y, dtype='int')
    input_shape = y.shape

    # Determine the number of classes
    if num_classes is None:
        num_classes = np.max(y) + 1

    # Convert to one-hot encoding
    categorical = np.zeros((len(y), num_classes))
    categorical[np.arange(len(y)), y] = 1

    return categorical

# Example with US city population sizes (0-3)
# 0: Small, 1: Medium, 2: Large, 3: Metropolitan
city_sizes = np.array([1, 3, 2, 0, 3, 1])
one_hot_cities = to_categorical(city_sizes)
print(one_hot_cities)

The output will be:

[[0. 1. 0. 0.]
 [0. 0. 0. 1.]
 [0. 0. 1. 0.]
 [1. 0. 0. 0.]
 [0. 0. 0. 1.]
 [0. 1. 0. 0.]]

You can see the output in the screenshot below.

cannot import name 'np_utils' from 'keras.utils'

Check out Module ‘tensorflow’ has no attribute ‘log’

Solution 5: Check for Conflicting Keras Installations

Sometimes this error occurs because you have multiple Keras installations that conflict with each other.

# Check TensorFlow version
import tensorflow as tf
print(f"TensorFlow version: {tf.__version__}")

# Check if you have standalone Keras installed
try:
    import keras
    print(f"Standalone Keras version: {keras.__version__}")
    print("Consider uninstalling standalone Keras if using TensorFlow 2.x")
except ImportError:
    print("No standalone Keras installed (this is good for TensorFlow 2.x)")

If you have standalone Keras installed and you’re using TensorFlow 2.x, you might want to uninstall it:

pip uninstall keras

Read AttributeError: Module ‘tensorflow’ has no attribute ‘global_variables_initializer’

Best Practices to Avoid This Error

  1. Check TensorFlow Version: Always verify which version of TensorFlow you’re using.
  2. Use Up-to-Date Documentation: The official TensorFlow documentation is your best resource for the correct API usage.
  3. Use Virtual Environments: Create separate environments for projects that use different TensorFlow versions.
  4. Migrate Legacy Code Properly: If you’re updating an old project, follow the TensorFlow migration guide.

When I’m working on machine learning projects, I always make sure to check the version compatibility first. This simple practice has saved me countless debugging hours, especially when working with libraries that evolve as rapidly as TensorFlow.

Real-World Application Example

Let’s say you’re building a model to classify US customer sentiment based on product reviews:

import tensorflow as tf
import numpy as np

# Example customer review sentiment data (0: Negative, 1: Neutral, 2: Positive)
sentiments = np.array([1, 2, 0, 0, 1, 2, 2, 1])

# Convert to one-hot encoding
one_hot_sentiments = tf.keras.utils.to_categorical(sentiments)

# Create a simple model
model = tf.keras.Sequential([
    tf.keras.layers.Dense(16, activation='relu', input_shape=(one_hot_sentiments.shape[1],)),
    tf.keras.layers.Dense(8, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax')
])

# Compile the model
model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

print("Model successfully created with correct one-hot encoding!")

When working with TensorFlow, always try to follow the most current API patterns. This will not only prevent errors like the ModuleNotFoundError for np_utils, but also ensure your code is more maintainable and efficient.

In my experience, staying updated with the latest recommended practices is much easier than fixing compatibility issues later. If you encounter this error, simply update your import statements as shown in this article, and you’ll be back to developing your machine learning models in no time.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.