首页 > 解决方案 > 从 numpy 数组加载变量。张量流 2.0

问题描述

创建图表后,我想根据给定的 Numpy 数组更改一些变量的值。我不想发送变量的值,feed_dict因为这些值不会经常变化。我也不想添加图表的另一个操作。有没有办法做到这一点?

标签: pythontensorflowtensorflow2.0

解决方案


你可以使用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()


推荐阅读