如何恢复可变对象 [英] How to restore variable object
问题描述
我想恢复一个可变对象.也就是说,我想在反序列化后有一个 tensorflow.Variables
类型的对象.
I want to restore a variable object. That is, I want to have an object of type tensorflow.Variables
after deserialization.
我尝试使用 MetaGraph.这是一个最小的例子.序列化:
I try to use MetaGraph. Here is a minimal example. Serialization:
import tensorflow as tf
var = tf.Variable(101)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver()
tf.add_to_collection('var', var)
saver.save(sess, 'data/sess')
反序列化
import tensorflow as tf
with tf.Session() as sess:
saver = tf.train.import_meta_graph('data/sess.meta')
saver.restore(sess, 'data/sess')
var = tf.get_collection('var')[0]
print(var)
print(type(var))
# Output:
# Tensor("Variable:0", shape=(), dtype=int32_ref)
# <class 'tensorflow.python.framework.ops.Tensor'>
print(tf.get_collection('variables'))
# [<tensorflow.python.ops.variables.Variable object at 0x10edd1d30>]
test_var = tf.get_collection('variables')[0]
print(test_var.name)
# Variable:0
问题是 tf.get_collection
返回 tf.Tensor
对象,而不是tf.Variable
.但是我可以在 variables
集合中看到 tf.Variable
对象.
The issue is that tf.get_collection
return tf.Tensor
object, not
tf.Variable
. But I can see tf.Variable
objects in variables
collection.
恢复Variable
对象的正确方法是什么?
What is the correct way of restoring Variable
object?
推荐答案
使用您报告的代码,您可以正确恢复变量和张量.但是,我建议您使用更惯用的方法来创建和恢复变量,以便您更好地管理图形元素.
Using the code that you reported, you are correctly restoring your variables and tensors. However, I suggest you a more idiomatic way to create and restore the variables that will let you manage better the graph elements.
首先,您应该使用 tf.get_variable 函数来创建并初始化一个变量.使用参数 name 您应该将名称关联到您的变量.这将允许您在还原步骤后检索它.
First of all, you should use tf.get_variable function to create and to initialize a variable. Using the parameter name you should associate a name to your variable. This will allow you to retrieve it after the restore step.
在您报告的代码中正确实现了恢复步骤.如果您想获得对您的变量的引用,您应该再次使用 tf.get_variable
函数而不指定任何初始化程序或形状.TensorFlow 作用域管理器会识别出您已经有一个具有您选择的名称的初始化变量,它会返回它.请参阅以下代码以更好地演示此过程:
The restore step is correctly implemented in the code that you have reported. If you want to get the reference to your variable you should again use the tf.get_variable
function without specifying any initializer or shape. The TensorFlow scope manager will recognize that you already have a initialized variable with the name that you have chosen and it will return it. See the following code for a better demonstration of this procedure:
import tensorflow as tf
with tf.Session() as sess:
saver = tf.train.import_meta_graph('data/sess.meta')
saver.restore(sess, 'data/sess')
# suppose that your variable is called "variable_101"
var = tf.get_variable("variable_101")
# var will represent your initialized variable
这篇关于如何恢复可变对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!