Skip to main content
 首页 » 编程设计

python之keras.backend的clear_session()方法没有清理拟合数据

2024年11月01日6findumars

我正在比较不同类型数据质量的拟合精度结果。 “好数据”是特征值中没有任何 NA 的数据。 “坏数据”是特征值中带有 NA 的数据。 “坏数据”应该通过一些值修正来修复。作为值(value)修正,它可能会用零或平均值替换 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 
 

根据 historyGood 数据查看拟合精度图:

之后,代码重置存储的模型并使用“坏”数据重新训练模型:

K.clear_session() 
 
historyBad = model.fit(..., xTrainBad, ...) 

根据historyBad数据查看拟合过程结果:

可以注意到,初始精度 > 0.7,这意味着模型“记住”了之前的拟合。

为了比较,这是“坏”数据的独立拟合结果:

如何将模型重置为“初始”状态?

请您参考如下方法:

K.clear_session() 不足以重置状态并确保再现性。您还需要:

  • 设置(和重置)随机种子
  • 重置 TensorFlow 默认图
  • 删除之前的模型

完成以下各项的代码。

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) 

请注意,如果其他变量引用模型,您也应该del它们 - 例如模型 = 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")