python - 从 numpy 数组加载变量。张量流 2.0
问题描述
创建图表后,我想根据给定的 Numpy 数组更改一些变量的值。我不想发送变量的值,feed_dict
因为这些值不会经常变化。我也不想添加图表的另一个操作。有没有办法做到这一点?
解决方案
你可以使用tf.Variable.load()
. 它不会向图中添加操作:
将新值加载到此变量中。
将新值写入变量的内存。不向图表添加操作。
如果您没有急于执行(通过tf.compat.v1.disable_eager_execution()
):
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
import numpy as np
var = tf.Variable(tf.ones([2, 2])) # <-- existing variable
with tf.compat.v1.Session() as sess:
sess.run(var.initializer)
print('Current value:')
print(var.eval())
var.load(np.random.normal(size=(2, 2))) # <-- load new value
print('New value:')
print(var.eval())
# Current value:
# [[1. 1.]
# [1. 1.]]
# New value:
# [[ 0.03251546 1.2442433 ]
# [-1.4733697 -0.07199704]]
警告注意事项:
不推荐使用 Variable.load(来自 tensorflow.python.ops.variables),并将在未来的版本中删除。更新说明:首选在 2.X 中具有等效行为的 Variable.assign。
如果您处于图形模式,则变量的行为与TF1.x
. 因此,使用 assign 确实会为图形添加新的操作。例如,在 中运行以下代码jupyter
:
%load_ext tensorboard.notebook
import tensorflow as tf
import numpy as np
tf.compat.v1.disable_eager_execution()
from tensorflow.python.ops.array_ops import placeholder
from tensorflow.python.summary.writer.writer import FileWriter
with tf.name_scope('inputs'):
x = placeholder(tf.float32, shape=[None, 2], name='x')
with tf.name_scope('logits'):
layer = tf.keras.layers.Dense(units=2)
logits = layer(x)
with tf.name_scope('assign'):
assign_op = layer.weights[0].assign(np.random.normal(size=(2, 2)))
FileWriter('logs/train', graph=x.graph).close()
%tensorboard --logdir logs/train
如您所见,它的行为与 in 完全相同TF1.x
(创建为变量赋值的操作)。TF2.0
警告适用于您以时尚(不带)编写代码的情况tf.compat.v1.disable_eager_execution()
。
推荐阅读
- download - 文件在 Chrome 中下载,但不在 Safari 中,但 console.log(response) 和 Network 选项卡显示从服务器发送的文件
- javascript - 如何停止绑定每个处理程序并声明变量“那个”
- multithreading - 防止同时运行功能
- c++ - 使用模板时出现 C++ 分段错误 11
- android - 找不到将数据库数据加载到其中的变量
- ruby - 使用带有参数的 proc 速记
- vba - 删除空白单元格 - 146,459 行
- java - Java中有保留的包名吗?
- python - python中的列表操作,列表中有3个列表
- html - 如何将背景应用于围绕我的内容而不是 HTML 的容器?