{"record":{"id":"2d1405d7f289547a","repo":"TheAlgorithms/Python","slug":"invalid-image-dtype-dtype-r-expected-uint8-or-f","errorCode":null,"errorMessage":"Invalid image dtype {dtype!r}, expected uint8 or float32","messagePattern":"Invalid image dtype (.+?), expected uint8 or float32","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"neural_network/input_data.py","lineNumber":158,"sourceCode":"\n        Args:\n          images: The images\n          labels: The labels\n          fake_data: Ignore inages and labels, use fake data.\n          one_hot: Bool, return the labels as one hot vectors (if True) or ints (if\n            False).\n          dtype: Output image dtype. One of [uint8, float32]. `uint8` output has\n            range [0,255]. float32 output has range [0,1].\n          reshape: Bool. If True returned images are returned flattened to vectors.\n          seed: The random seed to use.\n        \"\"\"\n        seed1, seed2 = random_seed.get_seed(seed)\n        # If op level seed is not set, use whatever graph level seed is returned\n        self._rng = np.random.default_rng(seed1 if seed is None else seed2)\n        dtype = dtypes.as_dtype(dtype).base_dtype\n        if dtype not in (dtypes.uint8, dtypes.float32):\n            msg = f\"Invalid image dtype {dtype!r}, expected uint8 or float32\"\n            raise TypeError(msg)\n        if fake_data:\n            self._num_examples = 10000\n            self.one_hot = one_hot\n        else:\n            assert images.shape[0] == labels.shape[0], (\n                f\"images.shape: {images.shape} labels.shape: {labels.shape}\"\n            )\n            self._num_examples = images.shape[0]\n\n            # Convert shape from [num examples, rows, columns, depth]\n            # to [num examples, rows*columns] (assuming depth == 1)\n            if reshape:\n                assert images.shape[3] == 1\n                images = images.reshape(\n                    images.shape[0], images.shape[1] * images.shape[2]\n                )\n            if dtype == dtypes.float32:\n                # Convert from [0, 255] -> [0.0, 1.0].","sourceCodeStart":140,"sourceCodeEnd":176,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/neural_network/input_data.py#L140-L176","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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')"],"exampleFix":"# before\ndatasets = read_data_sets('/tmp/mnist', dtype=np.float64)  # TypeError\n\n# after\ndatasets = read_data_sets('/tmp/mnist', dtype=np.float32)\nimages64 = datasets.train.images.astype(np.float64)  # cast later if needed","handlingStrategy":"type-guard","validationCode":"import numpy as np\n\nVALID_DTYPES = (np.uint8, np.float32)\n\ndef check_dtype(dtype):\n    base = np.dtype(dtype).type\n    if base not in VALID_DTYPES:\n        raise ValueError(f'{dtype!r} not supported; use uint8 or float32')","typeGuard":"def is_supported_dtype(dtype) -> bool:\n    return np.dtype(dtype).type in (np.uint8, np.float32)","tryCatchPattern":"try:\n    datasets = read_data_sets(train_dir, dtype=dtype)\nexcept TypeError as e:\n    if 'Invalid image dtype' in str(e):\n        dtype = np.float32  # fall back to a supported dtype\n        datasets = read_data_sets(train_dir, dtype=dtype)\n    else:\n        raise","preventionTips":["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"],"tags":["mnist","dtype","tensorflow","validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}