如何为 TensorFlow 变量赋值? [英] How to assign a value to a TensorFlow variable?

查看:35
本文介绍了如何为 TensorFlow 变量赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 python 中的 tensorflow 变量分配一个新值.

 将 tensorflow 导入为 tf将 numpy 导入为 npx = tf.Variable(0)init = tf.initialize_all_variables()sess = tf.InteractiveSession()sess.run(初始化)打印(x.eval())x.assign(1)打印(x.eval())

但我得到的输出是

<预><代码>00

所以值没有改变.我错过了什么?

解决方案

在 TF1 中,声明 x.assign(1) 实际上并没有将值 1 分配给 x,而是创建一个 tf.Operation 您必须显式运行以更新变量.* 调用 Operation.run()Session.run() 可以用来运行操作:

assign_op = x.assign(1)sess.run(assign_op) # 或 `assign_op.op.run()`打印(x.eval())# ==>1

(* 实际上,它返回一个tf.Tensor,对应于变量的更新值,以便于链式赋值.)

然而,在 TF2 x.assign(1) 现在会急切地分配值:

x.assign(1)打印(x.numpy())# ==>1

I am trying to assign a new value to a tensorflow variable in python.

import tensorflow as tf
import numpy as np

x = tf.Variable(0)
init = tf.initialize_all_variables()
sess = tf.InteractiveSession()
sess.run(init)

print(x.eval())

x.assign(1)
print(x.eval())

But the output I get is

0
0

So the value has not changed. What am I missing?

解决方案

In TF1, the statement x.assign(1) does not actually assign the value 1 to x, but rather creates a tf.Operation that you have to explicitly run to update the variable.* A call to Operation.run() or Session.run() can be used to run the operation:

assign_op = x.assign(1)
sess.run(assign_op)  # or `assign_op.op.run()`
print(x.eval())
# ==> 1

(* In fact, it returns a tf.Tensor, corresponding to the updated value of the variable, to make it easier to chain assignments.)

However, in TF2 x.assign(1) will now assign the value eagerly:

x.assign(1)
print(x.numpy())
# ==> 1

这篇关于如何为 TensorFlow 变量赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆