Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/ja/addons/tutorials/optimizers_lazyadam.ipynb
25118 views
Kernel: Python 3
#@title Licensed under the Apache License, Version 2.0 # 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.

概要

このガイドでは、アドオンパッケージの LazyAdam オプティマイザを使用する方法を紹介します。

LazyAdam

LazyAdam は、スパースな更新をより効率的に処理する Adam オプティマイザのバリアントです。従来の Adam アルゴリズムは、トレーニング可能な変数ごとに 2 つの移動平均アキュムレータを維持します。 アキュムレータはすべてのステップで更新されます。このクラスは、スパースな変数の勾配更新をレイジーに処理します。 その時点のバッチに表示されるスパースな変数インデックスの移動平均アキュムレータのみが更新され、すべてのインデックスのアキュムレータは更新されません。アプリケーションによっては、従来の Adam オプティマイザと比べてモデルトレーニング処理能力を大幅に改善できます。 ただし、従来の Adam アルゴリズムとは若干異なるセマンティクスを提供するため、経験的結果が異なる可能性があります。

セットアップ

!pip install -U tensorflow-addons
import tensorflow as tf import tensorflow_addons as tfa
# Hyperparameters batch_size=64 epochs=10

モデルの構築

model = tf.keras.Sequential([ tf.keras.layers.Dense(64, input_shape=(784,), activation='relu', name='dense_1'), tf.keras.layers.Dense(64, activation='relu', name='dense_2'), tf.keras.layers.Dense(10, activation='softmax', name='predictions'), ])

データの準備

# Load MNIST dataset as NumPy arrays dataset = {} num_validation = 10000 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() # Preprocess the data x_train = x_train.reshape(-1, 784).astype('float32') / 255 x_test = x_test.reshape(-1, 784).astype('float32') / 255

トレーニングと評価

一般的な keras オプティマイザを新しい tfa オプティマイザに置き換えるだけです。

# Compile the model model.compile( optimizer=tfa.optimizers.LazyAdam(0.001), # Utilize TFA optimizer loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy']) # Train the network history = model.fit( x_train, y_train, batch_size=batch_size, epochs=epochs)
# Evaluate the network print('Evaluate on test data:') results = model.evaluate(x_test, y_test, batch_size=128, verbose = 2) print('Test loss = {0}, Test acc: {1}'.format(results[0], results[1]))