How to Resolve Python Keras/TensorFlow Error "ImportError: cannot import name ..." for "pad_sequences" and "load_img"
When working with Keras for deep learning, particularly with newer versions of TensorFlow (which now fully integrates Keras), you might encounter ImportError
or AttributeError
messages like cannot import name 'pad_sequences' from 'keras.preprocessing.sequence'
or module 'keras.preprocessing.image' has no attribute 'load_img'
. These errors indicate that you are trying to import these utilities from their older, now deprecated, locations within the standalone Keras or older Keras-within-TensorFlow structure.
This guide explains these import path changes and provides the correct, modern import statements for TensorFlow 2.x and later.
Understanding the Error: Keras API Relocation in TensorFlow 2.x
Keras, originally a standalone high-level API for neural networks, became the official high-level API for TensorFlow starting with TensorFlow 2.0.0. This integration led to a restructuring of how Keras components are accessed. Many utilities that were previously in modules like keras.preprocessing
have been moved or are now primarily accessed through the tensorflow.keras
namespace.
Using import paths from the older, standalone Keras structure (e.g., from keras.preprocessing...
) with modern TensorFlow installations (TF 2.x and above) will lead to ImportError
or AttributeError
because those specific paths no longer exist or are deprecated.
Error: cannot import name 'pad_sequences' from 'keras.preprocessing.sequence'
- Error Message Example:
ImportError: cannot import name 'pad_sequences' from 'keras.preprocessing.sequence' (.../keras/preprocessing/sequence.py)
- Cause: You are trying to import
pad_sequences
using the old path from a standalone Keras or an older TensorFlow version's Keras API.
Solution: Import from tensorflow.keras.utils
(Recommended)
In modern TensorFlow (TF 2.x+), pad_sequences
is available under tensorflow.keras.utils
.
# ⛔️ Old, incorrect import (causes error with modern TensorFlow)
# from keras.preprocessing.sequence import pad_sequences
# ✅ Correct import for modern TensorFlow/Keras
from tensorflow.keras.utils import pad_sequences
# Example usage (assuming you have sequences to pad)
sequences = [[1, 2, 3], [4, 5], [6]]
padded_sequences = pad_sequences(sequences, padding='post', maxlen=5)
print("pad_sequences function object:", pad_sequences)
print("\nPadded Sequences:")
print(padded_sequences)
This is the standard and recommended way to access pad_sequences
.
Alternative (Older): Import from keras_preprocessing.sequence
The keras_preprocessing
package was a separate utility library that Keras used. While pad_sequences
might exist there, it's generally better to use the official tensorflow.keras.utils
path for better integration and future compatibility.
# Alternative, but prefer tensorflow.keras.utils
from keras_preprocessing.sequence import pad_sequences
print(pad_sequences)
If this works, it might indicate an older environment setup or specific dependencies. Prioritize tensorflow.keras.utils
.
Error: AttributeError: module 'keras.preprocessing.image' has no attribute 'load_img'
or ImportError: cannot import name 'load_img' from 'keras.preprocessing.image'
- Error Message Examples:
AttributeError: module 'keras.preprocessing.image' has no attribute 'load_img'
ImportError: cannot import name 'load_img' from 'keras.preprocessing.image' (.../keras/preprocessing/image.py) - Cause: You are trying to access
load_img
via the oldkeras.preprocessing.image
module, which is deprecated or doesn't exposeload_img
directly in this manner in modern TensorFlow.
Solution: Import from tensorflow.keras.utils
(Recommended)
Similar to pad_sequences
, load_img
is now found in tensorflow.keras.utils
.
import numpy as np # For example usage
# ⛔️ Old, incorrect import (causes error with modern TensorFlow)
# from keras.preprocessing.image import load_img
# Or trying:
# from keras.preprocessing import image
# img = image.load_img(...)
# ✅ Correct import for modern TensorFlow/Keras
from tensorflow.keras.utils import load_img, img_to_array
# Example usage (replace 'your_image.jpg' with an actual image path)
image_path = 'your_image.jpg'
try:
# Create a dummy image for testing if you don't have one
from PIL import Image
dummy_img = Image.new('RGB', (60, 30), color = 'red')
dummy_img.save(image_path)
img = load_img(
image_path,
target_size=(100, 100), # Example target size
color_mode="rgb" # Example color mode
)
print("load_img function object:", load_img)
print(f"\nLoaded image type: {type(img)}")
# Convert PIL image to NumPy array for Keras model input
img_array = img_to_array(img)
print(f"Image array shape: {img_array.shape}")
except FileNotFoundError:
print(f"Error: Image file not found at '{image_path}'. Please provide a valid path.")
except Exception as e:
print(f"An error occurred: {e}")
Always import load_img
directly from tensorflow.keras.utils
.
General Rule: Prefer tensorflow.keras
Imports
As a general guideline when working with TensorFlow 2.x and newer: always try to import Keras components from the tensorflow.keras
namespace first.
- Old Style (Avoid):
import keras
from keras.layers import Dense
from keras.models import Sequential
from keras.preprocessing import sequence, image - New Style (Preferred):
from tensorflow import keras # Access general Keras API via tf.keras
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.utils import pad_sequences, load_img
# For ImageDataGenerator (if needed, though tf.data is often preferred now):
# from tensorflow.keras.preprocessing.image import ImageDataGenerator
Solution for Persistent Issues: Upgrade TensorFlow and Keras
Outdated versions of tensorflow
or keras
(if you somehow have a standalone Keras installed alongside an older TensorFlow) can cause these import issues or hide the correct paths. Ensure you are using up-to-date versions.
pip install --upgrade tensorflow keras
# Or use pip3 / python -m pip etc.
# For Conda environments:
conda install -c conda-forge tensorflow keras # Or update
keras
as a separate pip package mainly refers to Keras 3 which supports multiple backends. If using TensorFlow as the backend, tensorflow
itself includes the Keras API.
Troubleshooting: Upgrade All Packages (Use with Caution)
In complex environments, conflicts might arise from multiple outdated packages. While sometimes risky, upgrading all packages might resolve transitive dependency issues related to Keras and TensorFlow APIs.
-
Method 1: Using pip-review (install first: pip install pip-review)
pip-review --auto
-
Method 2: Script (use with extreme caution - test thoroughly!)
import pkg_resources
from subprocess import call
packages = [dist.project_name for dist in pkg_resources.working_set]
print(f"Attempting to upgrade: {' '.join(packages)}")
call("pip install --upgrade " + ' '.join(packages), shell=True)
Recommendation: Prefer upgrading TensorFlow and Keras specifically (Solution 5). Only resort to upgrading everything if specific upgrades fail and you understand the potential risks of breaking other dependencies. Always use a virtual environment.
Conclusion
ImportError
s or AttributeError
s for Keras utilities like pad_sequences
and load_img
typically mean you are using outdated import paths not compatible with modern TensorFlow 2.x (which bundles Keras).
The primary solution is to update your import statements to use the tensorflow.keras
namespace:
- For
pad_sequences
:from tensorflow.keras.utils import pad_sequences
- For
load_img
:from tensorflow.keras.utils import load_img
Always prefer importing Keras components via tensorflow.keras...
when working with TensorFlow 2 and above. Keeping your tensorflow
package up-to-date is also crucial for accessing the latest API structures.