您的位置:首页 > 其它

tf.Variable

2016-11-15 16:24 113 查看
class tf.Variable

一个变量通过调用run() 方法维持图的状态。你通过构造variable 类的实例来添加一个变量到图中。

Variable() 构造器需要一个初始值,可以是任意类型和shape 的Tensor。初始值定义了变量的type和shape。构造完成之后,变量的type和shape 是固定的。可以使用assign 方法来修改变量的值。

如果你想修改变量的shape,你必须使用assign 操作,并且 validate_shpe=False

就像任何Tensor,通过Variable() 创建的variable,可以用作图中其他操作节点的输入。另外,所有操作承载的Tensor 类传递给variables. 所以你可以仅仅通过对变量执行算术来对图中添加节点。

#!/usr/bin/env python
# coding=utf-8

import tensorflow as tf
#create a variable
W=tf.Variable(<initial-value>,name=<optional-name>)

#use the variable in the graph like any Tensor
y=tf.matmul(W,... another variable or tensor ...)

#the overloaded operators are available too.
z=tf.sigmoid(W+b)

#assign a new value to the variable with 'assign()' or a related method.
W.assign(W+1.0)
W.assign_add(1.0)


当构造一个机器学习模型时,区分保存训练模型参数的变量和其他变量例如一个 用于计算训练步数的global step 变量是非常方便的。为使实现这个容易,变量构造器支持trainable=<bool> 参数。如果Ture ,新变量添加到图集合GraphKeys.TRAINABLE_VARIABLES。一个遍历的函数 trainable_variables() 返回这个集合中的内容。各种优化器类使用这个集合作为默认的变量列表去优化。

tf.Variable.__init__(initial_value=None, trainable=True, collections=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None)

使用初始值创建一个新的变量

新变量添加到collections 列出的图集合中,默认添加到 [GraphKeys.VARIABLES]

如果 trainable 是True,变量也添加到图集合 GraphKeys.TRAINABLE_VARIABLES.

这个构造器创建了两个操作节点,一个变量操作和一个赋值操作,用于将初始值赋给变量。

initial_value:  一个Tensor,或者可以转化为Tensor的Python对象,这是变量的初始值。初始值必须指定shape除非validate_shape 被设置为False。
trainable:  如果是True,变量也默认添加到GraphKeys.TRAINABLE_VARIABLES。这是很多优化器类使用的默认变量列表。
由另一个变量初始化
你有时候会需要用另一个变量的初始化值给当前变量初始化。由于tf.initialize_all_variables() 是并行地初始化所有变量,所以在有这种需求的情况下需要小心。
用其他变量的值初始化一个新的变量时,使用其他变量的 initialized_value() 属性。你可以直接把已初始化的值作为新变量的初始值,或者把它当做tensor 计算得到一个值赋予新变量。
#!/usr/bin/env python
# coding=utf-8

import tensorflow as tf

#create  a variable with a random value.
weights=tf.Variable(tf.random_normal([5,3],stddev=0.35),name="weights")
#Create another variable with the same value as 'weights'.
w2=tf.Variable(weights.initialized_value(),name="w2")
#Create another variable with twice the value of 'weights'
w_twice=tf.Variable(weights.initialized_value()*0.2, name="w_twice")

init=tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
weights_val,w2_val,w_twice_val=sess.run([weights,w2,w_twice])
print weights_val
print w2_val
print w_twice_val


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: