On this page
tf.compat.v1.keras.estimator.model_to_estimator
Constructs an Estimator instance from given keras model.
tf.compat.v1.keras.estimator.model_to_estimator(
    keras_model=None, keras_model_path=None, custom_objects=None, model_dir=None,
    config=None, checkpoint_format='saver', metric_names_map=None,
    export_outputs=None
)
If you use infrastructure or other tooling that relies on Estimators, you can still build a Keras model and use model_to_estimator to convert the Keras model to an Estimator for use with downstream systems.
For usage example, please see: Creating estimators from Keras Models.
Sample Weights:
Estimators returned by model_to_estimator are configured so that they can handle sample weights (similar to keras_model.fit(x, y, sample_weights)).
To pass sample weights when training or evaluating the Estimator, the first item returned by the input function should be a dictionary with keys features and sample_weights. Example below:
keras_model = tf.keras.Model(...)
keras_model.compile(...)
estimator = tf.keras.estimator.model_to_estimator(keras_model)
def input_fn():
  return dataset_ops.Dataset.from_tensors(
      ({'features': features, 'sample_weights': sample_weights},
       targets))
estimator.train(input_fn, steps=1)
Example with customized export signature:
inputs = {'a': tf.keras.Input(..., name='a'),
          'b': tf.keras.Input(..., name='b')}
outputs = {'c': tf.keras.layers.Dense(..., name='c')(inputs['a']),
           'd': tf.keras.layers.Dense(..., name='d')(inputs['b'])}
keras_model = tf.keras.Model(inputs, outputs)
keras_model.compile(...)
export_outputs = {'c': tf.estimator.export.RegressionOutput,
                  'd': tf.estimator.export.ClassificationOutput}
estimator = tf.keras.estimator.model_to_estimator(
    keras_model, export_outputs=export_outputs)
def input_fn():
  return dataset_ops.Dataset.from_tensors(
      ({'features': features, 'sample_weights': sample_weights},
       targets))
estimator.train(input_fn, steps=1)
| Args | |
|---|---|
| keras_model | A compiled Keras model object. This argument is mutually exclusive with keras_model_path. Estimator'smodel_fnuses the structure of the model to clone the model. Defaults toNone. | 
| keras_model_path | Path to a compiled Keras model saved on disk, in HDF5 format, which can be generated with the save()method of a Keras model. This argument is mutually exclusive withkeras_model. Defaults toNone. | 
| custom_objects | Dictionary for cloning customized objects. This is used with classes that is not part of this pip package. For example, if user maintains a relu6class that inherits fromtf.keras.layers.Layer, then passcustom_objects={'relu6': relu6}. Defaults toNone. | 
| model_dir | Directory to save Estimatormodel parameters, graph, summary files for TensorBoard, etc. If unset a directory will be created withtempfile.mkdtemp | 
| config | RunConfigto configEstimator. Allows setting up things inmodel_fnbased on configuration such asnum_ps_replicas, ormodel_dir. Defaults toNone. If bothconfig.model_dirand themodel_dirargument (above) are specified themodel_dirargument takes precedence. | 
| checkpoint_format | Sets the format of the checkpoint saved by the estimator when training. May be saverorcheckpoint, depending on whether to save checkpoints fromtf.train.Saverortf.train.Checkpoint. This argument currently defaults tosaver. When 2.0 is released, the default will becheckpoint. Estimators use name-basedtf.train.Savercheckpoints, while Keras models use object-based checkpoints fromtf.train.Checkpoint. Currently, saving object-based checkpoints frommodel_to_estimatoris only supported by Functional and Sequential models. Defaults to 'saver'. | 
| metric_names_map | Optional dictionary mapping Keras model output metric names to custom names. This can be used to override the default Keras model output metrics names in a multi IO model use case and provide custom names for the eval_metric_opsin Estimator. The Keras model metric names can be obtained usingmodel.metrics_namesexcluding any loss metrics such as total loss and output losses. For example, if your Keras model has two outputsout_1andout_2, withmseloss andaccmetric, thenmodel.metrics_nameswill be['loss', 'out_1_loss', 'out_2_loss', 'out_1_acc', 'out_2_acc']. The model metric names excluding the loss metrics will be['out_1_acc', 'out_2_acc']. | 
| export_outputs | Optional dictionary. This can be used to override the default Keras model output exports in a multi IO model use case and provide custom names for the export_outputsintf.estimator.EstimatorSpec. Default is None, which is equivalent to {'serving_default':tf.estimator.export.PredictOutput}. If not None, the keys must match the keys ofmodel.output_names. A dict{name: output}where:
 | 
| Returns | |
|---|---|
| An Estimator from given keras model. | 
| Raises | |
|---|---|
| ValueError | If neither keras_model nor keras_model_path was given. | 
| ValueError | If both keras_model and keras_model_path was given. | 
| ValueError | If the keras_model_path is a GCS URI. | 
| ValueError | If keras_model has not been compiled. | 
| ValueError | If an invalid checkpoint_format was given. | 
© 2020 The TensorFlow Authors. All rights reserved.
Licensed under the Creative Commons Attribution License 3.0.
Code samples licensed under the Apache 2.0 License.
 https://www.tensorflow.org/versions/r2.4/api_docs/python/tf/compat/v1/keras/estimator/model_to_estimator