Tensorflow中的Tensor和Variable有什么区别 [英] What's the difference between Tensor and Variable in Tensorflow

查看:32
本文介绍了Tensorflow中的Tensor和Variable有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Tensorflow 中的 TensorVariable 有什么区别?我在 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)

至于为什么你使用 Variables 而不是 Tensors,基本上一个 Variable 是一个 Tensor附加功能和实用性.您可以将 Variable 指定为可训练的(实际上是默认值),这意味着您的优化器将对其进行调整以尽量减少您的成本函数;您可以指定 Variable 在分布式系统上的位置;您可以轻松地保存和恢复变量和图表.可以在此处找到有关如何使用 Variable 的更多信息.

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.

这篇关于Tensorflow中的Tensor和Variable有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆