我需要創建一個類來搜索模型的最佳學習率,在每個批次中將學習率的值增加 %5。我已經看到 on_train_batch_end() 回呼,但我無法設定它。
uj5u.com熱心網友回復:
請參閱 tf.keras.callbacks.ReduceLROnPlateau 的來源。
https://github.com/keras-team/keras/blob/v2.6.0/keras/callbacks.py#L2581-L2701
秘密命令是
tf.keras.backend.set_value(self.model.optimizer.lr)
您不能分配它,也不能使用 tf.Variable.assign(),因為在 Keras 中,如果構建尚未發生,它可能是成員,或者在構建之后它可能是一個變數。
uj5u.com熱心網友回復:
降低高原上的學習率僅在一個時期結束時調整學習率。它不會在批次結束時到期。為此,您需要創建一個自定義回呼。如果我理解正確,您希望在每批結束時將學習率降低 5%。下面的代碼將為您做到這一點。在回呼模型中是編譯模型的名稱。freq 是一個整數,決定了學習率的調整頻率。如果 freq=1,它將在每批結束時進行調整。如果 freq=2 它將在每隔一個批次進行調整等。reduction_pct 是一個浮點數。它是學習率將降低的百分比。Verbose 是一個布林值。如果verbose=True,每次調整學習率時都會列印輸出,顯示用于剛剛完成的批次的LR和將用于下一批的LR。
class ADJLR_ON_BATCH(keras.callbacks.Callback):
def __init__ (self, model, freq, reduction_pct, verbose):
super(ADJLR_ON_BATCH, self).__init__()
self.model=model
self.freq=freq
self.reduction_pct =reduction_pct
self.verbose=verbose
self.adj_batch=freq
self.factor= 1.0-reduction_pct * .01
def on_train_batch_end(self, batch, logs=None):
lr=float(tf.keras.backend.get_value(self.model.optimizer.lr)) # get the current learning rate
if batch 1 == self.adj_batch:
new_lr=lr * self.factor
tf.keras.backend.set_value(self.model.optimizer.lr, new_lr) # set the learning rate in the optimizer
self.adj_batch =self.freq
if verbose:
print('\nat the end of batch ',batch 1, ' lr was adjusted from ', lr, ' to ', new_lr)
下面是一個使用回呼的示例,其中包含我相信您希望使用的值
model=your_model_name # variable name of your model
reduction_pct=5.0 # reduce lr by 5%
verbose=True # print out each time the LR is adjusted
frequency=1 # adjust LR at the end of every batch
callbacks=[ADJLR_ON_BATCH(model, frequency, reduction_pct, verbose)]
請記住在 model.fit 中包含 callbacks=callbacks。下面是結果列印輸出的示例,以 0.001 的 LR 開始
at the end of batch 1 lr was adjusted from 0.0010000000474974513 to 0.0009500000451225787
1/374 [..............................] - ETA: 1:14:55 - loss: 9.3936 - accuracy: 0.3333
at the end of batch 2 lr was adjusted from 0.0009500000160187483 to 0.0009025000152178108
at the end of batch 3 lr was adjusted from 0.0009025000035762787 to 0.0008573750033974647
3/374 [..............................] - ETA: 25:04 - loss: 9.1338 - accuracy: 0.4611
at the end of batch 4 lr was adjusted from 0.0008573749801144004 to 0.0008145062311086804
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/341009.html
