TensorFlow中的get_variable()

最近在学习使用TensorFlow,一直没有搞明白其中的get_variable()与Variable()的区别,今天特意在网上搜了一些资料,这里将一篇写的简单易懂的一篇外国博客分享给大家:http://www.machinelearningtutorial.net/fullpage/an-introduction-to-tensorflow-variables/ 。为了巩固自己的理解,自己先翻译一波。

TensorFlow中变量的定义

TensorFlow使用变量存储张量,通过一定的操作可以允许你读取或者修改张量。

变量的可以使用以下的方法创建:

import tensorflow as tf 
var = tf.Variable(tf.truncated_normal([3]))

TensorFlow中的变量是惰性加载的,如果你想看到变量的值,必须建立一个对话(Session)

import tensorflow as tf 
var = tf.Variable(tf.truncated_normal([3]))
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(var))

创建和初始化

TensorFlow一般有两种方法创建变量:

通过tf.Variable()

weights = tf.Variable(tf.random_normal([784, 200]), name='weights')

通过tf.get_variable()

import tensorflow as tf 
weights = tf.get_variable(name='weights', shape=[784, 200], initializer=tf.random_normal_initializer())

选择tf.Variable还是tf.get_variable()

推荐使用tf.get_variable()。在需要共享变量的场合,可以使得代码重构更加方便

关于tf.get_variable()的细节

tf.get_variable()可以重新使用一个已经存在的同名变量或者重新创建一个新的变量。比如:

a = tf.get_variable(name='v', shape=[1])

在Python中这个变量保存为a,而在TensorFlow中这个变量保存为v。如果进一步定义变量b

b = tf.get_variable(name='v', shape=[1])
# ValueError: Variable v already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at:

出现这个错误的原因在于,在使用TensorFlow中一个已经定义的变量时,需要申明reuse。为了重复使用tf.get_variable()定义的变量,必须在variable_scope中声明reuse

with tf.variable_scope('one'):
    a = tf.get_variable('v', [2])
with tf.variable_scope('one', reuse=True):
    c = tf.get_variable('v', [2])
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值