Tensorflow中的Tensor和Variable有什么区别 [英] What's the difference between Tensor and Variable in Tensorflow
问题描述
Tensorflow 中的 Tensor
和 Variable
有什么区别?我在 this stackoverflow answer,我们可以在任何可以使用 Tensor
的地方使用 Variable
.但是,我未能对 Variable
执行 session.run()
:
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.
推荐答案
Variable
基本上是对Tensor
在多次调用run
,我认为通过保存和恢复图形可以让一些事情变得更容易.Variable
需要先初始化,然后才能运行.您在定义 Variable
时提供了一个初始值,但您必须调用它的初始化函数才能在会话中实际分配此值,然后使用 Variable
.一种常见的方法是使用 tf.global_variables_initalizer()
.
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()
.
例如:
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)
至于为什么你使用 Variable
s 而不是 Tensor
s,基本上一个 Variable
是一个 Tensor
附加功能和实用性.您可以将 Variable
指定为可训练的(实际上是默认值),这意味着您的优化器将对其进行调整以尽量减少您的成本函数;您可以指定 Variable
在分布式系统上的位置;您可以轻松地保存和恢复变量
和图表.可以在此处找到有关如何使用 Variable
的更多信息.
As for why you use Variable
s instead of Tensor
s, 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 Variable
s and graphs. Some more information on how to use Variable
s can be found here.
这篇关于Tensorflow中的Tensor和Variable有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!