【问题标题】:How to count total number of trainable parameters in a tensorflow model defined with graph loaded from .pb file?如何计算使用从 .pb 文件加载的图形定义的张量流模型中可训练参数的总数?
【发布时间】:2018-10-14 00:19:34
【问题描述】:

我想计算张量流模型中的参数。它类似于现有的问题,如下所示。

How to count total number of trainable parameters in a tensorflow model?

但如果模型是使用从 .pb 文件加载的图形定义的,则所有建议的答案都不起作用。基本上我用以下函数加载了图表。

def load_graph(model_file):

  graph = tf.Graph()
  graph_def = tf.GraphDef()

  with open(model_file, "rb") as f:
    graph_def.ParseFromString(f.read())

  with graph.as_default():
    tf.import_graph_def(graph_def)

  return graph

一个例子是在 tensorflow-for-poets-2 中加载 freeze_graph.pb 文件以进行再训练。

https://github.com/googlecodelabs/tensorflow-for-poets-2

【问题讨论】:

  • 我真的不明白另一个问题的答案是如何不起作用的。获得图表后,您只需要获取该特定图表的可训练变量。调用该函数后您尝试了什么?您能否提供一个重现问题的示例 .pbtxt 文件?

标签: tensorflow neural-network convolutional-neural-network


【解决方案1】:

据我了解,GraphDef 没有足够的信息来描述Variables。正如here 解释的那样,您将需要MetaGraph,它包含GraphDefCollectionDef,这是一个可以描述Variables 的映射。所以下面的代码应该给我们正确的可训练变量计数。

导出元图:

import tensorflow as tf

a = tf.get_variable('a', shape=[1])
b = tf.get_variable('b', shape=[1], trainable=False)
init = tf.global_variables_initializer()
saver = tf.train.Saver([a])

with tf.Session() as sess:
    sess.run(init)
    saver.save(sess, r'.\test')

导入 MetaGraph 并统计可训练参数的总数。

import tensorflow as tf

saver = tf.train.import_meta_graph('test.meta')

with tf.Session() as sess:
    saver.restore(sess, 'test')

total_parameters = 0
for variable in tf.trainable_variables():
    total_parameters += 1
print(total_parameters)

【讨论】:

  • 这是否意味着 .pb 文件不包含任何 trainable_variables?非常感谢。
  • @Yanjun 我认为节点都在那里。但是你无法分辨哪一个是 trainable_variables。或者加载后不在tf.trainable_variables()中。
猜你喜欢
  • 2016-11-04
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
相关资源
最近更新 更多