[英]The clear_session() method of keras.backend does not clean up the fitting data
我正在比較不同類型數據質量的擬合精度結果。 “好數據”是特征值中沒有任何 NA 的數據。 “壞數據”是特征值中具有 NA 的數據。 應該通過一些值校正來修復“壞數據”。 作為值校正,它可能會用零或平均值替換 NA。
在我的代碼中,我試圖執行多個擬合程序。
查看簡化的代碼:
from keras import backend as K
...
xTrainGood = ... # the good version of the xTrain data
xTrainBad = ... # the bad version of the xTrain data
...
model = Sequential()
model.add(...)
...
historyGood = model.fit(..., xTrainGood, ...) # fitting the model with
# the original data without
# NA, zeroes, or the feature mean values
查看擬合精度plot,基於historyGood
數據:
之后,代碼重置存儲的 model 並使用“壞”數據重新訓練 model:
K.clear_session()
historyBad = model.fit(..., xTrainBad, ...)
根據historyBad
數據查看擬合過程結果:
可以注意到,初始精度> 0.7
,這意味着 model “記住”了之前的擬合。
為了比較,這是“壞”數據的獨立擬合結果:
如何將 model 重置為“初始”state?
K.clear_session()
不足以重置狀態並確保可重復性。 您還需要:
完成以下各項的代碼。
reset_seeds()
model = make_model() # example function to instantiate model
model.fit(x_good, y_good)
del model
K.clear_session()
tf.compat.v1.reset_default_graph()
reset_seeds()
model = make_model()
model.fit(x_bad, y_bad)
請注意,如果其他變量引用 model,您也應該del
它們 - 例如model = make_model(); model2 = model
model = make_model(); model2 = model
--> del model, model2
- 否則它們可能會持續存在。 最后, tf
隨機種子不像random
或numpy
那樣容易重置,並且需要事先清除圖形。
import tensorflow as tf import numpy as np import random import keras.backend as K def reset_seeds(): np.random.seed(1) random.seed(2) if tf.__version__[0] == '2': tf.random.set_seed(3) else: tf.set_random_seed(3) print("RANDOM SEEDS RESET")
您以錯誤的方式使用K.clear_session()
,要獲得具有隨機初始化權重的 model,您應該刪除舊的 model(使用del
關鍵字),然后繼續創建一個新的 Z20F35E630DAF44DB8C4C3F6。
您可以在每個擬合過程之后使用K.clear_session()
。
實例化一個新的model object同名還不夠?
model = make_model()
在單個文件中循環訓練多個模型時,我遇到了類似的問題。 我在 Keras/TF(2.5 版)上嘗試了很多東西,包括這個線程中的答案。 除了一件事之外沒有任何幫助 - 使用子進程模塊從另一個文件運行一個文件,這可以確保 kernel 每次都重新啟動。
以最簡單的方式,您可以將訓練代碼保存在單個文件中,並訪問它以運行初始 model 或從不同文件重新運行后續 model。 要從另一個文件運行一個文件,只需在第二個文件中執行:
run_no = [0,1,2,3]
for i in range(len()):
subprocess.run(["ipython", "your_main_file.ipynb", str(i)]) # for jupyter
#subprocess.run(["python3", "your_main_file.py", str(i)]) # for python
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.