TensorFlow Estimators are supported in TensorFlow, and can be created from new and existing tf.keras models. This tutorial contains a complete, minimal example of that process.
In Keras, you assemble layers to build models. A model is (usually) a graph
of layers. The most common type of model is a stack of layers: the
tf.keras.Sequential model.
To build a simple, fully-connected network (i.e. multi-layer perceptron):
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(16, activation='relu', input_shape=(4,)),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(3)
])
Use the Datasets API to scale to large datasets
or multi-device training.
Estimators need control of when and how their input pipeline is built. To allow this, they require an "Input function" or input_fn. The Estimator will call this function with no arguments. The input_fn must return a tf.data.Dataset.
for features_batch, labels_batch in input_fn().take(1):
print(features_batch)
print(labels_batch)
Create an Estimator from the tf.keras model.
A tf.keras.Model can be trained with the tf.estimator API by converting the
model to an tf.estimator.Estimator object with
tf.keras.estimator.model_to_estimator.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-04-03 UTC."],[],[],null,["# Create an Estimator from a Keras model\n\n\u003cbr /\u003e\n\n|---------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------|\n| [View on TensorFlow.org](https://www.tensorflow.org/tutorials/estimator/keras_model_to_estimator) | [Run in Google Colab](https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/estimator/keras_model_to_estimator.ipynb) | [View source on GitHub](https://github.com/tensorflow/docs/blob/master/site/en/tutorials/estimator/keras_model_to_estimator.ipynb) | [Download notebook](https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/estimator/keras_model_to_estimator.ipynb) |\n\n\u003e | **Warning:** TensorFlow 2.15 included the final release of the `tf-estimator` package. Estimators will not be available in TensorFlow 2.16 or after. See the [migration guide](https://tensorflow.org/guide/migrate/migrating_estimator) for more information about how to convert off of Estimators.\n\nOverview\n--------\n\nTensorFlow Estimators are supported in TensorFlow, and can be created from new and existing [`tf.keras`](https://www.tensorflow.org/api_docs/python/tf/keras) models. This tutorial contains a complete, minimal example of that process.\n| **Note:** If you have a Keras model, you can use it directly with [`tf.distribute` strategies](https://tensorflow.org/guide/migrate/guide/distributed_training) without converting it to an estimator. As such, `model_to_estimator` is no longer recommended.\n\nSetup\n-----\n\n import tensorflow as tf\n\n import numpy as np\n import tensorflow_datasets as tfds\n\n### Create a simple Keras model.\n\nIn Keras, you assemble *layers* to build *models* . A model is (usually) a graph\nof layers. The most common type of model is a stack of layers: the\n[`tf.keras.Sequential`](https://www.tensorflow.org/api_docs/python/tf/keras/Sequential) model.\n\nTo build a simple, fully-connected network (i.e. multi-layer perceptron): \n\n model = tf.keras.models.Sequential([\n tf.keras.layers.Dense(16, activation='relu', input_shape=(4,)),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(3)\n ])\n\nCompile the model and get a summary. \n\n model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n optimizer='adam')\n model.summary()\n\n### Create an input function\n\nUse the [Datasets API](../../guide/data) to scale to large datasets\nor multi-device training.\n\nEstimators need control of when and how their input pipeline is built. To allow this, they require an \"Input function\" or `input_fn`. The `Estimator` will call this function with no arguments. The `input_fn` must return a [`tf.data.Dataset`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset). \n\n def input_fn():\n split = tfds.Split.TRAIN\n dataset = tfds.load('iris', split=split, as_supervised=True)\n dataset = dataset.map(lambda features, labels: ({'dense_input':features}, labels))\n dataset = dataset.batch(32).repeat()\n return dataset\n\nTest out your `input_fn` \n\n for features_batch, labels_batch in input_fn().take(1):\n print(features_batch)\n print(labels_batch)\n\n### Create an Estimator from the tf.keras model.\n\nA [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) can be trained with the `tf.estimator` API by converting the\nmodel to an `tf.estimator.Estimator` object with\n`tf.keras.estimator.model_to_estimator`. \n\n import tempfile\n model_dir = tempfile.mkdtemp()\n keras_estimator = tf.keras.estimator.model_to_estimator(\n keras_model=model, model_dir=model_dir)\n\nTrain and evaluate the estimator. \n\n keras_estimator.train(input_fn=input_fn, steps=500)\n eval_result = keras_estimator.evaluate(input_fn=input_fn, steps=10)\n print('Eval result: {}'.format(eval_result))"]]