-
Notifications
You must be signed in to change notification settings - Fork 19.7k
Support PyDataset in Normalization layer adapt methods
#21817
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 3 commits
6a9aa5f
944082f
ac460d9
87db5b3
c279453
15d1562
0ab5a71
883822c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,7 +6,9 @@ | |
| from keras.src import ops | ||
| from keras.src.api_export import keras_export | ||
| from keras.src.layers.preprocessing.data_layer import DataLayer | ||
| from keras.src.trainers.data_adapters import get_data_adapter | ||
| from keras.src.utils.module_utils import tensorflow as tf | ||
| from keras.utils import PyDataset | ||
|
|
||
|
|
||
| @keras_export("keras.layers.Normalization") | ||
|
|
@@ -229,6 +231,26 @@ def adapt(self, data): | |
| # Batch dataset if it isn't batched | ||
| data = data.batch(128) | ||
| input_shape = tuple(data.element_spec.shape) | ||
| elif isinstance(data, PyDataset): | ||
| # as PyDatasets returns tuples of input/annotation pairs | ||
| adapter = get_data_adapter(data) | ||
| tf_dataset = adapter.get_tf_dataset() | ||
| if len(tf_dataset.element_spec) == 1: | ||
| # just x | ||
| data = tf_dataset.map(lambda x: x) | ||
| elif len(tf_dataset.element_spec) == 2: | ||
|
||
| # (x, y) pairs | ||
| data = tf_dataset.map(lambda x, y: x) | ||
| elif len(tf_dataset.element_spec) == 3: | ||
| # (x, y, sample_weight) tuples | ||
| data = tf_dataset.map(lambda x, y, z: x) | ||
| input_shape = data.element_spec.shape | ||
|
||
| else: | ||
| raise TypeError( | ||
| f"Unsupported data type: {type(data)}. `adapt` supports " | ||
| f"`np.ndarray`, backend tensors, `tf.data.Dataset`, and " | ||
| f"`keras.utils.PyDataset`." | ||
| ) | ||
|
|
||
| if not self.built: | ||
| self.build(input_shape) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This isn't doing anything, and can be removed
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I did that because:
otherwise, there's a
E AttributeError: 'tuple' object has no attribute 'shape'since the former returns a tuple. Alternatively, without themapwe could get the shape viatf_dataset.element_spec[0].shape.