【问题标题】:How to keep calculated values in a Tensorflow graph (on the GPU)?如何将计算值保存在 Tensorflow 图中(在 GPU 上)?
【发布时间】:2015-12-14 13:55:17
【问题描述】:

我们如何确保计算的值不会被复制回 CPU/python 内存,但仍可用于下一步的计算?

下面的代码显然不行:

import tensorflow as tf

a = tf.Variable(tf.constant(1.),name="a")
b = tf.Variable(tf.constant(2.),name="b")
result = a + b
stored = result

with tf.Session() as s:
    val = s.run([result,stored],{a:1.,b:2.})
    print(val) # 3
    val=s.run([result],{a:4.,b:5.})
    print(val) # 9
    print(stored.eval()) # 3  NOPE:

错误:尝试使用未初始化的值 _recv_b_0

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    答案是通过使用the assign operation 将值存储到tf.Variable 中:

    工作代码:

    import tensorflow as tf
    with tf.Session() as s:
        a = tf.Variable(tf.constant(1.),name="a")
        b = tf.Variable(tf.constant(2.),name="b")
        result = a + b
        stored  = tf.Variable(tf.constant(0.),name="stored_sum")
        assign_op=stored.assign(result)
        val,_ = s.run([result,assign_op],{a:1.,b:2.})
        print(val) # 3
        val=s.run(result,{a:4.,b:5.})
        print(val[0]) # 9
        print(stored.eval()) # ok, still 3 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-22
      • 2017-04-25
      • 2020-03-02
      • 2016-02-24
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多