空飛ぶ気まぐれ雑記帳

主に趣味とかプログラミングについて扱います。

Tensorflowでregularizationが効いていなかった話

Tensorflow 2.0で自分でTraining loopを書いている人は一度公式のドキュメント読んだほうがいいと思った
www.tensorflow.org

今まで知らなかったけど、Training loopを自分で書くケースでは正則化項のlossを自分で足し込む必要があるらしい。
該当箇所は以下。

There are two important things to note about this sort of regularization.

First: if you are writing your own training loop, then you need to be sure to ask the model for its regularization losses.

result = l2_model(features)
regularization_loss=tf.add_n(l2_model.losses)

Second: This implementation works by adding the weight penalties to the model's loss, and then applying a standard optimization procedure after that.

There is a second approach that instead only runs the optimizer on the raw loss, and then while applying the calculated step the optimizer also applies some weight decay. This "Decoupled Weight Decay" is seen in optimizers like optimizers.FTRL and optimizers.AdamW.

一応和訳。後半はだいぶ意訳ですが、知らんかった。

これらの正則化には2点注意すべきことがあります。
1. もし、自分自身で学習ループを描いているならば、あなたは正則化損失を自分で確認する必要があります。

result = l2_model(features)
regularization_loss=tf.add_n(l2_model.losses)

2. この実装はモデルの誤差関数に足し込み、そして標準的な最適化処理を実行することで動作します。
生の誤差関数の最適化だけを実行する代わりの2番目のアプローチとして、Weight decayを最適化時に計算して適用する方法があります。
これは「Decoupled Weight Decay」と呼ばれ、optimizers.FTRLやoptimizers.AdamWがこれに当たります。


和訳終わり、ちなみにですがまだ日本語ドキュメントは更新されてないんで、上記の記述はありません。
おそらく途中で翻訳者の人が力尽きたんでしょうかね。

それはさておき、正則化の件は気をつけましょう。
Tensorflow probabiltyとか使ってると本当に悲しいことになるんで。