【问题标题】:How to save a trained tensorflow model for later use for application?如何保存经过训练的 tensorflow 模型以供以后使用?
【发布时间】:2018-04-26 23:54:33
【问题描述】:

我是 tensorflow 的初学者,所以如果这是一个愚蠢的问题并且答案很明显,请原谅。

我创建了一个 Tensorflow 图,从 X 和 y 的占位符开始,我优化了一些代表我的模型的张量。图的一部分是可以计算预测向量的东西,例如对于线性回归类似

y_model = tf.add(tf.mul(X,w),d)
y_vals = sess.run(y_model,feed_dict={....})

训练完成后,我得到了可接受的 w 和 d 值,现在我想保存我的模型以备后用。然后,在另一个 python 会话中,我想恢复模型以便我可以再次运行

## Starting brand new python session
import tensorflow as tf
## somehow restor the graph and the values here: how????
## so that I can run this:
y_vals = sess.run(y_model,feed_dict={....})

对于一些不同的数据并取回 y 值。

我希望它以这样一种方式工作,即用于从占位符计算 y 值的图形也被存储和恢复 - 只要占位符得到正确的数据,这应该在没有用户的情况下透明地工作(那个谁应用模型)需要知道图形的样子)。

据我了解 tf.train.Saver().save(..) 只保存变量,但我也想保存图表。我认为 tf.train.export_meta_graph 在这里可能是相关的,但我不明白如何正确使用它,文档对我来说有点神秘,示例甚至没有在任何地方使用 export_meta_graph。

【问题讨论】:

  • 我不明白从该页面恢复我的模型的步骤。在执行 export_meta_graph("mymodel") 之后,我尝试了 ret = tf.train.import_meta_graph("mymodel") ,但是当我尝试 ret.restore(sess,"mymodel") 时,我收到错误“无法打开表文件./metagraph:数据丢失:不是 sstable”。如果我改为尝试使用 Saver.save(sess,"storedsess") 存储“storedsess”的 ret.restore(sess,"storedsess") 我收到错误“在检查点文件 storedsess 中找不到张量名称'变量'”.. .
  • 现在基本上已经回答了这个问题:stackoverflow.com/questions/38829641/…

标签: tensorflow


【解决方案1】:

来自docs,试试这个:

# Create some variables.
v1 = tf.Variable(..., name="v1")
v2 = tf.Variable(..., name="v2")
...
# Add an op to initialize the variables.
init_op = tf.global_variables_initializer()

# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Later, launch the model, initialize the variables, do some work, save the
# variables to disk.
with tf.Session() as sess:
  sess.run(init_op)
  # Do some work with the model.
  ..
  # Save the variables to disk.
  save_path = saver.save(sess, "/tmp/model.ckpt")
  print("Model saved in file: %s" % save_path)

你可以指定路径。

如果你想恢复模型,试试:

with tf.Session() as sess:
    saver = tf.train.import_meta_graph('/tmp/model.ckpt.meta')
    saver.restore(sess, "/tmp/model.ckpt")

【讨论】:

    【解决方案2】:

    在 TensorFlow 中保存图形:

    import tensorflow as tf
    
    # Create some placeholder variables
    x_pl = tf.placeholder(..., name="x")
    y_pl = tf.placeholder(..., name="y")
    
    # Add some operation to the Graph
    add_op = tf.add(x, y)
    
    with tf.Session() as sess:
    
        # Add variable initializer
        init = tf.global_variables_initializer()
    
        # Add ops to save variables to checkpoints
        # Unless var_list is specified Saver will save ALL named variables
        # in Graph
        # Optionally set maximum of 3 latest models to be saved
        saver = tf.train.Saver(max_to_keep=3)
    
        # Run variable initializer
        sess.run(init)
    
        for i in range(no_steps):
            # Feed placeholders with some data and run operation
            sess.run(add_op, feed_dict={x_pl: i+1, y_pl: i+5})
            saver.save(sess, "path/to/checkpoint/model.ckpt", global_step=i)
    

    这将保存以下文件:

    1) 元图

    .meta文件:

    • MetaGraph 的 MetaGraphDef 协议缓冲区表示,它保存完整的 Tf Graph 结构,即描述数据流和与之关联的所有元数据的 GraphDef,例如所有变量、操作、集合等。

    • 导入图结构将重新创建图及其所有变量,然后可以从检查点文件中恢复这些变量的对应值

    • 如果您不想恢复图形,但是您可以通过重新执行构建模型的 Python 代码来重建 MetaGraphDef 中的所有信息。您必须先重新创建完全相同的变量,然后才能从检查点恢复它们的值

    • 由于并不总是需要 Meta Graph 文件,您可以使用 write_meta_graph=False 关闭在 saver.save 中写入文件

    2) 检查点文件

    .data文件:

    • 包含tf.train.Saver() 中列出的所有已保存变量的值的二进制文件(默认为所有变量)

    .index文件:

    • 描述所有张量及其元数据检查点文件的不可变表:

    • 记录保存的最新检查点文件

    在 TensorFlow 中恢复图形:

    import tensorflow as tf
    
    latest_checkpoint = tf.train.latest_checkpoint("path/to/checkpoint")
    
    # Load latest checkpoint Graph via import_meta_graph:
    #   - construct protocol buffer from file content
    #   - add all nodes to current graph and recreate collections
    #   - return Saver
    saver = tf.train.import_meta_graph(latest_checkpoint + '.meta')
    
    # Start session
    with tf.Session() as sess:
    
        # Restore previously trained variables from disk
        print("Restoring Model: {}".format("path/to/checkpoint"))
        saver.restore(sess, latest_checkpoint)
    
        # Retrieve protobuf graph definition
        graph = tf.get_default_graph()
    
        print("Restored Operations from MetaGraph:")
        for op in graph.get_operations():
           print(op.name)
    
        # Access restored placeholder variables
        x_pl = graph.get_tensor_by_name("x_pl:0")
        y_pl = graph.get_tensor_by_name("y_pl:0")
    
        # Access restored operation to re run
        accuracy_op = graph.get_tensor_by_name("accuracy_op:0")
    

    这只是一个简单的基本示例,有关工作实现,请参阅here

    【讨论】:

    • 这是一个很好的答案,也是我能找到的唯一一个在新文件中而不是在同一执行中初始化保护程序的示例。
    • 谢谢@JavidPack :-)
    【解决方案3】:

    为了保存图表,您需要冻结图表。 这是用于冻结图形的 python 脚本:https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py

    这里是冻结图形的代码sn-p:

    from tensorflow.python.tools import freeze_graph
    freeze_graph.freeze_graph(input_graph_path, input_saver_def_path,
                                input_binary, checkpoint_path,  output_node
                                restore_op_name, filename_tensor_name,
                                output_frozen_graph_name, True, "")
    

    其中输出节点对应于输出张量变量。

    output = tf.nn.softmax(outer_layer_name,name="output")
    

    【讨论】:

    • 冻结时是否可以将模型的所有最后一个节点命名为输出,或者必须手动完成。例如,在 DNN 分类器演示 (tensorflow.org/get_started/monitors) 中,我看不到最后一个节点的任何名称,您可以在初始模型中轻松找到。
    • 不,名称 output 是我给神经网络中最后一个 softmax 层的东西。我浏览了 DNN 分类器,如果你只想保存图形,它有一个名为 export 和 export_savedmodel 的参数。至于输出节点名称,我不太确定 DNN 分类器。我需要输出节点名称,因为我在 android 上部署了模型。我找到了这个例子,但它适用于 keras [link] (github.com/llSourcell/…)
    猜你喜欢
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    相关资源
    最近更新 更多