通过构造一个Variable类的实例在图中添加一个变量(variable),
Variable()这个构造函数需要初始值,这个初始值可以是一个任何类型任何形状的Tensor,初始值的形状和类型决定了这个变量的形状和类型。构造之后,这个变量的形状和类型就固定了,他的值可以通过assign()函数(或者assign类似的函数)来改变。如果你想要在之后改变变量的形状,你就需要assign()函数同时设置变量的validate_shape=False 。
和任何的Tensor一样,通过Variable()创造的变量能够作为图中其他操作的输入使用。你也能够在图中添加节点,通过对变量进行算术操作。这里还是说的太抽象了,举个简单的例子来说明一下。
from __future__ import print_function,division
import numpy as np
import tensorflow as tf
#create a Variable
w=tf.Variable(initial_value=[[1,2],[3,4]],dtype=tf.float32)
x=tf.Variable(initial_value=[[1,1],[1,1]],dtype=tf.float32)
y=tf.matmul(w,x)
z=tf.sigmoid(y)
print(z)
init_op=tf.global_variables_initializer()
with tf.Session() as session:
session.run(init_op)
z=session.run(z)
print(z)
输出:
Tensor("Sigmoid:0", shape=(2, 2), dtype=float32)
[[ 0.95257413 0.95257413]
[ 0.999089 0.999089 ]]
属性:
device:这个变量的device
dtype:变量的元素类型
graph:存放变量的图
initial_value:这个变量的初始值
initializer :这个变量的初始化器
name:这个变脸的名字
**op:**The Operation of this variable.
函数:
_init_(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)
作用:
创建一个新的变量,初始值为initial_value(这个构造函数会创建两个操作(Op),一个变量OP和一个assignOp来设置变量为其初始化值)参数: initial_value:
一个Tensor类型或者是能够转化为Tensor的python对象类型。它是这个变量的初始值。这个初始值必须指定形状信息,不然后面的参数validate_shape需要设置为false。当然也能够传入一个无参数可调用并且返回制定初始值的对象,在这种情况下,dtype必须指定。
trainable:
如果为True(默认也为Ture),这个变量就会被添加到图的集合GraphKeys.TRAINABLE_VARIABLES.中去
,这个collection被作为优化器类的默认列表。 collections:图的collection
键列表,新的变量被添加到这些collection中去。默认是[GraphKeys.GLOBAL_VARIABLES].
validate_shape: 如果是False的话,就允许变量能够被一个形状未知的值初始化,默认是True,表示必须知道形状。
caching_device: 可选,描述设备的字符串,表示哪个设备用来为读取缓存。默认是变量的device, name:
可选,变量的名称 variable_def: VariableDef protocol buffer. If not None,
recreates the Variable object with its contents. variable_def and the
other arguments are mutually exclusive. dtype:
如果被设置,初始化的值就会按照这里的类型来定。 expected_shape:
TensorShape类型.要是设置了,那么初始的值会是这种形状 import_scope: Optional string. Name
scope to add to the Variable. Only used when initializing from
protocol buffer.
assign(value, use_locking=False)
作用:为变量指定一个新的值 参数: value: Tensor,变量的新值 use_locking: 如果是True,If True,
use locking during the assignment.
assign_add(delta, use_locking=False)
作用:为这个变量加上一个值 参数: delta: Tensor,待加的值 use_locking: If True, use
locking during the operation.
assign_sub(delta, use_locking=False)
作用:为这个变量减去一个值 参数: delta: Tensor,待减的值 use_locking: If True, use
locking during the operation.
eval(session=None)
作用:
在一个session里面,计算并且返回这个变量的值。这个不算是构造图的方法,它并不会添加一个操作到图里面。这个便捷方法需要一个包含这个变量的图投放到了一个session里面。要是没有sesssion,那么默认的就会使用默认的session。
参数: session: 估算这个变量的Session
v = tf.Variable([1, 2])
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# Usage passing the session explicitly.
print(v.eval(sess))
# Usage with the default session. The 'with' block
# above makes 'sess' the default session.
print(v.eval())
输出:
[1 2]
[1 2]
get_shape()
作用:返回变量的形状
initialized_value()
作用: 返回已经初始化变量的值.你应该使用这个函数来代替使用变量自己来初始化依赖这个变量的值的其他变量。
Initialize 'v' with a random tensor.
v = tf.Variable(tf.truncated_normal([10, 40]))
Use `initialized_value` to guarantee that `v` has been
initialized before its value is used to initialize `w`.
The random values are picked only once.
w = tf.Variable(v.initialized_value() * 2.0)
load(value, session=None)
作用:把新的值载入到变量里面 参数: value: 新的变量值 session:
用来估算这个变量的Session,要是没有传递,就用默认的v = tf.Variable([1, 2])
init = tf.global_variables_initializer()
from __future__ import print_function,division
import numpy as np
import tensorflow as tf
v=tf.Variable(initial_value=[1,2])
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
#显式地传递session到函数里面
v.load(value=[3,4],session=sess)
print(v.eval(session=sess))
输出:
[3 4]
read_value()
作用:返回这个变量的值,在当前的上下文中读取。返回的是一个含有这个值的Tensor
scatter_sub(sparse_delta, use_locking=False)
Subtracts IndexedSlices from this variable. This is essentially a
shortcut for scatter_sub(self, sparse_delta.indices,
sparse_delta.values). Args: sparse_delta: IndexedSlices to be
subtracted from this variable. use_locking: If True, use locking
during the operation. Returns: A Tensor that will hold the new value
of this variable after the scattered subtraction has completed.
Raises: ValueError: if sparse_delta is not an IndexedSlices.
set_shape(shape)
作用:改变变量形状 参数: shape:新的形状