Commit 9943637e authored by A. Unique TensorFlower's avatar A. Unique TensorFlower Committed by tensorflow-copybara
Browse files

Checks if input tf.keras.Model is compiled

Instead of checking for attribute, check that attribute value is not None.

PiperOrigin-RevId: 264409455
parent 672acd78
......@@ -194,15 +194,15 @@ def from_compiled_keras_model(keras_model, dummy_batch):
ValueError: If `keras_model` was *not* compiled.
"""
py_typecheck.check_type(keras_model, tf.keras.Model)
# Optimizer attribute is only set after calling tf.keras.Model.compile().
if not keras_model.optimizer:
raise ValueError('`keras_model` must be compiled. Use from_keras_model() '
'instead.')
dummy_tensors = _preprocess_dummy_batch(dummy_batch)
# NOTE: A sub-classed tf.keras.Model does not produce the compiled metrics
# until the model has been called on input. The work-around is to call
# Model.test_on_batch() once before asking for metrics.
keras_model.test_on_batch(**dummy_tensors)
# Optimizer attribute is only set after calling tf.keras.Model.compile().
if not hasattr(keras_model, 'optimizer'):
raise ValueError('`keras_model` must be compiled. Use from_keras_model() '
'instead.')
return model_utils.enhance(_TrainableKerasModel(keras_model, dummy_tensors))
......
......@@ -117,6 +117,15 @@ class KerasUtilsTest(test.TestCase, parameterized.TestCase):
dummy_batch=_create_dummy_batch(1),
loss=tf.keras.losses.MeanSquaredError())
def test_from_compiled_keras_model_fails_on_uncompiled_model(self):
keras_model = model_examples.build_linear_regression_keras_functional_model(
feature_dims=1)
with self.assertRaisesRegex(ValueError, '`keras_model` must be compiled'):
keras_utils.from_compiled_keras_model(
keras_model=keras_model,
dummy_batch=_create_dummy_batch(feature_dims=1))
# Test class for batches using namedtuple.
_make_test_batch = collections.namedtuple('TestBatch', ['x', 'y'])
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment