您的位置:首页 > 其它

TensorFlow基础知识点(三)变量/Variables

2017-03-14 14:17 232 查看
在TensorFlow中变量维持了图执行过程中的状态信息

接下来我们用TensorFlow的实例代码来说明。

# Create a Variable, that will be initialized to the scalar value 0.
# 建 立 一 个 变 量, 用0初 始 化 它 的 值
state = tf.Variable(0, name="counter")

# Create an Op to add one to `state`.

one = tf.constant(1)

new_value = tf.add(state, one)
update = tf.assign(state, new_value)

# Variables must be initialized by running an `init` Op after having
# launched the graph. We first have to add the     #`init` Op to the
#graph.
init_op = tf.initialize_all_variables()

# Launch the graph and run the ops.
with tf.Session() as sess:
# Run the 'init' op
sess.run(init_op)
# Print the initial value of 'state'
print(sess.run(state))
# Run the op that updates 'state' and print 'state'.
for _ in range(3):
sess.run(update)
print(sess.run(state))

# output:

# 0
# 1
# 2
# 3


代码中
assign()
操作时将图所描绘的表达式的一部分,正如
add()
操作一样,所以在操作
run()
执行表达式之前,它并不会真正执行赋值操作

注意:通常会将一个统计模型中的参数表示为一组变量 . 例如 , 你可以将一个神经网络的权重作为某个变量存储在一个 tensor 中 . 在训练过程中 , 通过重复运行训练图 , 更新这个

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