【问题标题】:Load variables from numpy arrays. Tensorflow 2.0从 numpy 数组加载变量。张量流 2.0
【发布时间】:2019-05-06 10:24:33
【问题描述】:

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

【问题讨论】:

    标签: python tensorflow tensorflow2.0


    【解决方案1】:

    您可以使用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
    

    如您所见,它的行为与TF1.x 完全相同(创建为变量赋值的操作)。警告适用于您以TF2.0 方式编写代码(没有tf.compat.v1.disable_eager_execution())的情况。

    【讨论】:

    • 我曾经在 Tensorflow Variable.load (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version. Instructions for updating: Prefer Variable.assign which has equivalent behavior in 2.X.
    • 你说的是graph,我假设你在TF2.0使用了graph模式。我会更新我的问题
    • 我说的是图形模式
    • 您是在tf.compat.v1.disable_eager_execution() 中做的,还是要更新@tf.function 中的变量?
    • 我已经更新了我的答案。如果您使用图形模式,则警告无关紧要。不要忘记它是alpha 版本,并且在文档等中仍然有很多bugs/不准确之处。
    猜你喜欢
    • 2017-11-05
    • 2020-03-20
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2019-02-24
    • 2018-09-11
    相关资源
    最近更新 更多