使用张量流导出神经网络的权重

时间:2016-12-08 08:27:02

标签: python machine-learning neural-network tensorflow

我使用tensorflow工具编写了神经网络。 一切正常,现在我想导出我的神经网络的最终权重,以制作一个单一的预测方法。 我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

您需要在培训结束时使用tf.train.Saver课程保存模型。

在初始化Saver对象时,您需要传递要保存的所有变量的列表。最好的部分是你可以在不同的计算图中使用这些保存的变量!

使用

创建Saver对象
# Assume you want to save 2 variables `v1` and `v2`
saver = tf.train.Saver([v1, v2])

使用tf.Session对象

保存变量
saver.save(sess, 'filename');

当然,您可以添加其他详细信息,例如global_step

您可以使用restore()功能在以后恢复变量。恢复的变量将自动初始化为这些值。

答案 1 :(得分:1)

上面的答案是保存/恢复会话快照的标准方法。但是,如果要将网络导出为单个二进制文件以便与其他tensorflow工具一起使用,则需要执行更多步骤。

首先,freeze the graph。 TF提供了相应的工具。我这样用它:

#!/bin/bash -x

# The script combines graph definition and trained weights into
# a single binary protobuf with constant holders for the weights.
# The resulting graph is suitable for the processing with other tools.


TF_HOME=~/tensorflow/

if [ $# -lt 4 ]; then
    echo "Usage: $0 graph_def snapshot output_nodes output.pb"
    exit 0
fi

proto=$1
snapshot=$2
out_nodes=$3
out=$4

$TF_HOME/bazel-bin/tensorflow/python/tools/freeze_graph --input_graph=$proto \
    --input_checkpoint=$snapshot \
    --output_graph=$out \
    --output_node_names=$out_nodes 

完成后,您可以optimize it for inference或使用any other tool

相关问题