keras
python
attributeerror
to_categorical
machine learning

AttributeError module 'keras.utils' has no attribute 'to_categorical'

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The error AttributeError: module 'keras.utils' has no attribute 'to_categorical' usually means your environment is not importing the Keras package you think it is. The fix is rarely about the one-hot encoding logic itself. It is usually about package versions, mixed namespaces, or a local file that shadows the real library.

What to_categorical Is Supposed To Do

to_categorical converts integer class labels into one-hot encoded vectors. For example, labels 0, 2, and 1 become rows such as [1, 0, 0], [0, 0, 1], and [0, 1, 0].

A normal TensorFlow-backed Keras example looks like this:

python
1import numpy as np
2from tensorflow.keras.utils import to_categorical
3
4labels = np.array([0, 2, 1, 2])
5encoded = to_categorical(labels, num_classes=3)
6
7print(encoded)

If that import fails or the attribute is missing, your Python environment needs attention.

The Most Common Cause: Mixed Keras Namespaces

Many projects accidentally mix two ecosystems:

  • 'keras, the standalone package'
  • 'tensorflow.keras, the Keras implementation bundled with TensorFlow'

In TensorFlow 2.x projects, the safest import is usually:

python
from tensorflow.keras.utils import to_categorical

That keeps all Keras symbols tied to the same TensorFlow installation. Problems start when one file imports layers from keras, another imports models from tensorflow.keras, and the environment contains incompatible versions of both.

Check What Python Is Actually Importing

Before reinstalling anything, inspect the active interpreter and module path:

python
1import keras
2import tensorflow as tf
3
4print("keras module:", keras.__file__)
5print("keras version:", getattr(keras, "__version__", "unknown"))
6print("tensorflow version:", tf.__version__)
7print("has to_categorical:", hasattr(keras.utils, "to_categorical"))

This tells you whether Python is loading the package from your virtual environment, from a global installation, or from an unexpected local file.

One especially common mistake is a project file named keras.py or a directory named keras. Python imports that local module first, so keras.utils is no longer the official package.

Use A Consistent Import Strategy

If you are training with TensorFlow 2.x, keep imports consistent:

python
1import tensorflow as tf
2from tensorflow.keras import layers, models
3from tensorflow.keras.utils import to_categorical
4
5x = tf.random.normal((4, 10))
6y = to_categorical([0, 1, 2, 1], num_classes=3)
7
8model = models.Sequential([
9    layers.Dense(16, activation="relu"),
10    layers.Dense(3, activation="softmax"),
11])
12
13model.compile(optimizer="adam", loss="categorical_crossentropy")
14model.fit(x, y, epochs=1, verbose=0)

Using one namespace from top to bottom removes a large class of import errors.

Alternative: Use tf.one_hot

If you only need one-hot encoding and want to avoid the utility function entirely, TensorFlow can do it directly:

python
1import tensorflow as tf
2
3labels = tf.constant([0, 2, 1, 2])
4encoded = tf.one_hot(labels, depth=3)
5
6print(encoded)

This is useful in data pipelines where you are already working with tensors and do not need a NumPy array.

Environment Cleanup Steps

If the attribute is still missing, clean up the environment deliberately:

  1. Activate the intended virtual environment.
  2. Remove conflicting installs if the project should use only TensorFlow-backed Keras.
  3. Reinstall the package set together.

Typical commands are:

bash
python -m pip uninstall keras tensorflow -y
python -m pip install tensorflow

If your project explicitly depends on standalone Keras, install and use that package consistently instead of mixing both import styles.

Common Pitfalls

The biggest mistake is naming a file keras.py or creating a local keras directory. That shadows the real package before you ever reach the correct import.

Another common issue is mixing keras imports with tensorflow.keras imports. Even if some imports work, the environment becomes much harder to reason about.

Developers also sometimes pass labels that are already one-hot encoded into to_categorical, which creates the wrong shape and hides the original import problem.

Finally, IDE interpreter mismatches are common. The package you installed may not be the interpreter your editor or notebook is actually using.

Summary

  • Start by importing to_categorical from tensorflow.keras.utils in TensorFlow-based projects.
  • Verify the actual module path before assuming the function was removed.
  • Keep all Keras imports in the same namespace to avoid mixed-version errors.
  • If needed, use tf.one_hot as a direct TensorFlow alternative.
  • Check for local module shadowing and wrong interpreters before reinstalling packages blindly.

Course illustration
Course illustration

All Rights Reserved.