TensorFlow模型保存后无法立即恢复的问题求助
问题:TensorFlow模型保存后立即恢复报错
我刚保存完TensorFlow模型就尝试恢复,结果一直报错。报错信息提示模型数据未完全转换,还出现了AttributeError: 'NoneType' object has no attribute 'restore'。我试着加了10秒sleep延迟,以为是保存是异步操作,但完全没用。奇怪的是相同代码在其他脚本里能正常运行,应该是时序或者代码细节出了问题。
报错信息:
venv2/local/lib/python2.7/site-packages/tensorflow/python/framework/meta_graph.py:636: RuntimeWarning: Unexpected end-group tag: Not all data was converted Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "src/python/kmer/learning.py", line 269, in <module> TensorflowTrainingJob.launch(resume_from_reduce = c.resume_from_reduce) File "src/python/kmer/learning.py", line 66, in launch job.execute() File "kmer/map_reduce.py", line 71, in execute self.distribute_workload() File "kmer/map_reduce.py", line 107, in distribute_workload self.run_batch(self.batch[index]) File "kmer/map_reduce.py", line 121, in run_batch batch[track] = self.transform(batch[track], track) File "src/python/kmer/learning.py", line 110, in transform saver.restore(session, tf.train.latest_checkpoint(os.path.join("model save location"))) AttributeError: 'NoneType' object has no attribute 'restore'
我的代码:
with tf.Session() as session: session.run(init) for epoch in range(5): o, c = session.run([optimizer, cost], feed_dict = {x: X, y: Y}) saver.save(session, "model save location") time.sleep(10) graph = tf.Graph() session = tf.Session(graph = graph) with graph.as_default(): saver = tf.train.import_meta_graph("model save location") saver.restore(session, tf.train.latest_checkpoint("model save location")))
问题分析与修复方案
咱先把核心问题拆解清楚:
1. 路径错误导致模型加载失败
你调用saver.save(session, "model save location")时,如果传入的是文件夹路径,TensorFlow会在该文件夹下生成多个模型文件(比如model.ckpt.meta、model.ckpt.index、checkpoint等)。但加载时tf.train.import_meta_graph需要指定完整的.meta文件路径,而不是文件夹路径。这直接导致saver加载失败变成None,才触发了AttributeError。
修复后的加载代码应该改成:
saver = tf.train.import_meta_graph("model save location/model.ckpt.meta")
2. 语法错误:多了一个右括号
最后一行代码里多了一个多余的右括号,这也是潜在问题,修正后:
saver.restore(session, tf.train.latest_checkpoint("model save location"))
3. 关于“异步保存”的误解
别被误导了,TensorFlow的saver.save()是同步操作,调用后会等待所有模型文件写入完成才返回,所以加sleep完全没必要,也解决不了问题。你遇到的根本不是时序问题,纯粹是代码里的路径和语法错误。
4. 额外建议:规范保存路径
为了避免后续再踩路径的坑,建议保存时明确指定文件名前缀,比如:
import os # 用os.path.join拼接路径,避免跨平台问题 save_path = os.path.join("model save location", "my_model.ckpt") saver.save(session, save_path)
这样加载时的.meta路径就更清晰:
meta_path = os.path.join("model save location", "my_model.ckpt.meta") saver = tf.train.import_meta_graph(meta_path)
内容的提问来源于stack exchange,提问作者Paghillect
相关产品推荐
相关产品推荐

