如何从graph.pbtxt中将Tensorflow训练后的权重提取到原始数据

时间:2018-10-02 16:56:29

标签: tensorflow neural-network conv-neural-network cudnn

我已经训练了一个具有以下功能的自定义神经网络:

tf.estimator.train_and_evaluate

经过正确培训后,它包含以下文件:

  • 检查点
  • events.out.tfevents.1538489166.ti
  • model.ckpt-0.data-00000-of-00002
  • model.ckpt-0.index
  • model.ckpt-10.data-00000-of-00002
  • model.ckpt-10.index评估
  • graph.pbtxt
  • model.ckpt-0.data-00001-of-00002
  • model.ckpt-0.meta
  • model.ckpt-10.data-00001-of-00002
  • model.ckpt-10.meta

现在,我需要将每层的 weight biases 导出到原始数据结构中,例如数组numpy

我已经阅读了TensorFlow以及其他主题的多个页面,但是都找不到这个问题。我想做的第一件事是按照此处的建议将fils和frozen.py放到graph.pd中:

Tensorflow: How to convert .meta, .data and .index model files into one graph.pb file

但是仍然没有解决主要问题。

2 个答案:

答案 0 :(得分:0)

如果仅希望评估张量,则可以签出the docs say。但是如果你想部署网络后,您可以查看TensorFlow this question,它可能是目前性能最高的。或者,如果您想将此网络导出到其他框架并在其中使用它们,则可以为此实际使用serving

答案 1 :(得分:0)

如果严格要求在numpy数组中保存权重和偏差,则可以遵循以下示例:

# In a TF shell, define all requirements and call the model function 
y = model(x, is_training=False, reuse=tf.AUTO_REUSE) # For example

调用此函数后,您可以通过运行来查看图中的所有变量

tf.global_variables()

您需要从最新的检查点(例如 ckpt_dir )还原所有这些变量,然后执行每个变量以获取最新值。

checkpoint = tf.train.latest_checkpoint('./model_dir/')
fine_tune = tf.contrib.slim.assign_from_checkpoint_fn(checkpoint,
                                                      tf.global_variables(),
                                                      ignore_missing_vars=True)


sess = tf.Session()
sess.run(tf.global_variables_initializer())
gv = sess.run(tf.global_variables())

现在 gv 将是所有变量值(权重和偏差)的列表;您可以通过索引- gv [5] 等访问任何单个组件。也可以将整个对象转换为数组并使用numpy保存。

np.save('my_weights', np.array(gv))

这会将您所有的权重和偏差保存为当前工作目录中的numpy数组-'my_weights.npy'。

希望这会有所帮助。