Skip to content

Commit

Permalink
Adds error for serializing metric using layer serialization.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 527991285
  • Loading branch information
nkovela1 authored and tensorflower-gardener committed Apr 28, 2023
1 parent 1b7c53d commit 861ad74
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
8 changes: 8 additions & 0 deletions keras/layers/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
from keras.layers.rnn import cell_wrappers
from keras.layers.rnn import gru
from keras.layers.rnn import lstm
from keras.metrics import base_metric
from keras.saving import serialization_lib
from keras.saving.legacy import serialization as legacy_serialization
from keras.saving.legacy.saved_model import json_utils
Expand Down Expand Up @@ -208,6 +209,13 @@ def serialize(layer, use_legacy_format=False):
pprint(tf.keras.layers.serialize(model))
# prints the configuration of the model, as a dict.
"""
if isinstance(layer, base_metric.Metric):
raise ValueError(
f"Cannot serialize {layer} since it is a metric. "
"Please use the `keras.metrics.serialize()` and "
"`keras.metrics.deserialize()` APIs to serialize "
"and deserialize metrics."
)
if use_legacy_format:
return legacy_serialization.serialize_keras_object(layer)

Expand Down
6 changes: 6 additions & 0 deletions keras/layers/serialization_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from keras.layers.rnn import gru_v1
from keras.layers.rnn import lstm
from keras.layers.rnn import lstm_v1
from keras.metrics import Mean
from keras.testing_infra import test_combinations


Expand Down Expand Up @@ -191,6 +192,11 @@ def test_serialize_deserialize_gru(self, layer):
self.assertIsInstance(new_layer, gru_v1.GRU)
self.assertNotIsInstance(new_layer, gru.GRU)

def test_serialize_metric_throws_error(self):
metric = Mean()
with self.assertRaisesRegex(ValueError, "since it is a metric."):
_ = keras.layers.serialize(metric)


if __name__ == "__main__":
tf.test.main()

0 comments on commit 861ad74

Please sign in to comment.