Attend the Women in ML Symposium on December 7 Register now

从 Estimator 迁移到 Keras API

在 TensorFlow.org 上查看 在 Google Colab 运行 在 Github 上查看源代码 下载笔记本

本指南演示了如何从 TensorFlow 1 的 tf.estimator.Estimator API 迁移到 TensorFlow 2 的 tf.keras API。首先,您将使用 tf.estimator.Estimator 设置并运行一个用于训练和评估的基本模型。然后,您将使用 tf.keras API 在 TensorFlow 2 中执行对应步骤。此外,您还将了解如何通过子类化 tf.keras.Model 和使用 tf.GradientTape 来自定义训练步骤。

  • 在 TensorFlow 1 中,可以使用高级 tf.estimator.Estimator API 训练和评估模型,以及执行推断和保存模型(用于提供)。
  • 在 TensorFlow 2 中,使用 Keras API 执行上述任务,例如模型构建、梯度应用、训练、评估和预测。

(要将模型/检查点保存工作流迁移到 TensorFlow 2,请查看 SavedModel检查点迁移指南。)

安装

从导入和一个简单的数据集开始:

import tensorflow as tf
import tensorflow.compat.v1 as tf1
2022-08-31 00:08:48.288929: E tensorflow/stream_executor/cuda/cuda_blas.cc:2981] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
2022-08-31 00:08:49.041788: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvrtc.so.11.1: cannot open shared object file: No such file or directory
2022-08-31 00:08:49.042064: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvrtc.so.11.1: cannot open shared object file: No such file or directory
2022-08-31 00:08:49.042089: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
features = [[1., 1.5], [2., 2.5], [3., 3.5]]
labels = [[0.3], [0.5], [0.7]]
eval_features = [[4., 4.5], [5., 5.5], [6., 6.5]]
eval_labels = [[0.8], [0.9], [1.]]

TensorFlow 1:使用 tf.estimator.Estimator 进行训练和评估

此示例展示了如何在 TensorFlow 1 中使用 tf.estimator.Estimator 执行训练和评估。

首先定义几个函数:训练数据的输入函数,评估数据的评估输入函数,以及告知 Estimator 如何使用特征和标签定义训练运算的模型函数:

def _input_fn():
  return tf1.data.Dataset.from_tensor_slices((features, labels)).batch(1)

def _eval_input_fn():
  return tf1.data.Dataset.from_tensor_slices(
      (eval_features, eval_labels)).batch(1)

def _model_fn(features, labels, mode):
  logits = tf1.layers.Dense(1)(features)
  loss = tf1.losses.mean_squared_error(labels=labels, predictions=logits)
  optimizer = tf1.train.AdagradOptimizer(0.05)
  train_op = optimizer.minimize(loss, global_step=tf1.train.get_global_step())
  return tf1.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)

实例化您的 Estimator,并训练模型:

estimator = tf1.estimator.Estimator(model_fn=_model_fn)
estimator.train(_input_fn)
INFO:tensorflow:Using default config.
WARNING:tensorflow:Using temporary folder as model directory: /tmpfs/tmp/tmpjvvl7bw6
INFO:tensorflow:Using config: {'_model_dir': '/tmpfs/tmp/tmpjvvl7bw6', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true
graph_options {
  rewrite_options {
    meta_optimizer_iterations: ONE
  }
}
, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_checkpoint_save_graph_def': True, '_service': None, '_cluster_spec': ClusterSpec({}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.9/site-packages/tensorflow/python/training/training_util.py:396: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.
INFO:tensorflow:Calling model_fn.
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.9/site-packages/tensorflow/python/training/adagrad.py:138: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0...
INFO:tensorflow:Saving checkpoints for 0 into /tmpfs/tmp/tmpjvvl7bw6/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0...
INFO:tensorflow:loss = 0.78629035, step = 0
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 3...
INFO:tensorflow:Saving checkpoints for 3 into /tmpfs/tmp/tmpjvvl7bw6/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 3...
INFO:tensorflow:Loss for final step: 0.7746613.
<tensorflow_estimator.python.estimator.estimator.Estimator at 0x7f3806c311c0>

使用评估集评估程序:

estimator.evaluate(_eval_input_fn)
INFO:tensorflow:Calling model_fn.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Starting evaluation at 2022-08-31T00:08:54
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmpjvvl7bw6/model.ckpt-3
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Inference Time : 0.15828s
INFO:tensorflow:Finished evaluation at 2022-08-31-00:08:54
INFO:tensorflow:Saving dict for global step 3: global_step = 3, loss = 0.95430946
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 3: /tmpfs/tmp/tmpjvvl7bw6/model.ckpt-3
{'loss': 0.95430946, 'global_step': 3}

TensorFlow 2:使用内置 Keras 方法进行训练和评估

此示例演示了如何在 TensorFlow 2 中使用 Model.fitModel.evaluate 执行训练和评估。(可以在使用内置方法进行训练和评估指南中了解详情。)

dataset = tf.data.Dataset.from_tensor_slices((features, labels)).batch(1)
eval_dataset = tf.data.Dataset.from_tensor_slices(
      (eval_features, eval_labels)).batch(1)

model = tf.keras.models.Sequential([tf.keras.layers.Dense(1)])
optimizer = tf.keras.optimizers.Adagrad(learning_rate=0.05)

model.compile(optimizer=optimizer, loss="mse")

这样,您就可以通过调用 Model.fit 来训练模型了:

model.fit(dataset)
3/3 [==============================] - 0s 3ms/step - loss: 0.5478
<keras.callbacks.History at 0x7f37f035ccd0>

最后,使用 Model.evaluate 评估模型:

model.evaluate(eval_dataset, return_dict=True)
3/3 [==============================] - 0s 2ms/step - loss: 0.3235
{'loss': 0.3234606087207794}

TensorFlow 2:使用自定义训练步骤和内置 Keras 方法进行训练和评估

在 TensorFlow 2 中,还可以使用 tf.GradientTape 编写自己的自定义训练步骤函数来执行前向和后向传递,同时仍然利用内置的训练支持,例如 tf.keras.callbacks.Callbacktf.distribute.Strategy。(在自定义 Model.fit 的功能从头开始编写自定义训练循环中了解详情。)

在此示例中,首先通过子类化重写 Model.train_steptf.keras.Sequential 来创建自定义 tf.keras.Model。(详细了解如何子类化 tf.keras.Model)。在该类中,定义一个自定义 train_step 函数,此函数在一个训练步骤中为每批次数据执行前向传递和后向传递。

class CustomModel(tf.keras.Sequential):
  """A custom sequential model that overrides `Model.train_step`."""

  def train_step(self, data):
    batch_data, labels = data

    with tf.GradientTape() as tape:
      predictions = self(batch_data, training=True)
      # Compute the loss value (the loss function is configured
      # in `Model.compile`).
      loss = self.compiled_loss(labels, predictions)

    # Compute the gradients of the parameters with respect to the loss.
    gradients = tape.gradient(loss, self.trainable_variables)
    # Perform gradient descent by updating the weights/parameters.
    self.optimizer.apply_gradients(zip(gradients, self.trainable_variables))
    # Update the metrics (includes the metric that tracks the loss).
    self.compiled_metrics.update_state(labels, predictions)
    # Return a dict mapping metric names to the current values.
    return {m.name: m.result() for m in self.metrics}

接下来,和之前一样:

dataset = tf.data.Dataset.from_tensor_slices((features, labels)).batch(1)
eval_dataset = tf.data.Dataset.from_tensor_slices(
      (eval_features, eval_labels)).batch(1)

model = CustomModel([tf.keras.layers.Dense(1)])
optimizer = tf.keras.optimizers.Adagrad(learning_rate=0.05)

model.compile(optimizer=optimizer, loss="mse")

调用 Model.fit 以训练模型:

model.fit(dataset)
3/3 [==============================] - 0s 3ms/step - loss: 1.0773
<keras.callbacks.History at 0x7f380409da60>

最后,使用 Model.evaluate 评估程序:

model.evaluate(eval_dataset, return_dict=True)
3/3 [==============================] - 0s 2ms/step - loss: 3.6868
{'loss': 3.6867949962615967}

后续步骤

您可能会发现有用的其他 Keras 资源:

以下指南有助于从 tf.estimator API 迁移分布策略工作流: