如何修复Python聊天机器人代码报错Attempted to use a closed Session
问题原因
- 第一个
ValueError是首次运行代码时还没有生成过model.tflearn模型 checkpoint 文件,加载不存在的文件触发报错。 - 后续的
RuntimeError是TFLearn对TensorFlow 2.x的eager execution模式兼容差,加载失败进入训练分支时,会话被提前关闭导致无法正常训练。 - 额外还有两处代码逻辑错误,会导致后续聊天功能运行异常。
修复步骤
1. 新增TensorFlow兼容配置
在导入tensorflow的代码后,立即添加关闭eager execution的配置:
import tensorflow as tf tf.compat.v1.disable_eager_execution() # 新增这行
2. 修正chat函数的两处逻辑错误
原chat函数里的置信度判断和响应输出缩进错误,修改为以下内容:
def chat(): print("Start talking with the bot (type quit to stop)!") while True: inp = input("You: ") if inp.lower() == "quit": break results = model.predict([bag_of_words(inp, words)]) results_index = numpy.argmax(results) tag = labels[results_index] # 修正:predict返回二维数组,取第一个样本的置信度 if results[0][results_index] >0.7: for tg in data["intents"]: if tg['tag'] == tag: responses = tg['responses'] # 修正:输出缩进移到匹配成功的分支内,避免乱输出 print(random.choice(responses)) else: print ('I did not get you')
3. 清理旧缓存后重新运行
删除运行目录下之前生成的data.pickle、model.tflearn开头的所有缓存文件,重新运行代码即可正常训练,训练完成后会自动保存模型,下次运行会直接加载无需重新训练。
注意事项
如果运行时提示找不到intents.json,把with open('/content/sample_data/intents.json') as file:里的路径替换为你本地intents.json的实际存放路径。
可选优化(非必须)
可以调整模型加载逻辑,避免首次运行无意义的加载报错:
先导入os模块,把原来的模型加载部分替换为:
import os model = tflearn.DNN(net) # 只有模型文件存在时才加载 if os.path.exists("model.tflearn.index"): model.load("model.tflearn") else: model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True) model.save("model.tflearn")
内容的提问来源于stack exchange,提问作者Kevin Tracey
相关产品推荐
相关产品推荐

