我在尝试使用交叉验证评估命名实体识别任务的训练。问题在于keras模型未能正确清除,无法进行交叉验证的其他迭代。
我已经尝试了在Stack Overflow、GitHub或论坛中建议的几种清除模型的解决方案,但都没有效果。我将重点讨论两个似乎接近标准解决方案的方法。
第一个方法:我在交叉验证循环外创建模型(架构+编译),但在循环内调用keras.backend.clear_session()。我得到了错误:“tensorflow.python.framework.errors_impl.InvalidArgumentError: Tensor words_input:0, specified in either feed_devices or fetch_devices was not found in the Graph”。
第二个方法:我在循环内创建模型并在循环内调用keras.backend.clear_session()。我得到了错误:“Duplicate node name in graph: ‘training/Nadam/Pow’”。
很抱歉代码可能不够清晰,但由于隐私问题我无法展示代码
第一个方法
kf = KFold(folds, shuffle=True)model = create_model(...)for i, (train_idx, test_idx) in enumerate(kf.split(...)): ... train_batch, train_batch_len = createBatches(train_set) test_batch, test_batch_len = createBatches(test_set) model, _, _= training(model, ..., epochs=epochs) clear_session()
第二个方法
kf = KFold(folds, shuffle=True)for i, (train_idx, test_idx) in enumerate(kf.split(...)): model = create_model(...) ... train_batch, train_batch_len = createBatches(train_set) test_batch, test_batch_len = createBatches(test_set) model, _, _= training(model, ..., epochs=epochs) clear_session()
在create_model()中,我们定义了层的架构并调用compile(…)
我确实希望在kfold的每次迭代中使用一个清除后的模型进行交叉验证。另外需要提及的是,我尝试过在每次迭代开始时设置初始权重,但由于我在数百个epoch上工作,这似乎引起了存储问题——据我所知,keras在每个epoch都会创建节点。这样做时,如果我使用少量epoch,整个kfold运行良好,但当我在数百个epoch上运行时,训练性能在第二次迭代后F1分数保持在0。
回答:
你还需要在清除会话之前删除模型
from keras import backend as Kdel modelK.clear_session()gc.collect()