TheAlgorithms/Python · error · TypeError
Invalid image dtype {dtype!r}, expected uint8 or float32
Error message
Invalid image dtype {dtype!r}, expected uint8 or float32 What it means
Raised by the _DataSet constructor when the requested dtype, after being normalized through tf.compat.v1.dtypes.as_dtype, is neither uint8 nor float32. The dataset pipeline only supports these two output dtypes because MNIST pixels are natively uint8 and float32 is the only supported normalized ([0,1]) form. Any other NumPy or TensorFlow dtype is rejected with a TypeError.
Source
Thrown at neural_network/input_data.py:158
Args:
images: The images
labels: The labels
fake_data: Ignore inages and labels, use fake data.
one_hot: Bool, return the labels as one hot vectors (if True) or ints (if
False).
dtype: Output image dtype. One of [uint8, float32]. `uint8` output has
range [0,255]. float32 output has range [0,1].
reshape: Bool. If True returned images are returned flattened to vectors.
seed: The random seed to use.
"""
seed1, seed2 = random_seed.get_seed(seed)
# If op level seed is not set, use whatever graph level seed is returned
self._rng = np.random.default_rng(seed1 if seed is None else seed2)
dtype = dtypes.as_dtype(dtype).base_dtype
if dtype not in (dtypes.uint8, dtypes.float32):
msg = f"Invalid image dtype {dtype!r}, expected uint8 or float32"
raise TypeError(msg)
if fake_data:
self._num_examples = 10000
self.one_hot = one_hot
else:
assert images.shape[0] == labels.shape[0], (
f"images.shape: {images.shape} labels.shape: {labels.shape}"
)
self._num_examples = images.shape[0]
# Convert shape from [num examples, rows, columns, depth]
# to [num examples, rows*columns] (assuming depth == 1)
if reshape:
assert images.shape[3] == 1
images = images.reshape(
images.shape[0], images.shape[1] * images.shape[2]
)
if dtype == dtypes.float32:
# Convert from [0, 255] -> [0.0, 1.0].View on GitHub (pinned to f5988cc097)
Solutions
- Pass dtype=np.uint8 (pixel values 0-255) or dtype=np.float32 (values 0-1); these are the only supported values
- If you need another dtype, load with float32 and cast afterwards: images.astype(np.float64)
- Check for typos in the dtype string (e.g. 'float' instead of 'float32')
Example fix
# before
datasets = read_data_sets('/tmp/mnist', dtype=np.float64) # TypeError
# after
datasets = read_data_sets('/tmp/mnist', dtype=np.float32)
images64 = datasets.train.images.astype(np.float64) # cast later if needed Defensive patterns
Strategy: type-guard
Validate before calling
import numpy as np
VALID_DTYPES = (np.uint8, np.float32)
def check_dtype(dtype):
base = np.dtype(dtype).type
if base not in VALID_DTYPES:
raise ValueError(f'{dtype!r} not supported; use uint8 or float32') Type guard
def is_supported_dtype(dtype) -> bool:
return np.dtype(dtype).type in (np.uint8, np.float32) Try / catch
try:
datasets = read_data_sets(train_dir, dtype=dtype)
except TypeError as e:
if 'Invalid image dtype' in str(e):
dtype = np.float32 # fall back to a supported dtype
datasets = read_data_sets(train_dir, dtype=dtype)
else:
raise Prevention
- Restrict dtype configuration to the literal choices uint8 / float32 in UIs and config schemas
- Cast to the final precision after loading instead of asking the loader for unsupported dtypes
When it happens
Trigger: Calling read_data_sets(..., dtype=...) or constructing _DataSet(..., dtype=...) with values such as np.float64, np.int32, tf.int64, or the string 'float64'. dtypes.as_dtype resolves the name, but the base_dtype falls outside the allowed pair.
Common situations: Porting old tutorials that pass dtype=np.float64 for higher precision, copying a dtype from a different dataset loader (e.g. CIFAR loaders that accept float64), or assuming any NumPy dtype string is accepted.
Related errors
- number must be positive
- The value of input must be non-negative
- Input list must contain at least two elements
- Inputs and select signal must be 0 or 1
- plain must contain only lowercase letters (a-z)
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/2d1405d7f289547a.
Report an issue: GitHub.