Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/ja/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 に Evaluator タスクを移行する方法を示します。TensorFlow 1 では、API が分散して実行されている場合、この機能は tf.estimator.train_and_evaluate によって実装されます。 Tensorflow 2 では、組み込みの tf.keras.utils.SidecarEvaluator、または Evaluator タスクのカスタム評価ループを使用できます。

TensorFlow 1(tf.estimator.Estimator.evaluate)と TensorFlow 2(Model.fit(..., validation_data=(...)) または Model.evaluate)の両方に単純なシリアル評価オプションがあります。Evaluator タスクは、ワーカーがトレーニングと評価を切り替えないようにする場合に適しています。評価を分散する場合は、 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.train_and_evaluate を使用して Estimator を評価するように tf.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 が分散して使用される場合、Evaluator は専用の Evaluator タスクとして実行されます。詳細については、分散トレーニングに関する移行ガイドを確認してください。

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

TensorFlow 2: Keras モデルの評価

TensorFlow 2 では、トレーニングに Keras 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()

Next steps

  • サイドカー評価の詳細については、tf.keras.utils.SidecarEvaluator API ドキュメントを読むことを検討してください。

  • Keras でトレーニングと評価を交互に行うことを検討するには、その他の組み込みメソッドについて読むことを検討してください。