Skip to content

keras.layers.Normalization#adapt() does not support keras.utils.PyDataset as input. #21300

Open
@limzikiki

Description

@limzikiki

Expected behavior

When I create a custom PyDataset and then pass it into the Normalization adapt method, the mean and variance should be computed successfully, as for a TensorFlow dataset.

Actual behavior

Method adapt does not handle the PyDataset like inputs.

Traceback (most recent call last):
  File "/home/user/project/keras_bug_sample.py", line 14, in <module>
    normalizer.adapt(CustomDataset)
  File "/home/user/.pyenv/versions/3.12.8/lib/python3.12/site-packages/keras/src/layers/preprocessing/normalization.py", line 230, in adapt
    self.build(input_shape)
               ^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'input_shape' where it is not associated with a value

Steps to reproduce

import keras

class CustomDataset(keras.utils.PyDataset):
    def __len__(self):
        return 100

    def __getitem__(self, idx):
        # Generate dummy data
        x = np.random.rand(32, 32, 3)
        y = np.random.randint(0, 10, size=(1,))
        return x, y

normalizer = keras.layers.Normalization()
normalizer.adapt(CustomDataset)

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions