How to restore a variable object

I want to restore a variable object. That is, I want to have an object of type tensorflow.Variablesafter deserialization.

I am trying 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')

Deserialization

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

The problem is that the object tf.get_collectionreturns tf.Tensor, not tf.Variable. But I see objects tf.Variablein the collection variables.

What is the correct way to restore an object Variable?

+1
source share
1 answer

, , . , , .

, tf.get_variable . , . .

, . , tf.get_variable, . TensorFlow , , , . , . :

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
+3

Source: https://habr.com/ru/post/1672184/


All Articles