Export weights of neural network using tensorflow

…衆ロ難τιáo~ 提交于 2019-12-12 11:58:13

问题


I wrote neural-network using tensorflow tools. everything working and now I want to export the final weights of my neural network to make a single prediction method. How can I do this?


回答1:


You will need to save your model at the end of training by using the tf.train.Saver class.

While initializing the Saver object, you will need to pass a list of all the variables you wish to save. The best part is that you can use these saved variables in a different computation graph!

Create a Saver object by using,

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

Save your variables by using the tf.Session object,

saver.save(sess, 'filename');

Of course, you can add additional details like global_step.

You can restore the variables in the future by using the restore() function. The restored variables will be initialized to these values automatically.




回答2:


The answer above is the standard way to save/restore session snapshot. However, if you want to export your network as a single binary file for further use with other tensorflow tools, you'll need to perform few more steps.

First, freeze the graph. TF provides the corresponding tool. I use it like this:

#!/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 

Having done that, you can optimize it for inference, or use any other tool.



来源:https://stackoverflow.com/questions/41034888/export-weights-of-neural-network-using-tensorflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!