What is the difference between tensor and variable in tensorflow

What is the difference between Tensor and Variable in Tensorflow? I have noticed in https://stackoverflow.com/a/167188/168 , we can use Variable wherever Tensor can be used. However, I was unable to execute session.run() on Variable :

 A = tf.zeros([10]) # A is a Tensor B = tf.Variable([111, 11, 11]) # B is a Variable sess.run(A) # OK. Will return the values in A sess.run(B) # Error. 
+7
tensorflow
source share
1 answer

Variable is basically a Tensor wrapper that maintains state through multiple run calls, and I think some things make it easier to save and restore graphs. Before starting it, you must initialize the variable. You specify the initial value when defining a variable, but you must call its initialization function to actually assign that value in your session and then use the variable. The usual way to do this is tf.global_variables_initalizer() .

For example:

 import tensorflow as tf test_var = tf.Variable([111, 11, 1]) sess = tf.Session() sess.run(test_var) # Error! sess.run(tf.global_variables_initializer()) # initialize variables sess.run(test_var) # array([111, 11, 1], dtype=int32) 

As for why you use variables instead of tensors, basically a variable is a tensor with additional features and usefulness. You can specify the variable as trained (by default, in fact), which means that your optimizer will configure it to minimize your cost function; You can specify where the variable is located in a distributed system; You can easily save and restore variables and graphs. More information on how to use variables can be found here .

+7
source share

All Articles