Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/zh-cn/guide/migrate/evaluator.ipynb
25118 views
Kernel: Python 3
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.

评估是对模型进行衡量和基准测试的关键部分。

本指南演示了如何将评估器任务从 TensorFlow 1 迁移到 TensorFlow 2。在 TensorFlow 1 中,当 API 以分布式方式运行时,此功能由 tf.estimator.train_and_evaluate 实现。在 Tensorflow 2 中,可以使用内置 tf.keras.utils.SidecarEvaluator,或在评估器任务上使用自定义评估循环。

TensorFlow 1 (tf.estimator.Estimator.evaluate) 和 TensorFlow 2(Model.fit(..., validation_data=(...))Model.evaluate)中都有简单的连续评估选项。当您不希望工作进程在训练和评估之间切换时,评估器任务更合适,而当您希望分布评估时,Model.fit 中的内置评估更合适。

安装

import tensorflow.compat.v1 as tf1 import tensorflow as tf import numpy as np import tempfile import time import os
mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0

TensorFlow 1:使用 tf.estimator.train_and_evaluate 进行评估

在 TensorFlow 1 中,可以配置 tf.estimator 以使用 tf.estimator.train_and_evaluate 评估 Estimator。

在此示例中,首先定义 tf.estimator.Estimator 并指定训练和评估规范:

feature_columns = [tf1.feature_column.numeric_column("x", shape=[28, 28])] classifier = tf1.estimator.DNNClassifier( feature_columns=feature_columns, hidden_units=[256, 32], optimizer=tf1.train.AdamOptimizer(0.001), n_classes=10, dropout=0.2 ) train_input_fn = tf1.estimator.inputs.numpy_input_fn( x={"x": x_train}, y=y_train.astype(np.int32), num_epochs=10, batch_size=50, shuffle=True, ) test_input_fn = tf1.estimator.inputs.numpy_input_fn( x={"x": x_test}, y=y_test.astype(np.int32), num_epochs=10, shuffle=False ) train_spec = tf1.estimator.TrainSpec(input_fn=train_input_fn, max_steps=10) eval_spec = tf1.estimator.EvalSpec(input_fn=test_input_fn, steps=10, throttle_secs=0)

随后,训练和评估模型。评估在训练之间同步运行,因为它在此笔记本中被限制为本地运行,并且在训练和评估之间交替运行。但是,如果 Estimator 是以分布式方式使用的,则评估器将作为专用评估器任务运行。有关详情,请查看分布式训练的迁移指南

tf1.estimator.train_and_evaluate(estimator=classifier, train_spec=train_spec, eval_spec=eval_spec)

TensorFlow 2:评估 Keras 模型

在 TensorFlow 2 中,如果您使用 Model.fit API 进行训练,则可以使用 tf.keras.utils.SidecarEvaluator 评估模型。此外,还可以在 Tensorboard 中呈现评估指标,本指南中未介绍此功能。

为了帮助演示这一点,我们首先定义和训练模型:

def create_model(): return tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10) ]) loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) model = create_model() model.compile(optimizer='adam', loss=loss, metrics=['accuracy'], steps_per_execution=10, run_eagerly=True) log_dir = tempfile.mkdtemp() model_checkpoint = tf.keras.callbacks.ModelCheckpoint( filepath=os.path.join(log_dir, 'ckpt-{epoch}'), save_weights_only=True) model.fit(x=x_train, y=y_train, epochs=1, callbacks=[model_checkpoint])

然后,使用 tf.keras.utils.SidecarEvaluator 评估模型。在实际训练中,建议使用单独的作业进行评估,以释放工作进程资源进行训练。

data = tf.data.Dataset.from_tensor_slices((x_test, y_test)) data = data.batch(64) tf.keras.utils.SidecarEvaluator( model=model, data=data, checkpoint_dir=log_dir, max_evaluations=1 ).start()

后续步骤

  • 要详细了解 sidecar 评估,请考虑阅读 tf.keras.utils.SidecarEvaluator API 文档。

  • 要考虑在 Keras 中交替进行训练和评估,请考虑阅读其他内置方法