Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Tensor and Variable in Tensorflow

Tags:

tensorflow

What's the difference between Tensor and Variable in Tensorflow? I noticed in this stackoverflow answer, we can use Variable wherever Tensor can be used. However, I failed to do session.run() on a 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. 
like image 361
NoSegfault Avatar asked May 24 '17 19:05

NoSegfault


People also ask

What is the most important different between a variable and a tensor?

So, the most important difference between Variables and Tensors is mutability. The values in a Variable object can be updated (e.g., with the assign() function) as opposed to Tensors. “The values of tensor objects cannot be updated, and you can only create a new Tensor object with the new values.”

What is the difference between tensor and variable Pytorch?

Difference between Tensor and a Variable in Pytorch subtraction etc. tensors plus it calculates gradient. Tensors are usually constant. Variables represent changes in data.

Does TensorFlow use tensors?

Learn about Tensors, the multi-dimensional arrays used by TensorFlow. Tensors are multi-dimensional arrays with a uniform type (called a dtype ).


1 Answers

Variable is basically a wrapper on Tensor that maintains state across multiple calls to run, and I think makes some things easier with saving and restoring graphs. A Variable needs to be initialized before you can run it. You provide an initial value when you define the Variable, but you have to call its initializer function in order to actually assign this value in your session and then use the Variable. A common way to do this is with 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 capability and utility. You can specify a Variable as trainable (the default, actually), meaning that your optimizer will adjust it in an effort to minimize your cost function; you can specify where the Variable resides on a distributed system; you can easily save and restore Variables and graphs. Some more information on how to use Variables can be found here.

like image 160
Engineero Avatar answered Sep 21 '22 20:09

Engineero