keras.backend的clear_session()方法不会清除拟合数据

时间:2019-10-18 15:20:38

标签: python tensorflow keras tf.keras keras-2

我正在比较不同类型数据质量的拟合精度结果。 “好数据”是特征值中没有任何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

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

enter image description here

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

K.clear_session()

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

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

enter image description here

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

为进行比较,这是“不良”数据的独立拟合结果:

enter image description here

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

3 个答案:

答案 0 :(得分:1)

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-例如model = make_model(); model2 = model-> del model, model2-否则它们可能会持续存在。最后,tf的随机种子不如randomnumpy的重置那样容易,并且需要事先清除图形。


使用的功能/模块

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")

答案 1 :(得分:0)

您使用错误的方式使用K.clear_session(),要获得具有随机初始化的权重的模型,应删除旧模型(使用del关键字),然后继续创建新模型,并对其进行培训。

您可以在每个拟合过程之后使用K.clear_session()

答案 2 :(得分:0)

实例化一个新的同名模型对象还不够?

model = make_model()