tensorflow--tf.Various()

来源:互联网 发布:中国社会调查数据 编辑:程序博客网 时间:2024/06/15 18:59

class tf.Variable

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

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

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

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

[python] view plain copy
  1. #!/usr/bin/env python  
  2. # coding=utf-8  
  3.   
  4. import tensorflow as tf  
  5. #create a variable  
  6. W=tf.Variable(<initial-value>,name=<optional-name>)  
  7.   
  8. #use the variable in the graph like any Tensor   
  9. y=tf.matmul(W,... another variable or tensor ...)  
  10.   
  11. #the overloaded operators are available too.  
  12. z=tf.sigmoid(W+b)  
  13.   
  14. #assign a new value to the variable with 'assign()' or a related method.  
  15. W.assign(W+1.0)  
  16. 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 计算得到一个值赋予新变量。
[python] view plain copy
  1. #!/usr/bin/env python  
  2. # coding=utf-8  
  3.   
  4. import tensorflow as tf  
  5.   
  6. #create  a variable with a random value.  
  7. weights=tf.Variable(tf.random_normal([5,3],stddev=0.35),name="weights")  
  8. #Create another variable with the same value as 'weights'.  
  9. w2=tf.Variable(weights.initialized_value(),name="w2")  
  10. #Create another variable with twice the value of 'weights'  
  11. w_twice=tf.Variable(weights.initialized_value()*0.2, name="w_twice")  
  12.   
  13. init=tf.initialize_all_variables()  
  14. with tf.Session() as sess:  
  15.     sess.run(init)  
  16.     weights_val,w2_val,w_twice_val=sess.run([weights,w2,w_twice])  
  17.     print weights_val  
  18.     print w2_val  
  19.     print w_twice_val  



原创粉丝点击