炼数成金Tensorflow学习笔记之2.2_变量
代码及分析
import tensorflow as tf
x = tf.Variable([1, 2])
a = tf.constant([3, 3])
sub = tf.subtract(x, a)
add = tf.add(x, sub)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print(sess.run(sub))
print(sess.run(add))
state = tf.Variable(0, name="counter")
new_value = tf.add(state, 1)
update = tf.assign(state, new_value)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(state))
for _ in range(5):
print(sess.run(update))
print(sess.run(state))
'''
这一块的输出结果:
0
1
1
2
2
3
3
4
4
5
5
'''
- 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
)
作用:生成一个变量,维护图在执行过程中的状态信息
initial_value=None:Variable 类的初始值,这个变量必须指定 shape 信息,否则后面 validate_shape 需设为 False
trainable=True:是否把变量添加到 collection GraphKeys.TRAINABLE_VARIABLES 中(collection 是一种全局存储,不受变量名生存空间影响,一处保存,到处可取)
collections=None:全局存储,默认是 GraphKeys.GLOBAL_VARIABLES
validate_shape=True:是否允许被未知维度的 initial_value 初始化
caching_device=None:指明哪个 device 用来缓存变量
name=None:变量名
variable_def=None:
dtype=None:如果被设置,初始化的值就会按照这个类型初始化
expected_shape=None:要是设置了,那么初始的值会是这种维度
import_scope=None:
另一篇博客中有介绍 - tf.subtract(x, y, name=None)
作用:返回 x-y 的元素.
注意:Subtract 支持广播. - tf.add(x,y,name=None)
作用:返回 x+y 的元素.
注意:Subtract 支持广播. - tf.global_variables_initializer()
作用:添加节点用于初始化全局变量(GraphKeys.GLOBAL_VARIABLES)。返回一个初始化所有全局变量的操作(Op)。
与之相对应的有一个tf.local_variables_initializer():返回一个初始化所有局部变量的操作(Op)。初始化局部变量(GraphKeys.LOCAL_VARIABLE)。 - tf.assign(ref, value, validate_shape=None, use_locking=None, name=None)
作用:函数完成了将value赋值给ref的作用。