一次将数据加载到占位符,然后运行多次计算

时间:2019-01-03 21:29:23

标签: python tensorflow

问题

如何一次将数据加载到占位符,然后对占位符中的数据运行多个计算?

用例

  • 我有100个形状相同的numpy数组(A 1 ,...,A 100 )。
  • 目标函数取决于输入数据和变量B的数组。
  • 例如,A 1 的损失函数可以是`loss_1 = np.sum(A_1)+ np.sum(B_1)。
  • 对于每个A n ,我想找到变量B n 的数组,以将相应的损失函数loss n 最小化。
  • 结果应为100个变量数组,它们是:B 1 ,...,B 100

我想加载A 1 ,找到B 1 ,然后对其余的A数组重复上述操作。

尝试1

使用tf.constant加载A数组将导致内存不足。在加载A 1 并找到B 1 之后。当我加载A 2 时,A 1 仍会保留在GPU的内存中。一段时间后,该程序将耗尽GPU的所有内存。

尝试2

使用占位符,并在最小化的每个步骤中加载相同的数据。这将很慢,因为将数据传输到GPU的速度很慢。

import tensorflow as tf

x = tf.placeholder("float", None)
y = x * 2

with tf.Session() as session:
    for j in range(100):  # Iterate over the 100 A arrays
        A_n = [1, 2, 3]  # The 100 different A arrays.
        for i in range(300):  # Steps of one minimization
            # Why do I have to feed the same data for 300 times??
            result = session.run(y, feed_dict={x: A_n})
            print(result)

1 个答案:

答案 0 :(得分:1)

这可以通过将function isUCI() { var globalContext = Xrm.Utility.getGlobalContext(); var t1 = globalContext.getCurrentAppUrl(); var t2 = globalContext.getClientUrl(); return t1 !== t2; } 转换为变量来实现。 TF 1.X中的变量通过通过x显式运行其初始化程序来初始化。因此,您只需要使用占位符初始化变量Session.run

x

请注意,这假设x_init = tf.placeholder(tf.float32, shape=(3, )) x = tf.Variable(x_init) y = x * 2 with tf.Session() as sess: for j in range(100): A_n = [j, j + 1, j + 2] # Reinitialize `x` with the new A_n. sess.run(x.initializer, feed_dict={x_init: A_n}) # `x` is initialized and therefore there is nothing to feed. for i in range(300): result = sess.run(y) print(result) 的形状相同。