Variable 变量

本文详细介绍了在TensorFlow中如何定义、初始化和操作变量。通过一个计数器的例子,展示了变量声明、常量设定、加法操作及变量更新的过程。强调了在TensorFlow中变量初始化的重要性,并演示了如何在Session中运行变量更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

声明

来源于莫烦 Python:Variable 变量


代码

import tensorflow as tf

state = tf.Variable(0, name='counter')
#print(state.name)
one = tf.constant(1)

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

init = tf.initialize_all_variables()  # 初始化所有的变量

with tf.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

输出结果:1 2 3


在 Tensorflow 中,定义了某字符串是变量,它才是变量,这一点是与 Python 所不同的。

定义语法: state = tf.Variable()

import tensorflow as tf

state = tf.Variable(0, name='counter')

# 定义常量 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().

到这里变量还是没有被激活,需要再在sess里, sess.run(init), 激活 init这一步.

# 如果定义 Variable, 就一定要 initialize
# init = tf.initialize_all_variables() # tf 马上就要废弃这种写法
init = tf.global_variables_initializer()  # 替换成这样就好
 
# 使用 Session
with tf.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

一定要把 sess 的指针指向 state 再进行 print 才能得到想要的结果!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值