索引while_loop TensorFlow函数中的列表

时间:2018-05-24 13:28:05

标签: list tensorflow indexing while-loop

您好。

我有一个问题。我实际上有一个占位符列表(真正的python列表)。 我的列表长度为 n(=以下代码中的T),如下所示:

my_list = [[D0, K], [D1, K], ... [Dn, K]]

其中Di不需要相同的尺寸。这就是我使用列表的原因(因为我无法将此列表转换为张量而没有填充)

我想做的是:

temp = []
for step in range(T):
    temp.append(tf.reduce_sum(x[step], axis=0))

sum_vn_t = tf.stack(temp)

前面定义的长度 n x = my_list 。 这段代码只会转换我的输入列表 x ,如下所示:

[[D0, K], [D1, K], ... [Dn, K]]

[n, K]

我实际上对每个Di行求和,使得我的新张量大小[n,K]的每个第j行包含: sum([Dj,K],axis = 0 )

问题在于,如果我使用python 进行循环,我不确定反向传播是否真的有效(我对TensorFlow很新,但我认为如果我不喜欢#39;使用 while_loop 功能,我的操作不会被添加到Graph中,所以做一个原生的python for循环没有意义吗?)。

所以我只是尝试使用tensorflow while_loop重新编码这段代码。 代码如下:

def reduce_it(i, outputs):
    i_row = tf.reduce_sum(x[i], axis=0) # x[i] throw an error as i is a Tensor
    outputs = outputs.write(i, i_row)

    return i+1, outputs

temp = tf.TensorArray(dtype=tf.float32, infer_shape=False, size=1,
                  dynamic_size=True)
_, temp = tf.while_loop(lambda i, *args: tf.less(i, T),
                     reduce_it, [0, temp])
temp = temp.stack()

我已经看到有人问这个,但是没有人能够给他一个解决方法。我尝试通过传递一个numpy数组将Tensor i 转换为整数,我在while循环中添加元素以获得此数组的形状:

def reduce_it(arr, outputs):
    idx = arr.shape[0] - 1 # use shape[0] of array as i
    i_row = tf.reduce_sum(x[idx], axis=0)
    outputs = outputs.write(tf.constant([idx]), i_row)
    arr = np.append(arr, 0)
    return arr, outputs

temp = tf.TensorArray(dtype=tf.float32, infer_shape=False, size=1,
                  dynamic_size=True)
_, temp = tf.while_loop(lambda arr, *args: tf.less(arr.shape[0], T),
                     reduce_it, [np.array([0]), temp])
temp = temp.stack()

但它不起作用,因为我的数组 arr 的形状在循环期间发生了变化,因此我可能需要使用while_loop的shape_invariants选项,但我没有设法让工作代码......

此外,我已经通过添加填充来将我的列表转换为Tensor,使得我的张量大小为: [T,max(Di),K] 但我仍然需要知道哪个维度我在我的循环的每次迭代中工作,这意味着我需要创建一个大小为n的张量(1d阵列),在位置i上具有Di作为数字:

my_tensor = [D1, D2, ..., Dn]

然后我需要在我的while循环中收集Di,但如果我只是这样做:

my_dim = tf.gather(my_tensor, i)

我只会收集一个张量,我需要一个整数。

我认为我无法定义会话并恢复my_dim.eval(),因为此代码是我的模块的一部分,然后在训练期间调用(此时我会创建一个会话)。

TF的一些专家可以想到解决方法或黑客攻击吗?

提前谢谢

注意:填充也是一个解决方案,但实际上我的代码后面我需要得到每个初始矩阵的大小[Di,K],所以如果我填充我的[Di,K] ]这样我就可以构建一个Tensor形状:

[n, max(Dn), K]

然后,我仍然需要恢复每个[Di,K]以便能够使用正确尺寸的tf.matmul()(例如操作)。所以填充实际上不适合我。

我希望我的帖子足够清楚。

1 个答案:

答案 0 :(得分:2)

在下面找到一个潜在的解决方案,但我不推荐使用T的大值(此方法会创建与my_list中的元素一样多的操作。)

你用零填充张量的想法似乎是一个好的。如果我正确理解了您的最终目标,那么这些额外的零不应该影响您的tf.reduce_sum(x[idx], axis=0)(但仍然可能不建议大型T使用此解决方案,原因与之前相同)。< / p>

最后,您还可以尝试将代码转换为使用tf.SparseTensortf.sparse_reduce_sum()

tf.case()tf.while_loop()

的解决方案
import tensorflow as tf
import numpy as np

T = 10
my_list = [tf.ones((np.random.randint(2, 42))) for i in range(T)] # list of random size tensors

def reduce_it(i, outputs):
    get_lambda_for_list_element = lambda idx: lambda: my_list[idx]
    cases = {tf.equal(i, idx): get_lambda_for_list_element(idx) for idx in range(len(my_list))}
    x = tf.case(cases, exclusive=True)

    # It's not clear to me what my_list contains / what your loop is suppose to compute.
    # Here's a toy example supposing the loop computes:
    #       outputs[i] = tf.reduce_sum(my_list[i]) for i in range(T)
    i_row = tf.reduce_sum(x)
    indices = tf.range(0, T)
    outputs = tf.where(tf.equal(indices, i), tf.tile(tf.expand_dims(i_row, 0), [T]), outputs)

    return i+1, outputs

temp = tf.zeros((T))
_, temp = tf.while_loop(lambda i, *args: tf.less(i, T), reduce_it, [0, temp])

with tf.Session() as sess:
    res = sess.run(temp)
    print(res)
    # [37.  2. 22. 16. 37. 40. 10.  3. 12. 26.]

    # Checking if values are correct:
    print([sess.run(tf.reduce_sum(tensor)) for tensor in my_list])
    # [37.0, 2.0, 22.0, 16.0, 37.0, 40.0, 10.0, 3.0, 12.0, 26.0]

tf.pad()

的解决方案
import tensorflow as tf
import numpy as np

T = 10
my_list = [tf.ones((np.random.randint(2, 42))) for i in range(T)]  # list of random size tensors

dims = [t.get_shape().as_list()[0] for t in my_list]
max_dims = max(dims)

my_padded_list = [tf.squeeze(
    # Padding with zeros:
    tf.pad(tf.expand_dims(t, 0),
           tf.constant([[0, 0], [int(np.floor((max_dims - t.get_shape().as_list()[0]) / 2)),
                                 int(np.ceil((max_dims - t.get_shape().as_list()[0]) / 2))]],
                       dtype=tf.int32),
           "CONSTANT"))
    for t in my_list]

my_padded_list = tf.stack(my_padded_list)
outputs_with_padding = tf.reduce_sum(my_padded_list, axis=1)

with tf.Session() as sess:
    # [13. 11. 24.  9. 16.  8. 24. 34. 35. 32.]
    res = sess.run(outputs_with_padding)
    print(res)

    # Checking if values are correct:
    print([sess.run(tf.reduce_sum(tensor)) for tensor in my_list])
    # [13.0, 11.0, 24.0, 9.0, 16.0, 8.0, 24.0, 34.0, 35.0, 32.0]

tf.SparseTensor

的解决方案
import tensorflow as tf
import numpy as np

T = 4
K = 2
max_length = 42
my_list = [np.random.rand(np.random.randint(1, max_length + 1), K) for i in range(T)]  # list of random size tensors

x = tf.sparse_placeholder(tf.float32)
res = tf.sparse_reduce_sum(x, axis=1)

with tf.Session() as sess:
    # Preparing inputs for sparse placeholder:
    indices = np.array([ [t, i, k] for t in range(T) 
                         for i in range(my_list[t].shape[0]) 
                         for k in range(my_list[t].shape[1]) ], dtype=np.int64)
    values = np.concatenate([t.reshape((-1)) for t in my_list])
    dense_shape = np.array([T, max_length, K], dtype=np.int64)
    sparse_feed_dict = {x: tf.SparseTensorValue(indices, values, dense_shape)}
    # or implictely, sparse_feed_dict = {x: (indices, values, dense_shape)}
    print(sess.run(res, feed_dict=sparse_feed_dict))
    # [[2.160928   3.38365   ]
    #  [13.332438  14.3232155]
    #  [6.563875   6.540451  ]
    #  [3.3114233  2.138658  ]]

    # Checking if values are correct:
    print([sess.run(tf.reduce_sum(tensor, axis=0)) for tensor in my_list])
    # [array([2.16092795, 3.38364983  ]), 
    #  array([13.33243797, 14.32321563]), 
    #  array([6.56387488, 6.54045109  ]), 
    #  array([3.31142322, 2.13865792  ])]