variable与get_variable

TensorFlow变量详解
本文详细对比了TensorFlow中tf.Variable与tf.get_variable的区别,包括它们在变量共享方面的应用及如何解决命名冲突问题,并介绍了多种初始化变量的方法。
部署运行你感兴趣的模型镜像

Variable

tensorflow中有两个关于variable的op,tf.Variable()tf.get_variable()下面介绍这两个的区别

tf.Variable与tf.get_variable()

tf.Variable(initial_value=None, trainable=True, collections=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, expected_shape=None, import_scope=None)
 
 
  • 1
tf.get_variable(name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=True, collections=None, caching_device=None, partitioner=None, validate_shape=True, custom_getter=None)
 
 
  • 1

区别

  1. 使用tf.Variable时,如果检测到命名冲突,系统会自己处理。使用tf.get_variable()时,系统不会处理冲突,而会报错
import tensorflow as tf
w_1 = tf.Variable(3,name="w_1")
w_2 = tf.Variable(1,name="w_1")
print w_1.name
print w_2.name
#输出
#w_1:0
#w_1_1:0
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
import tensorflow as tf

w_1 = tf.get_variable(name="w_1",initializer=1)
w_2 = tf.get_variable(name="w_1",initializer=2)
#错误信息
#ValueError: Variable w_1 already exists, disallowed. Did
#you mean to set reuse=True in VarScope?
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. 基于这两个函数的特性,当我们需要共享变量的时候,需要使用tf.get_variable()。在其他情况下,这两个的用法是一样的

get_variable()与Variable的实质区别

来看下面一段代码:

import tensorflow as tf

with tf.variable_scope("scope1"):
    w1 = tf.get_variable("w1", shape=[])
    w2 = tf.Variable(0.0, name="w2")
with tf.variable_scope("scope1", reuse=True):
    w1_p = tf.get_variable("w1", shape=[])
    w2_p = tf.Variable(1.0, name="w2")

print(w1 is w1_p, w2 is w2_p)
#输出
#True  False
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

看到这,就可以明白官网上说的参数复用的真面目了。由于tf.Variable() 每次都在创建新对象,所有reuse=True 和它并没有什么关系。对于get_variable(),来说,如果已经创建的变量对象,就把那个对象返回,如果没有创建变量对象的话,就创建一个新的。

random Tensor

可用于赋值给tf.Variable()的第一个参数

tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)

tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)

tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None)

tf.random_shuffle(value, seed=None, name=None)

tf.random_crop(value, size, seed=None, name=None)

tf.multinomial(logits, num_samples, seed=None, name=None)

tf.random_gamma(shape, alpha, beta=None, dtype=tf.float32, seed=None, name=None)

tf.set_random_seed(seed)
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

constant value tensor

tf.zeros(shape, dtype=tf.float32, name=None)

tf.zeros_like(tensor, dtype=None, name=None)

tf.ones(shape, dtype=tf.float32, name=None)

tf.ones_like(tensor, dtype=None, name=None)

tf.fill(dims, value, name=None)

tf.constant(value, dtype=None, shape=None, name='Const')
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

initializer

tf.constant_initializer(value=0, dtype=tf.float32)
tf.random_normal_initializer(mean=0.0, stddev=1.0, seed=None, dtype=tf.float32)
tf.truncated_normal_initializer(mean=0.0, stddev=1.0, seed=None, dtype=tf.float32)
tf.random_uniform_initializer(minval=0, maxval=None, seed=None, dtype=tf.float32)
tf.uniform_unit_scaling_initializer(factor=1.0, seed=None, dtype=tf.float32)
tf.zeros_initializer(shape, dtype=tf.float32, partition_info=None)
tf.ones_initializer(dtype=tf.float32, partition_info=None)
tf.orthogonal_initializer(gain=1.0, dtype=tf.float32, seed=None)
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

参考资料 
https://www.tensorflow.org/api_docs/python/state_ops/variables#Variable 
https://www.tensorflow.org/api_docs/python/state_ops/sharing_variables#get_variable 
https://www.tensorflow.org/versions/r0.10/api_docs/python/constant_op/ 
https://www.tensorflow.org/api_docs/python/state_ops/

转自:http://blog.youkuaiyun.com/u012436149/article/details/53696970

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

在函数中定义的局部变量默认只在函数内部有效,因此主程序不能直接访问这些变量。然而,可以通过特定方式将局部变量的值传递给主程序使用。以下是几种常见方法,结合引用内容进行说明: ### 3.1 返回局部变量的值 函数可以返回局部变量的值,这是最常见和推荐的方式。返回时,函数会将局部变量的值复制一份传递给调用者。这种方式适用于所有基本数据类型和不可变对象。 ```python def get_value(): x = 5 return x result = get_value() print(result) # 输出 5 ``` 局部变量 `x` 存储在栈中,函数返回时会复制其值给调用者,不会出现内存问题[^3]。 ### 3.2 返回局部静态变量的地址 如果需要返回局部变量的地址,必须确保该变量不会在函数返回后被销毁。可以通过将局部变量声明为静态变量实现这一点。静态变量存储在静态存储区,生命周期持续到程序结束。 ```cpp int* get_static_variable_address() { static int value = 10; return &value; // 返回静态局部变量的地址是安全的 } ``` 此方法适用于需要在多个函数调用之间保留变量值的情况[^3]。 ### 3.3 使用可变对象(如列表或字典) 对于可变对象,如 Python 中的列表或字典,可以通过修改对象内容来影响函数外部的数据结构。函数可以修改传递进来的可变对象,而无需直接返回局部变量。 ```python def modify_list(lst): lst.append(10) my_list = [1, 2, 3] modify_list(my_list) print(my_list) # 输出 [1, 2, 3, 10] ``` 由于列表是可变对象,函数可以直接修改其内容,从而影响主程序中的变量。 ### 3.4 使用全局变量 可以通过 `global` 关键字将函数内部的变量声明为全局变量,使其在主程序中可用。这种方法不推荐用于频繁的数据交互,因为它可能导致代码难以维护。 ```python def set_global_variable(): global x x = 20 set_global_variable() print(x) # 输出 20 ``` 该方式适用于需要在多个函数之间共享变量的场景,但需谨慎使用以避免命名冲突和副作用[^1]。 ### 3.5 使用闭包 通过闭包机制,函数可以返回另一个函数,使得外部函数能够访问其内部变量。闭包保持了变量的作用域,因此可以安全访问。 ```python def outer_function(): value = 15 def inner_function(): return value return inner_function closure = outer_function() print(closure()) # 输出 15 ``` 闭包提供了封装和数据隐藏的能力,适用于需要维护状态的场景。 ### 3.6 使用类和实例变量 面向对象编程提供了一种结构化的方式来管理状态。通过类的实例变量,可以在多个方法之间共享数据,同时避免全局变量的副作用。 ```python class DataHolder: def __init__(self): self.value = 25 def get_value(self): return self.value holder = DataHolder() print(holder.get_value()) # 输出 25 ``` 类和实例变量有助于组织代码并提高可维护性,特别适用于复杂的数据交互场景。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值