在Tensorflow中,定义了某字符串变量,它才是变量,这一点与Python不同。定义语法:
sate = tf.Variable()例子:写一个累加器。
import tensorflow as tf
state = tf.Variable(3, name="counter")
# print(state.name)
# 定义常量one
one = tf.constant(1)
# 定义加法步骤(注:此步骤并没有直接计算)
new_value = tf.add(state , one)
# 将State更新为new_value
update = tf.assign(state,new_value)
# 如果在Tensorflow中定义了变量,那么初始化变量是最重要的,所以定义变量以后一定要定义init = tf.initialize_all_variables()
init = tf.initialize_all_variables() # must have if define variable
with tf.Session() as sess:
# 变量还没有激活,需要在sess里激活init
sess.run(init)
for _ in range(3):
sess.run(update)
print(sess.run(state))注:如果没有运行成功,请检查编译器能否编译中文字符。若果不能,请把文章注释的中文字符删除。
视频笔记:https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/2-4-variable/

本文介绍如何在TensorFlow中定义和使用变量,并通过一个简单的累加器示例展示了变量的操作流程,包括变量初始化、定义操作符以及Session的使用。
195

被折叠的 条评论
为什么被折叠?



