python - 如何获取变量的当前值?

标签 python tensorflow

假设我们有一个变量:

x = tf.Variable(...)

可以在训练过程中使用 assign() 方法更新此变量。

获取变量当前值的最佳方法是什么?

我知道我们可以使用这个:

session.run(x)

但我担心这会引发一整套操作。

在 Theano 中,你可以这样做

y = theano.shared(...)
y_vals = y.get_value()

我正在 TensorFlow 中寻找等价的东西。

最佳答案

获取变量值的唯一方法是在 session 中运行它。在 FAQ it is written那:

A Tensor object is a symbolic handle to the result of an operation, but does not actually hold the values of the operation's output.

所以 TF 等效项是:

import tensorflow as tf

x = tf.Variable([1.0, 2.0])

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    v = sess.run(x)
    print(v)  # will show you your variable.

带有 init = global_variables_initializer() 的部分很重要,应该这样做以初始化变量。

另外,看看 InteractiveSession如果你在 IPython 中工作。

关于python - 如何获取变量的当前值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33679382/

相关文章:

python - 如何将 Tensorflow Simple Audio Recognition frozen graph(.pb) 转换为 Core ML 模型?

python - 组合包含相似子字符串的列表元素

python - 如何在 Python 中将 IPv6 链路本地地址转换为 MAC 地址

python - 卷积网络的输入 channel 数

tensorflow - 为什么这个 Conv2d_Transpose/deconv2d 不返回 tensorflow 中的原始输入?

python - 如何在 tensorflow 中查找类型或打印变量详细信息\内容

python - 在值重复的情况下在字典中查找最大键的最大值的键

python - 反转字母表

javascript - Google Cloud 上的 Ajax 到 Python

python - TensorFlow 2.0 : do you need a @tf. 每个函数之上的函数装饰器?