How do I get the current value of a Variable?

后端 未结 4 625
走了就别回头了
走了就别回头了 2020-12-04 21:49

Suppose we have a variable:

x = tf.Variable(...)

This variable can be updated during the training process using the assign() m

相关标签:
4条回答
  • 2020-12-04 22:19

    The only way to get the value of the variable is by running it in a session. In the FAQ it is written that:

    A Tensor object is a symbolic handle to the result of an operation, but does not actually hold the values of the operation's output.

    So TF equivalent would be:

    import tensorflow as tf
    
    x = tf.Variable([1.0, 2.0])
    
    init = tf.global_variables_initializer()
    
    with tf.Session() as sess:
        sess.run(init)
        v = sess.run(x)
        print(v)  # will show you your variable.
    

    The part with init = global_variables_initializer() is important and should be done in order to initialize variables.

    Also, take a look at InteractiveSession if you work in IPython.

    0 讨论(0)
  • 2020-12-04 22:21

    tf.Print can simplify your life!

    tf.Print will print the value of the tensor(s) you tell it to print at the moment where the tf.Print line is called in your code when your code is evaluated.

    So for example:

    import tensorflow as tf
    x = tf.Variable([1.0, 2.0])
    x = tf.Print(x,[x])
    x = 2* x
    
    tf.initialize_all_variables()
    
    sess = tf.Session()
    sess.run()
    

    [1.0 2.0 ]

    because it prints the value of x at the moment when the tf.Print line is. If instead you do

    v = x.eval()
    print(v)
    

    you will get:

    [2.0 4.0 ]

    because it will give you the final value of x.

    0 讨论(0)
  • 2020-12-04 22:26

    As they cancelled tf.Variable() in tensorflow 2.0.0,

    If you want to extract values from a tensor(ie "net"), you can use this,

    net.[tf.newaxis,:,:].numpy().
    
    0 讨论(0)
  • 2020-12-04 22:28

    In general, session.run(x) will evaluate only the nodes that are necessary to compute x and nothing else, so it should be relatively cheap if you want to inspect the value of the variable.

    Take a look at this great answer https://stackoverflow.com/a/33610914/5543198 for more context.

    0 讨论(0)
提交回复
热议问题