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

来源:互联网 发布:淘宝返利最高返多少 编辑:程序博客网 时间:2024/05/17 05:00

在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.

0 0
原创粉丝点击