Keras 3 API 文件 / 回呼 API / SwapEMAWeights

SwapEMAWeights

[原始碼]

SwapEMAWeights 類別

keras.callbacks.SwapEMAWeights(swap_on_epoch=False)

在評估前後交換模型權重和 EMA 權重。

此回呼會在模型評估之前,將模型的權重值替換為優化器的 EMA 權重值(過去模型權重值的指數移動平均,實現「Polyak 平均」),並在評估後恢復先前的權重。

SwapEMAWeights 回呼應與設定 use_ema=True 的優化器一起使用。

請注意,權重會就地交換以節省記憶體。如果您在其他回呼中修改 EMA 權重或模型權重,則行為未定義。

範例

# Remember to set `use_ema=True` in the optimizer
optimizer = SGD(use_ema=True)
model.compile(optimizer=optimizer, loss=..., metrics=...)

# Metrics will be computed with EMA weights
model.fit(X_train, Y_train, callbacks=[SwapEMAWeights()])

# If you want to save model checkpoint with EMA weights, you can set
# `swap_on_epoch=True` and place ModelCheckpoint after SwapEMAWeights.
model.fit(
    X_train,
    Y_train,
    callbacks=[SwapEMAWeights(swap_on_epoch=True), ModelCheckpoint(...)]
)

參數

  • swap_on_epoch:是否在 on_epoch_begin()on_epoch_end() 執行交換。如果您想將 EMA 權重用於其他回呼,例如 ModelCheckpoint,則此選項非常有用。預設為 False