{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "wJcYs_ERTnnI" }, "source": [ "##### Copyright 2021 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "cellView": "form", "execution": { "iopub.execute_input": "2022-12-14T22:24:43.743890Z", "iopub.status.busy": "2022-12-14T22:24:43.743253Z", "iopub.status.idle": "2022-12-14T22:24:43.747067Z", "shell.execute_reply": "2022-12-14T22:24:43.746542Z" }, "id": "HMUDt0CiUJk9" }, "outputs": [], "source": [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "id": "77z2OchJTk0l" }, "source": [ "# Estimator から Keras API に移行する\n", "\n", "\n", " \n", " \n", " \n", " \n", "
TensorFlow.org で表示\n", " Google Colab で実行\n", " GitHub でソースを表示ノートブックをダウンロード
" ] }, { "cell_type": "markdown", "metadata": { "id": "meUTrR4I6m1C" }, "source": [ "このガイドでは、TensorFlow 1 の `tf.estimator.Estimator` API から TensorFlow 2 の `tf.keras` API に移行する方法を示します。最初に、`tf.estimator.Estimator` を使用してトレーニングと評価のための基本モデルをセットアップして実行します。次に、`tf.keras` API を使用して TensorFlow 2 で同等の手順を実行します。また、`tf.GradientTape` をサブクラス化し、`tf.keras.Model` を使用してトレーニングの手順をカスタマイズする方法も学びます。\n", "\n", "- TensorFlow 1 では、高レベルの `tf.estimator.Estimator` API を使用して、モデルのトレーニングと評価、推論の実行、およびモデルの保存(提供用)を行うことができます。\n", "- TensorFlow 2 では、Keras API を使用して、[モデルの構築](https://www.tensorflow.org/guide/keras/custom_layers_and_models)、勾配の適用、 [トレーニング](https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit)、評価、予測などの前述のタスクを実行します。\n", "\n", "(モデル/チェックポイント保存ワークフローを TensorFlow 2 に移行するには、[SavedModel](saved_model.ipynb) および [Checkpoint](checkpoint_saved.ipynb) 移行ガイドを確認してください。)" ] }, { "cell_type": "markdown", "metadata": { "id": "YdZSoIXEbhg-" }, "source": [ "## セットアップ\n", "\n", "インポートと単純なデータセットから始めます。" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:24:43.750656Z", "iopub.status.busy": "2022-12-14T22:24:43.750108Z", "iopub.status.idle": "2022-12-14T22:24:45.655171Z", "shell.execute_reply": "2022-12-14T22:24:45.654333Z" }, "id": "iE0vSfMXumKI" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2022-12-14 22:24:44.683460: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory\n", "2022-12-14 22:24:44.683565: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory\n", "2022-12-14 22:24:44.683576: 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.\n" ] } ], "source": [ "import tensorflow as tf\n", "import tensorflow.compat.v1 as tf1" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:24:45.659460Z", "iopub.status.busy": "2022-12-14T22:24:45.659049Z", "iopub.status.idle": "2022-12-14T22:24:45.663106Z", "shell.execute_reply": "2022-12-14T22:24:45.662536Z" }, "id": "m7rnGxsXtDkV" }, "outputs": [], "source": [ "features = [[1., 1.5], [2., 2.5], [3., 3.5]]\n", "labels = [[0.3], [0.5], [0.7]]\n", "eval_features = [[4., 4.5], [5., 5.5], [6., 6.5]]\n", "eval_labels = [[0.8], [0.9], [1.]]" ] }, { "cell_type": "markdown", "metadata": { "id": "4uXff1BEssdE" }, "source": [ "## TensorFlow 1: tf.estimator.Estimator でトレーニングと評価を行う\n", "\n", "この例では、TensorFlow 1 で `tf.estimator.Estimator` を使用してトレーニングと評価を実行する方法を示します。\n", "\n", "いくつかの関数を定義することから始めます。トレーニングデータの入力関数、評価データの評価入力関数、および特徴量とラベルを使用してトレーニング演算がどのように定義されるかを `Estimator` に伝えるモデル関数です。" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:24:45.666523Z", "iopub.status.busy": "2022-12-14T22:24:45.665951Z", "iopub.status.idle": "2022-12-14T22:24:45.670880Z", "shell.execute_reply": "2022-12-14T22:24:45.670332Z" }, "id": "lqe9obf7suIj" }, "outputs": [], "source": [ "def _input_fn():\n", " return tf1.data.Dataset.from_tensor_slices((features, labels)).batch(1)\n", "\n", "def _eval_input_fn():\n", " return tf1.data.Dataset.from_tensor_slices(\n", " (eval_features, eval_labels)).batch(1)\n", "\n", "def _model_fn(features, labels, mode):\n", " logits = tf1.layers.Dense(1)(features)\n", " loss = tf1.losses.mean_squared_error(labels=labels, predictions=logits)\n", " optimizer = tf1.train.AdagradOptimizer(0.05)\n", " train_op = optimizer.minimize(loss, global_step=tf1.train.get_global_step())\n", " return tf1.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)" ] }, { "cell_type": "markdown", "metadata": { "id": "44bf417bf9c0" }, "source": [ "`Estimator` をインスタンス化し、モデルをトレーニングします。" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:24:45.674157Z", "iopub.status.busy": "2022-12-14T22:24:45.673638Z", "iopub.status.idle": "2022-12-14T22:24:50.086817Z", "shell.execute_reply": "2022-12-14T22:24:50.085933Z" }, "id": "922720812527" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Using default config.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "WARNING:tensorflow:Using temporary folder as model directory: /tmpfs/tmp/tmpzy9ux6di\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Using config: {'_model_dir': '/tmpfs/tmp/tmpzy9ux6di', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true\n", "graph_options {\n", " rewrite_options {\n", " meta_optimizer_iterations: ONE\n", " }\n", "}\n", ", '_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}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "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.\n", "Instructions for updating:\n", "Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Calling model_fn.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "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.\n", "Instructions for updating:\n", "Call initializer instance with the dtype argument instead of passing it to the constructor\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Done calling model_fn.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Create CheckpointSaverHook.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Graph was finalized.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Running local_init_op.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Done running local_init_op.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Saving checkpoints for 0 into /tmpfs/tmp/tmpzy9ux6di/model.ckpt.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:loss = 0.3302933, step = 0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 3...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Saving checkpoints for 3 into /tmpfs/tmp/tmpzy9ux6di/model.ckpt.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 3...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Loss for final step: 0.9824529.\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "estimator = tf1.estimator.Estimator(model_fn=_model_fn)\n", "estimator.train(_input_fn)" ] }, { "cell_type": "markdown", "metadata": { "id": "17c9933c2d89" }, "source": [ "評価セットを使用してプログラムを評価します。" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:24:50.090488Z", "iopub.status.busy": "2022-12-14T22:24:50.089913Z", "iopub.status.idle": "2022-12-14T22:24:50.484692Z", "shell.execute_reply": "2022-12-14T22:24:50.483816Z" }, "id": "HsOpjW5plH9Q" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Calling model_fn.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Done calling model_fn.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Starting evaluation at 2022-12-14T22:24:50\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Graph was finalized.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmpzy9ux6di/model.ckpt-3\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Running local_init_op.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Done running local_init_op.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Inference Time : 0.25545s\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Finished evaluation at 2022-12-14-22:24:50\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Saving dict for global step 3: global_step = 3, loss = 2.2362373\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "INFO:tensorflow:Saving 'checkpoint_path' summary for global step 3: /tmpfs/tmp/tmpzy9ux6di/model.ckpt-3\n" ] }, { "data": { "text/plain": [ "{'loss': 2.2362373, 'global_step': 3}" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "estimator.evaluate(_eval_input_fn)" ] }, { "cell_type": "markdown", "metadata": { "id": "KEmzBjfnsxwT" }, "source": [ "## TensorFlow 2: 組み込みの Keras メソッドを使用してトレーニングと評価を行う\n", "\n", "この例では、TensorFlow 2 で Keras `Model.fit` と `Model.evaluate` を使用してトレーニングと評価を実行する方法を示します(詳細については、[組み込みメソッドを使用したトレーニングと評価](https://www.tensorflow.org/guide/keras/train_and_evaluate)ガイドを参照してください)。\n", "\n", "- `tf.data.Dataset` API を使用してデータセットパイプラインを準備することから始めます。\n", "- 1 つの線形(tf.keras.layers.Dense)レイヤーを持つ単純な Keras Sequential モデルを定義します。\n", "- Adagrad オプティマイザをインスタンス化します(`tf.keras.optimizers.Adagrad`)。\n", "- `optimizer` 変数と平均二乗誤差(`\"mse\"`)損失を `Model.compile` に渡して、トレーニング用のモデルを構成します。" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:24:50.488564Z", "iopub.status.busy": "2022-12-14T22:24:50.487956Z", "iopub.status.idle": "2022-12-14T22:24:50.518528Z", "shell.execute_reply": "2022-12-14T22:24:50.517901Z" }, "id": "atVciNgPs0fw" }, "outputs": [], "source": [ "dataset = tf.data.Dataset.from_tensor_slices((features, labels)).batch(1)\n", "eval_dataset = tf.data.Dataset.from_tensor_slices(\n", " (eval_features, eval_labels)).batch(1)\n", "\n", "model = tf.keras.models.Sequential([tf.keras.layers.Dense(1)])\n", "optimizer = tf.keras.optimizers.Adagrad(learning_rate=0.05)\n", "\n", "model.compile(optimizer=optimizer, loss=\"mse\")" ] }, { "cell_type": "markdown", "metadata": { "id": "ed17a6291959" }, "source": [ "これで、`Model.fit` を呼び出してモデルをトレーニングする準備が整いました。" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:24:50.522081Z", "iopub.status.busy": "2022-12-14T22:24:50.521514Z", "iopub.status.idle": "2022-12-14T22:24:51.043078Z", "shell.execute_reply": "2022-12-14T22:24:51.042327Z" }, "id": "a0b732534501" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\r", "1/3 [=========>....................] - ETA: 0s - loss: 3.7549" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r", "3/3 [==============================] - 0s 5ms/step - loss: 10.1551\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model.fit(dataset)" ] }, { "cell_type": "markdown", "metadata": { "id": "74767288a2ea" }, "source": [ "最後に、`Model.evaluate` を使用してモデルを評価します。" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:24:51.046749Z", "iopub.status.busy": "2022-12-14T22:24:51.046061Z", "iopub.status.idle": "2022-12-14T22:24:51.144209Z", "shell.execute_reply": "2022-12-14T22:24:51.143536Z" }, "id": "Kip65sYBlKiu" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\r", "1/3 [=========>....................] - ETA: 0s - loss: 25.7323" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r", "3/3 [==============================] - 0s 3ms/step - loss: 41.3360\n" ] }, { "data": { "text/plain": [ "{'loss': 41.33598709106445}" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model.evaluate(eval_dataset, return_dict=True)" ] }, { "cell_type": "markdown", "metadata": { "id": "BuVYN0CHs5sD" }, "source": [ "## TensorFlow 2: カスタムトレーニングステップと組み込みの Keras メソッドを使用してトレーニングと評価を行う" ] }, { "cell_type": "markdown", "metadata": { "id": "gHx_RUL8xcJ3" }, "source": [ "TensorFlow 2 では、`tf.keras.callbacks.Callback` や `tf.distribute.Strategy` などの組み込みのトレーニングサポートを引き続き利用しながら、`tf.GradientTape` を使用して独自のカスタムトレーニングステップ関数を作成して、フォワードパスとバックワードパスを実行することもできます。(詳細については、[Model.fit の処理をカスタマイズする](https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit)および[トレーニングループの新規作成](https://www.tensorflow.org/guide/keras/writing_a_training_loop_from_scratch)を参照してください。)\n", "\n", "この例では、`tf.keras.Sequential` をオーバーライドする `Model.train_step` をサブクラス化することにより、カスタム `tf.keras.Model` を作成することから始めます。([tf.keras.Model のサブクラス化](https://www.tensorflow.org/guide/keras/custom_layers_and_models)について詳しくご覧ください)。そのクラス内で、データのバッチごとに 1 つのトレーニングステップでフォワードパスとバックワードパスを実行するカスタムの `train_step` 関数を定義します。\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:24:51.147808Z", "iopub.status.busy": "2022-12-14T22:24:51.147249Z", "iopub.status.idle": "2022-12-14T22:24:51.152083Z", "shell.execute_reply": "2022-12-14T22:24:51.151459Z" }, "id": "rSz_y0zOs8h2" }, "outputs": [], "source": [ "class CustomModel(tf.keras.Sequential):\n", " \"\"\"A custom sequential model that overrides `Model.train_step`.\"\"\"\n", "\n", " def train_step(self, data):\n", " batch_data, labels = data\n", "\n", " with tf.GradientTape() as tape:\n", " predictions = self(batch_data, training=True)\n", " # Compute the loss value (the loss function is configured\n", " # in `Model.compile`).\n", " loss = self.compiled_loss(labels, predictions)\n", "\n", " # Compute the gradients of the parameters with respect to the loss.\n", " gradients = tape.gradient(loss, self.trainable_variables)\n", " # Perform gradient descent by updating the weights/parameters.\n", " self.optimizer.apply_gradients(zip(gradients, self.trainable_variables))\n", " # Update the metrics (includes the metric that tracks the loss).\n", " self.compiled_metrics.update_state(labels, predictions)\n", " # Return a dict mapping metric names to the current values.\n", " return {m.name: m.result() for m in self.metrics}" ] }, { "cell_type": "markdown", "metadata": { "id": "ee7c4f94d69b" }, "source": [ "次に、前と同じように以下を実行します。\n", "\n", "- `tf.data.Dataset` でデータセットパイプラインを準備します。\n", "- 1 つの `tf.keras.layers.Dense` レイヤーで単純なモデルを定義します。\n", "- Adagrad のインスタンス化(`tf.keras.optimizers.Adagrad`)\n", "- 損失関数として平均二乗誤差(`\"mse\"`)を使用しながら、`Model.compile` でトレーニング用のモデルを構成します。" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:24:51.155385Z", "iopub.status.busy": "2022-12-14T22:24:51.154893Z", "iopub.status.idle": "2022-12-14T22:24:51.170611Z", "shell.execute_reply": "2022-12-14T22:24:51.169983Z" }, "id": "01fcc2b1292c" }, "outputs": [], "source": [ "dataset = tf.data.Dataset.from_tensor_slices((features, labels)).batch(1)\n", "eval_dataset = tf.data.Dataset.from_tensor_slices(\n", " (eval_features, eval_labels)).batch(1)\n", "\n", "model = CustomModel([tf.keras.layers.Dense(1)])\n", "optimizer = tf.keras.optimizers.Adagrad(learning_rate=0.05)\n", "\n", "model.compile(optimizer=optimizer, loss=\"mse\")" ] }, { "cell_type": "markdown", "metadata": { "id": "844543802ff5" }, "source": [ "`Model.fit` を呼び出してモデルをトレーニングします。" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:24:51.174102Z", "iopub.status.busy": "2022-12-14T22:24:51.173582Z", "iopub.status.idle": "2022-12-14T22:24:51.532228Z", "shell.execute_reply": "2022-12-14T22:24:51.531556Z" }, "id": "211be3620765" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\r", "1/3 [=========>....................] - ETA: 0s - loss: 0.2560" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r", "3/3 [==============================] - 0s 3ms/step - loss: 0.4927\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model.fit(dataset)" ] }, { "cell_type": "markdown", "metadata": { "id": "c93b9d6fc9d7" }, "source": [ "最後に、`Model.evaluate` を使用してプログラムを評価します。" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T22:24:51.535877Z", "iopub.status.busy": "2022-12-14T22:24:51.535158Z", "iopub.status.idle": "2022-12-14T22:24:51.616781Z", "shell.execute_reply": "2022-12-14T22:24:51.616056Z" }, "id": "nYO2wI1SlNCG" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\r", "1/3 [=========>....................] - ETA: 0s - loss: 0.7179" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r", "3/3 [==============================] - 0s 3ms/step - loss: 1.4714\n" ] }, { "data": { "text/plain": [ "{'loss': 1.4713608026504517}" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model.evaluate(eval_dataset, return_dict=True)" ] }, { "cell_type": "markdown", "metadata": { "id": "e9b5c9a4747b" }, "source": [ "## Next steps\n", "\n", "役に立つと思われる追加の Keras リソースは次のとおりです。\n", "\n", "- ガイド: [組み込みメソッドを使用したトレーニングと評価](https://www.tensorflow.org/guide/keras/train_and_evaluate)\n", "- ガイド: [Model.fit の処理をカスタマイズする](https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit)\n", "- ガイド: [トレーニングループの新規作成](https://www.tensorflow.org/guide/keras/writing_a_training_loop_from_scratch)\n", "- ガイド: [サブクラス化によるレイヤーとモデルの新規作成](https://www.tensorflow.org/guide/keras/custom_layers_and_models)\n", "\n", "次のガイドは、`tf.estimator` API から分散ストラテジーのワークフローを移行するのに役立ちます。\n", "\n", "- [TPUEstimator から TPUStrategy への移行](tpu_estimator.ipynb)\n", "- [シングルワーカーのマルチ GPUトレーニングを移行する](mirrored_strategy.ipynb)\n", "- [マルチワーカー CPU/GPUトレーニングを移行する](multi_worker_cpu_gpu_training.ipynb)" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "migrating_estimator.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.16" } }, "nbformat": 4, "nbformat_minor": 0 }