{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "b518b04cbfe0" }, "source": [ "##### Copyright 2020 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "cellView": "form", "execution": { "iopub.execute_input": "2022-12-14T21:33:43.501874Z", "iopub.status.busy": "2022-12-14T21:33:43.501242Z", "iopub.status.idle": "2022-12-14T21:33:43.508232Z", "shell.execute_reply": "2022-12-14T21:33:43.507708Z" }, "id": "906e07f6e562" }, "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": "d201e826ab29" }, "source": [ "# Writing your own callbacks" ] }, { "cell_type": "markdown", "metadata": { "id": "71699af85d2d" }, "source": [ "\n", " \n", " \n", " \n", " \n", "
TensorFlow.org で実行 Google Colabで実行 GitHubでソースを表示 ノートブックをダウンロード
" ] }, { "cell_type": "markdown", "metadata": { "id": "d75eb2e25f36" }, "source": [ "## はじめに\n", "\n", "コールバックは、トレーニング、評価、推論の間に Keras モデルの動作をカスタマイズするための強力なツールです。例には、TensorBoard でトレーニングの進捗状況や結果を可視化できる `tf.keras.callbacks.TensorBoard` や、トレーニング中にモデルを定期的に保存できる `tf.keras.callbacks.ModelCheckpoint` などを含みます。\n", "\n", "このガイドでは、Keras コールバックとは何か、それができること、そして独自のコールバックを構築する方法を学ぶことができます。まずは、簡単なコールバックアプリケーションのデモをいくつか紹介します。" ] }, { "cell_type": "markdown", "metadata": { "id": "b3600ee25c8e" }, "source": [ "## Setup" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T21:33:43.511674Z", "iopub.status.busy": "2022-12-14T21:33:43.511468Z", "iopub.status.idle": "2022-12-14T21:33:45.408062Z", "shell.execute_reply": "2022-12-14T21:33:45.407350Z" }, "id": "4dadb6688663" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2022-12-14 21:33:44.444160: 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 21:33:44.444264: 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 21:33:44.444275: 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", "from tensorflow import keras" ] }, { "cell_type": "markdown", "metadata": { "id": "42676f705fc8" }, "source": [ "## Keras コールバックの概要\n", "\n", "全てのコールバックは `keras.callbacks.Callbacks.Callback` クラスをサブクラス化し、トレーニング、テスト、予測のさまざまな段階で呼び出される一連のメソッドをオーバーライドします。コールバックは、トレーニング中にモデルの内部状態や統計上のビューを取得するのに有用です。\n", "\n", "以下のモデルメソッドには、(キーワード引数 `callbacks` として)コールバックのリストを渡すことができます。\n", "\n", "- `keras.Model.fit()`\n", "- `keras.Model.evaluate()`\n", "- `keras.Model.predict()`" ] }, { "cell_type": "markdown", "metadata": { "id": "46945bdf5056" }, "source": [ "## コールバックメソッドの概要\n", "\n", "### グローバルメソッド\n", "\n", "#### `on_(train|test|predict)_begin(self, logs=None)`\n", "\n", "`fit`/`evaluate`/`predict` の先頭で呼び出されます。\n", "\n", "#### `on_(train|test|predict)_end(self, logs=None)`\n", "\n", "`fit`/`evaluate`/`predict` の最後に呼び出されます。\n", "\n", "### トレーニング/テスト/予測のためのバッチレベルのメソッド\n", "\n", "#### `on_(train|test|predict)_batch_begin(self, batch, logs=None)`\n", "\n", "トレーニング/テスト/予測中に、バッチを処理する直前に呼び出されます。\n", "\n", "#### `on_(train|test|predict)_batch_end(self, batch, logs=None)`\n", "\n", "バッチのトレーニング/テスト/予測の終了時に呼び出されます。このメソッド内では、`logs` はメトリクスの結果を含むディクショナリです。\n", "\n", "### エポックレベルのメソッド(トレーニングのみ)\n", "\n", "#### `on_epoch_begin(self, epoch, logs=None)`\n", "\n", "トレーニング中に、エポックの最初に呼び出されます。\n", "\n", "#### `on_epoch_end(self, epoch, logs=None)`\n", "\n", "トレーニング中、エポックの最後に呼び出されます。" ] }, { "cell_type": "markdown", "metadata": { "id": "82f2370418a1" }, "source": [ "## 基本的な例\n", "\n", "具体的な例を見てみましょう。まず最初に、TensorFlow をインポートして単純な Sequential Keras モデルを定義してみます。" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T21:33:45.412770Z", "iopub.status.busy": "2022-12-14T21:33:45.411991Z", "iopub.status.idle": "2022-12-14T21:33:45.416634Z", "shell.execute_reply": "2022-12-14T21:33:45.415880Z" }, "id": "7350ea602e50" }, "outputs": [], "source": [ "# Define the Keras model to add callbacks to\n", "def get_model():\n", " model = keras.Sequential()\n", " model.add(keras.layers.Dense(1, input_dim=784))\n", " model.compile(\n", " optimizer=keras.optimizers.RMSprop(learning_rate=0.1),\n", " loss=\"mean_squared_error\",\n", " metrics=[\"mean_absolute_error\"],\n", " )\n", " return model\n" ] }, { "cell_type": "markdown", "metadata": { "id": "044db5f2dc6f" }, "source": [ "次に、Keras データセット API からトレーニングとテスト用の MNIST データを読み込みます。" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T21:33:45.420053Z", "iopub.status.busy": "2022-12-14T21:33:45.419475Z", "iopub.status.idle": "2022-12-14T21:33:45.773927Z", "shell.execute_reply": "2022-12-14T21:33:45.772891Z" }, "id": "f8826736a184" }, "outputs": [], "source": [ "# Load example MNIST data and pre-process it\n", "(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\n", "x_train = x_train.reshape(-1, 784).astype(\"float32\") / 255.0\n", "x_test = x_test.reshape(-1, 784).astype(\"float32\") / 255.0\n", "\n", "# Limit the data to 1000 samples\n", "x_train = x_train[:1000]\n", "y_train = y_train[:1000]\n", "x_test = x_test[:1000]\n", "y_test = y_test[:1000]" ] }, { "cell_type": "markdown", "metadata": { "id": "b9acd50b2215" }, "source": [ "今度は、以下のログを記録する単純なカスタムコールバックを定義します。\n", "\n", "- When `fit`/`evaluate`/`predict` starts & ends\n", "- When each epoch starts & ends\n", "- 各トレーニングバッチの開始時と終了時\n", "- 各評価(テスト)バッチの開始時と終了時\n", "- 各推論(予測)バッチの開始時と終了時" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T21:33:45.777987Z", "iopub.status.busy": "2022-12-14T21:33:45.777734Z", "iopub.status.idle": "2022-12-14T21:33:45.787472Z", "shell.execute_reply": "2022-12-14T21:33:45.786717Z" }, "id": "cc9888d28e79" }, "outputs": [], "source": [ "class CustomCallback(keras.callbacks.Callback):\n", " def on_train_begin(self, logs=None):\n", " keys = list(logs.keys())\n", " print(\"Starting training; got log keys: {}\".format(keys))\n", "\n", " def on_train_end(self, logs=None):\n", " keys = list(logs.keys())\n", " print(\"Stop training; got log keys: {}\".format(keys))\n", "\n", " def on_epoch_begin(self, epoch, logs=None):\n", " keys = list(logs.keys())\n", " print(\"Start epoch {} of training; got log keys: {}\".format(epoch, keys))\n", "\n", " def on_epoch_end(self, epoch, logs=None):\n", " keys = list(logs.keys())\n", " print(\"End epoch {} of training; got log keys: {}\".format(epoch, keys))\n", "\n", " def on_test_begin(self, logs=None):\n", " keys = list(logs.keys())\n", " print(\"Start testing; got log keys: {}\".format(keys))\n", "\n", " def on_test_end(self, logs=None):\n", " keys = list(logs.keys())\n", " print(\"Stop testing; got log keys: {}\".format(keys))\n", "\n", " def on_predict_begin(self, logs=None):\n", " keys = list(logs.keys())\n", " print(\"Start predicting; got log keys: {}\".format(keys))\n", "\n", " def on_predict_end(self, logs=None):\n", " keys = list(logs.keys())\n", " print(\"Stop predicting; got log keys: {}\".format(keys))\n", "\n", " def on_train_batch_begin(self, batch, logs=None):\n", " keys = list(logs.keys())\n", " print(\"...Training: start of batch {}; got log keys: {}\".format(batch, keys))\n", "\n", " def on_train_batch_end(self, batch, logs=None):\n", " keys = list(logs.keys())\n", " print(\"...Training: end of batch {}; got log keys: {}\".format(batch, keys))\n", "\n", " def on_test_batch_begin(self, batch, logs=None):\n", " keys = list(logs.keys())\n", " print(\"...Evaluating: start of batch {}; got log keys: {}\".format(batch, keys))\n", "\n", " def on_test_batch_end(self, batch, logs=None):\n", " keys = list(logs.keys())\n", " print(\"...Evaluating: end of batch {}; got log keys: {}\".format(batch, keys))\n", "\n", " def on_predict_batch_begin(self, batch, logs=None):\n", " keys = list(logs.keys())\n", " print(\"...Predicting: start of batch {}; got log keys: {}\".format(batch, keys))\n", "\n", " def on_predict_batch_end(self, batch, logs=None):\n", " keys = list(logs.keys())\n", " print(\"...Predicting: end of batch {}; got log keys: {}\".format(batch, keys))\n" ] }, { "cell_type": "markdown", "metadata": { "id": "8184bd3a76c2" }, "source": [ "試してみましょう。" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T21:33:45.790693Z", "iopub.status.busy": "2022-12-14T21:33:45.790297Z", "iopub.status.idle": "2022-12-14T21:33:50.576636Z", "shell.execute_reply": "2022-12-14T21:33:50.575953Z" }, "id": "75f7aa1edac6" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Starting training; got log keys: []\n", "Start epoch 0 of training; got log keys: []\n", "...Training: start of batch 0; got log keys: []\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "...Training: end of batch 0; got log keys: ['loss', 'mean_absolute_error']\n", "...Training: start of batch 1; got log keys: []\n", "...Training: end of batch 1; got log keys: ['loss', 'mean_absolute_error']\n", "...Training: start of batch 2; got log keys: []\n", "...Training: end of batch 2; got log keys: ['loss', 'mean_absolute_error']\n", "...Training: start of batch 3; got log keys: []\n", "...Training: end of batch 3; got log keys: ['loss', 'mean_absolute_error']\n", "Start testing; got log keys: []\n", "...Evaluating: start of batch 0; got log keys: []\n", "...Evaluating: end of batch 0; got log keys: ['loss', 'mean_absolute_error']\n", "...Evaluating: start of batch 1; got log keys: []\n", "...Evaluating: end of batch 1; got log keys: ['loss', 'mean_absolute_error']\n", "...Evaluating: start of batch 2; got log keys: []\n", "...Evaluating: end of batch 2; got log keys: ['loss', 'mean_absolute_error']\n", "...Evaluating: start of batch 3; got log keys: []\n", "...Evaluating: end of batch 3; got log keys: ['loss', 'mean_absolute_error']\n", "Stop testing; got log keys: ['loss', 'mean_absolute_error']\n", "End epoch 0 of training; got log keys: ['loss', 'mean_absolute_error', 'val_loss', 'val_mean_absolute_error']\n", "Stop training; got log keys: ['loss', 'mean_absolute_error', 'val_loss', 'val_mean_absolute_error']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Start testing; got log keys: []\n", "...Evaluating: start of batch 0; got log keys: []\n", "...Evaluating: end of batch 0; got log keys: ['loss', 'mean_absolute_error']\n", "...Evaluating: start of batch 1; got log keys: []\n", "...Evaluating: end of batch 1; got log keys: ['loss', 'mean_absolute_error']\n", "...Evaluating: start of batch 2; got log keys: []\n", "...Evaluating: end of batch 2; got log keys: ['loss', 'mean_absolute_error']\n", "...Evaluating: start of batch 3; got log keys: []\n", "...Evaluating: end of batch 3; got log keys: ['loss', 'mean_absolute_error']\n", "...Evaluating: start of batch 4; got log keys: []\n", "...Evaluating: end of batch 4; got log keys: ['loss', 'mean_absolute_error']\n", "...Evaluating: start of batch 5; got log keys: []\n", "...Evaluating: end of batch 5; got log keys: ['loss', 'mean_absolute_error']\n", "...Evaluating: start of batch 6; got log keys: []\n", "...Evaluating: end of batch 6; got log keys: ['loss', 'mean_absolute_error']\n", "...Evaluating: start of batch 7; got log keys: []\n", "...Evaluating: end of batch 7; got log keys: ['loss', 'mean_absolute_error']\n", "Stop testing; got log keys: ['loss', 'mean_absolute_error']\n", "Start predicting; got log keys: []\n", "...Predicting: start of batch 0; got log keys: []\n", "...Predicting: end of batch 0; got log keys: ['outputs']\n", "\r", "1/8 [==>...........................] - ETA: 0s" ] }, { "name": "stdout", "output_type": "stream", "text": [ "...Predicting: start of batch 1; got log keys: []\n", "...Predicting: end of batch 1; got log keys: ['outputs']\n", "...Predicting: start of batch 2; got log keys: []\n", "...Predicting: end of batch 2; got log keys: ['outputs']\n", "...Predicting: start of batch 3; got log keys: []\n", "...Predicting: end of batch 3; got log keys: ['outputs']\n", "...Predicting: start of batch 4; got log keys: []\n", "...Predicting: end of batch 4; got log keys: ['outputs']\n", "...Predicting: start of batch 5; got log keys: []\n", "...Predicting: end of batch 5; got log keys: ['outputs']\n", "...Predicting: start of batch 6; got log keys: []\n", "...Predicting: end of batch 6; got log keys: ['outputs']\n", "...Predicting: start of batch 7; got log keys: []\n", "...Predicting: end of batch 7; got log keys: ['outputs']\n", "Stop predicting; got log keys: []\n", "\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", "8/8 [==============================] - 0s 2ms/step\n" ] } ], "source": [ "model = get_model()\n", "model.fit(\n", " x_train,\n", " y_train,\n", " batch_size=128,\n", " epochs=1,\n", " verbose=0,\n", " validation_split=0.5,\n", " callbacks=[CustomCallback()],\n", ")\n", "\n", "res = model.evaluate(\n", " x_test, y_test, batch_size=128, verbose=0, callbacks=[CustomCallback()]\n", ")\n", "\n", "res = model.predict(x_test, batch_size=128, callbacks=[CustomCallback()])" ] }, { "cell_type": "markdown", "metadata": { "id": "02113b8677eb" }, "source": [ "### `logs` ディクショナリを使用する\n", "\n", "`logs` ディクショナリは、バッチまたはエポックの最後の損失値と全てのメトリクスを含みます。次の例は、損失値と平均絶対誤差を含んでいます。" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T21:33:50.580202Z", "iopub.status.busy": "2022-12-14T21:33:50.579731Z", "iopub.status.idle": "2022-12-14T21:33:51.217517Z", "shell.execute_reply": "2022-12-14T21:33:51.216791Z" }, "id": "629bc145eb84" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Up to batch 0, the average loss is 24.54.\n", "Up to batch 1, the average loss is 469.66.\n", "Up to batch 2, the average loss is 322.26.\n", "Up to batch 3, the average loss is 243.81.\n", "Up to batch 4, the average loss is 196.38.\n", "Up to batch 5, the average loss is 164.77.\n", "Up to batch 6, the average loss is 142.26.\n", "Up to batch 7, the average loss is 128.22.\n", "The average loss for epoch 0 is 128.22 and mean absolute error is 6.06.\n", "Up to batch 0, the average loss is 6.47.\n", "Up to batch 1, the average loss is 5.57.\n", "Up to batch 2, the average loss is 5.40.\n", "Up to batch 3, the average loss is 5.09.\n", "Up to batch 4, the average loss is 4.89.\n", "Up to batch 5, the average loss is 4.75.\n", "Up to batch 6, the average loss is 4.74.\n", "Up to batch 7, the average loss is 4.74.\n", "The average loss for epoch 1 is 4.74 and mean absolute error is 1.75.\n", "Up to batch 0, the average loss is 6.22.\n", "Up to batch 1, the average loss is 5.95.\n", "Up to batch 2, the average loss is 5.94.\n", "Up to batch 3, the average loss is 5.91.\n", "Up to batch 4, the average loss is 6.01.\n", "Up to batch 5, the average loss is 6.14.\n", "Up to batch 6, the average loss is 6.10.\n", "Up to batch 7, the average loss is 6.07.\n" ] } ], "source": [ "class LossAndErrorPrintingCallback(keras.callbacks.Callback):\n", " def on_train_batch_end(self, batch, logs=None):\n", " print(\n", " \"Up to batch {}, the average loss is {:7.2f}.\".format(batch, logs[\"loss\"])\n", " )\n", "\n", " def on_test_batch_end(self, batch, logs=None):\n", " print(\n", " \"Up to batch {}, the average loss is {:7.2f}.\".format(batch, logs[\"loss\"])\n", " )\n", "\n", " def on_epoch_end(self, epoch, logs=None):\n", " print(\n", " \"The average loss for epoch {} is {:7.2f} \"\n", " \"and mean absolute error is {:7.2f}.\".format(\n", " epoch, logs[\"loss\"], logs[\"mean_absolute_error\"]\n", " )\n", " )\n", "\n", "\n", "model = get_model()\n", "model.fit(\n", " x_train,\n", " y_train,\n", " batch_size=128,\n", " epochs=2,\n", " verbose=0,\n", " callbacks=[LossAndErrorPrintingCallback()],\n", ")\n", "\n", "res = model.evaluate(\n", " x_test,\n", " y_test,\n", " batch_size=128,\n", " verbose=0,\n", " callbacks=[LossAndErrorPrintingCallback()],\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "742d62e5394a" }, "source": [ "## `self.model` 属性を使用する\n", "\n", "コールバックは、そのメソッドの 1 つが呼び出された時にログ情報を受け取ることに加え、現在のトレーニング/評価/推論のラウンドに関連付けられたモデルに、`self.model` でアクセスすることができます。\n", "\n", "コールバックで `self.model` を使用してできることを幾つか次に示します。\n", "\n", "- `self.model.stop_training = True` を設定して直ちにトレーニングを中断する。\n", "- `self.model.optimizer.learning_rate` など、オプティマイザ(`self.model.optimizer` として使用可能)のハイパーパラメータを変化させる。\n", "- 一定間隔でモデルを保存する。\n", "- 各エポックの終了時に幾つかのテストサンプルの `model.predict()` の出力を記録し、トレーニング中にサ二ティーチェックとして使用する。\n", "- 各エポックの終了時に中間特徴の可視化を抽出して、モデルが何を学習しているかを経時的に監視する。\n", "- など\n", "\n", "これを確認するために、2 つの例で見てみましょう。" ] }, { "cell_type": "markdown", "metadata": { "id": "7eb29d3ed752" }, "source": [ "## Keras コールバックアプリケーションの例" ] }, { "cell_type": "markdown", "metadata": { "id": "2d1d29d99fa5" }, "source": [ "### 最小損失で Early stopping する\n", "\n", "この最初の例は、属性 `self.model.stop_training`(ブール)を設定して、損失の最小値に達した時点でトレーニングを停止する `Callback` を作成しています。オプションで、ローカル最小値に到達した後、実際に停止するまでに幾つのエポックを待つべきか、引数 `patience` で指定することが可能です。\n", "\n", "`tf.keras.callbacks.EarlyStopping` は、より完全で一般的な実装を提供します。" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T21:33:51.221867Z", "iopub.status.busy": "2022-12-14T21:33:51.221095Z", "iopub.status.idle": "2022-12-14T21:33:51.735073Z", "shell.execute_reply": "2022-12-14T21:33:51.734350Z" }, "id": "5d2acd79cecd" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Up to batch 0, the average loss is 28.01.\n", "Up to batch 1, the average loss is 478.97.\n", "Up to batch 2, the average loss is 326.88.\n", "Up to batch 3, the average loss is 247.41.\n", "Up to batch 4, the average loss is 199.61.\n", "The average loss for epoch 0 is 199.61 and mean absolute error is 8.38.\n", "Up to batch 0, the average loss is 8.27.\n", "Up to batch 1, the average loss is 7.42.\n", "Up to batch 2, the average loss is 6.64.\n", "Up to batch 3, the average loss is 6.49.\n", "Up to batch 4, the average loss is 6.43.\n", "The average loss for epoch 1 is 6.43 and mean absolute error is 2.08.\n", "Up to batch 0, the average loss is 3.78.\n", "Up to batch 1, the average loss is 4.07.\n", "Up to batch 2, the average loss is 4.41.\n", "Up to batch 3, the average loss is 4.35.\n", "Up to batch 4, the average loss is 4.22.\n", "The average loss for epoch 2 is 4.22 and mean absolute error is 1.66.\n", "Up to batch 0, the average loss is 4.30.\n", "Up to batch 1, the average loss is 6.80.\n", "Up to batch 2, the average loss is 7.85.\n", "Up to batch 3, the average loss is 11.09.\n", "Up to batch 4, the average loss is 17.11.\n", "The average loss for epoch 3 is 17.11 and mean absolute error is 3.40.\n", "Restoring model weights from the end of the best epoch.\n", "Epoch 00004: early stopping\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import numpy as np\n", "\n", "\n", "class EarlyStoppingAtMinLoss(keras.callbacks.Callback):\n", " \"\"\"Stop training when the loss is at its min, i.e. the loss stops decreasing.\n", "\n", " Arguments:\n", " patience: Number of epochs to wait after min has been hit. After this\n", " number of no improvement, training stops.\n", " \"\"\"\n", "\n", " def __init__(self, patience=0):\n", " super(EarlyStoppingAtMinLoss, self).__init__()\n", " self.patience = patience\n", " # best_weights to store the weights at which the minimum loss occurs.\n", " self.best_weights = None\n", "\n", " def on_train_begin(self, logs=None):\n", " # The number of epoch it has waited when loss is no longer minimum.\n", " self.wait = 0\n", " # The epoch the training stops at.\n", " self.stopped_epoch = 0\n", " # Initialize the best as infinity.\n", " self.best = np.Inf\n", "\n", " def on_epoch_end(self, epoch, logs=None):\n", " current = logs.get(\"loss\")\n", " if np.less(current, self.best):\n", " self.best = current\n", " self.wait = 0\n", " # Record the best weights if current results is better (less).\n", " self.best_weights = self.model.get_weights()\n", " else:\n", " self.wait += 1\n", " if self.wait >= self.patience:\n", " self.stopped_epoch = epoch\n", " self.model.stop_training = True\n", " print(\"Restoring model weights from the end of the best epoch.\")\n", " self.model.set_weights(self.best_weights)\n", "\n", " def on_train_end(self, logs=None):\n", " if self.stopped_epoch > 0:\n", " print(\"Epoch %05d: early stopping\" % (self.stopped_epoch + 1))\n", "\n", "\n", "model = get_model()\n", "model.fit(\n", " x_train,\n", " y_train,\n", " batch_size=64,\n", " steps_per_epoch=5,\n", " epochs=30,\n", " verbose=0,\n", " callbacks=[LossAndErrorPrintingCallback(), EarlyStoppingAtMinLoss()],\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "939ecfbe0383" }, "source": [ "### 学習率をスケジューリングする\n", "\n", "この例では、トレーニングの過程でカスタムコールバックを使用して、オプティマイザの学習率を動的に変更する方法を示します。\n", "\n", "より一般的な実装については、`callbacks.LearningRateScheduler` をご覧ください。" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T21:33:51.738672Z", "iopub.status.busy": "2022-12-14T21:33:51.738428Z", "iopub.status.idle": "2022-12-14T21:33:52.392941Z", "shell.execute_reply": "2022-12-14T21:33:52.392244Z" }, "id": "71c752b248c0" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Epoch 00000: Learning rate is 0.1000.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Up to batch 0, the average loss is 31.39.\n", "Up to batch 1, the average loss is 474.76.\n", "Up to batch 2, the average loss is 323.83.\n", "Up to batch 3, the average loss is 245.54.\n", "Up to batch 4, the average loss is 198.48.\n", "The average loss for epoch 0 is 198.48 and mean absolute error is 8.41.\n", "\n", "Epoch 00001: Learning rate is 0.1000.\n", "Up to batch 0, the average loss is 8.15.\n", "Up to batch 1, the average loss is 6.27.\n", "Up to batch 2, the average loss is 6.25.\n", "Up to batch 3, the average loss is 6.16.\n", "Up to batch 4, the average loss is 6.00.\n", "The average loss for epoch 1 is 6.00 and mean absolute error is 2.00.\n", "\n", "Epoch 00002: Learning rate is 0.1000.\n", "Up to batch 0, the average loss is 4.04.\n", "Up to batch 1, the average loss is 4.12.\n", "Up to batch 2, the average loss is 3.87.\n", "Up to batch 3, the average loss is 4.20.\n", "Up to batch 4, the average loss is 4.33.\n", "The average loss for epoch 2 is 4.33 and mean absolute error is 1.68.\n", "\n", "Epoch 00003: Learning rate is 0.0500.\n", "Up to batch 0, the average loss is 4.64.\n", "Up to batch 1, the average loss is 4.56.\n", "Up to batch 2, the average loss is 4.37.\n", "Up to batch 3, the average loss is 4.59.\n", "Up to batch 4, the average loss is 4.29.\n", "The average loss for epoch 3 is 4.29 and mean absolute error is 1.65.\n", "\n", "Epoch 00004: Learning rate is 0.0500.\n", "Up to batch 0, the average loss is 3.17.\n", "Up to batch 1, the average loss is 3.19.\n", "Up to batch 2, the average loss is 3.39.\n", "Up to batch 3, the average loss is 3.22.\n", "Up to batch 4, the average loss is 3.31.\n", "The average loss for epoch 4 is 3.31 and mean absolute error is 1.44.\n", "\n", "Epoch 00005: Learning rate is 0.0500.\n", "Up to batch 0, the average loss is 5.49.\n", "Up to batch 1, the average loss is 6.32.\n", "Up to batch 2, the average loss is 6.98.\n", "Up to batch 3, the average loss is 7.44.\n", "Up to batch 4, the average loss is 7.11.\n", "The average loss for epoch 5 is 7.11 and mean absolute error is 2.17.\n", "\n", "Epoch 00006: Learning rate is 0.0100.\n", "Up to batch 0, the average loss is 4.03.\n", "Up to batch 1, the average loss is 4.08.\n", "Up to batch 2, the average loss is 3.89.\n", "Up to batch 3, the average loss is 3.79.\n", "Up to batch 4, the average loss is 3.78.\n", "The average loss for epoch 6 is 3.78 and mean absolute error is 1.56.\n", "\n", "Epoch 00007: Learning rate is 0.0100.\n", "Up to batch 0, the average loss is 4.43.\n", "Up to batch 1, the average loss is 4.00.\n", "Up to batch 2, the average loss is 3.72.\n", "Up to batch 3, the average loss is 3.64.\n", "Up to batch 4, the average loss is 3.34.\n", "The average loss for epoch 7 is 3.34 and mean absolute error is 1.44.\n", "\n", "Epoch 00008: Learning rate is 0.0100.\n", "Up to batch 0, the average loss is 4.40.\n", "Up to batch 1, the average loss is 3.69.\n", "Up to batch 2, the average loss is 3.62.\n", "Up to batch 3, the average loss is 3.55.\n", "Up to batch 4, the average loss is 3.31.\n", "The average loss for epoch 8 is 3.31 and mean absolute error is 1.44.\n", "\n", "Epoch 00009: Learning rate is 0.0050.\n", "Up to batch 0, the average loss is 2.58.\n", "Up to batch 1, the average loss is 3.41.\n", "Up to batch 2, the average loss is 3.80.\n", "Up to batch 3, the average loss is 3.87.\n", "Up to batch 4, the average loss is 3.59.\n", "The average loss for epoch 9 is 3.59 and mean absolute error is 1.46.\n", "\n", "Epoch 00010: Learning rate is 0.0050.\n", "Up to batch 0, the average loss is 2.16.\n", "Up to batch 1, the average loss is 3.18.\n", "Up to batch 2, the average loss is 2.96.\n", "Up to batch 3, the average loss is 3.33.\n", "Up to batch 4, the average loss is 3.48.\n", "The average loss for epoch 10 is 3.48 and mean absolute error is 1.42.\n", "\n", "Epoch 00011: Learning rate is 0.0050.\n", "Up to batch 0, the average loss is 3.29.\n", "Up to batch 1, the average loss is 3.03.\n", "Up to batch 2, the average loss is 3.27.\n", "Up to batch 3, the average loss is 3.11.\n", "Up to batch 4, the average loss is 3.03.\n", "The average loss for epoch 11 is 3.03 and mean absolute error is 1.38.\n", "\n", "Epoch 00012: Learning rate is 0.0010.\n", "Up to batch 0, the average loss is 3.55.\n", "Up to batch 1, the average loss is 3.31.\n", "Up to batch 2, the average loss is 3.36.\n", "Up to batch 3, the average loss is 3.34.\n", "Up to batch 4, the average loss is 3.26.\n", "The average loss for epoch 12 is 3.26 and mean absolute error is 1.41.\n", "\n", "Epoch 00013: Learning rate is 0.0010.\n", "Up to batch 0, the average loss is 4.06.\n", "Up to batch 1, the average loss is 3.39.\n", "Up to batch 2, the average loss is 3.44.\n", "Up to batch 3, the average loss is 3.71.\n", "Up to batch 4, the average loss is 3.55.\n", "The average loss for epoch 13 is 3.55 and mean absolute error is 1.48.\n", "\n", "Epoch 00014: Learning rate is 0.0010.\n", "Up to batch 0, the average loss is 3.41.\n", "Up to batch 1, the average loss is 3.62.\n", "Up to batch 2, the average loss is 3.40.\n", "Up to batch 3, the average loss is 3.38.\n", "Up to batch 4, the average loss is 3.22.\n", "The average loss for epoch 14 is 3.22 and mean absolute error is 1.38.\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class CustomLearningRateScheduler(keras.callbacks.Callback):\n", " \"\"\"Learning rate scheduler which sets the learning rate according to schedule.\n", "\n", " Arguments:\n", " schedule: a function that takes an epoch index\n", " (integer, indexed from 0) and current learning rate\n", " as inputs and returns a new learning rate as output (float).\n", " \"\"\"\n", "\n", " def __init__(self, schedule):\n", " super(CustomLearningRateScheduler, self).__init__()\n", " self.schedule = schedule\n", "\n", " def on_epoch_begin(self, epoch, logs=None):\n", " if not hasattr(self.model.optimizer, \"lr\"):\n", " raise ValueError('Optimizer must have a \"lr\" attribute.')\n", " # Get the current learning rate from model's optimizer.\n", " lr = float(tf.keras.backend.get_value(self.model.optimizer.learning_rate))\n", " # Call schedule function to get the scheduled learning rate.\n", " scheduled_lr = self.schedule(epoch, lr)\n", " # Set the value back to the optimizer before this epoch starts\n", " tf.keras.backend.set_value(self.model.optimizer.lr, scheduled_lr)\n", " print(\"\\nEpoch %05d: Learning rate is %6.4f.\" % (epoch, scheduled_lr))\n", "\n", "\n", "LR_SCHEDULE = [\n", " # (epoch to start, learning rate) tuples\n", " (3, 0.05),\n", " (6, 0.01),\n", " (9, 0.005),\n", " (12, 0.001),\n", "]\n", "\n", "\n", "def lr_schedule(epoch, lr):\n", " \"\"\"Helper function to retrieve the scheduled learning rate based on epoch.\"\"\"\n", " if epoch < LR_SCHEDULE[0][0] or epoch > LR_SCHEDULE[-1][0]:\n", " return lr\n", " for i in range(len(LR_SCHEDULE)):\n", " if epoch == LR_SCHEDULE[i][0]:\n", " return LR_SCHEDULE[i][1]\n", " return lr\n", "\n", "\n", "model = get_model()\n", "model.fit(\n", " x_train,\n", " y_train,\n", " batch_size=64,\n", " steps_per_epoch=5,\n", " epochs=15,\n", " verbose=0,\n", " callbacks=[\n", " LossAndErrorPrintingCallback(),\n", " CustomLearningRateScheduler(lr_schedule),\n", " ],\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "c9be225b57f1" }, "source": [ "### 組み込みの Keras コールバック\n", "\n", "既存の Keras コールバックについては、[API ドキュメント](https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/)を読んで必ず確認してください。アプリケーションには、CSV へのロギング、モデルの保存、TensorBoard でのメトリクスの可視化、その他多数があります。" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "custom_callback.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 }