是否有任何解决方法可以沿着具有可变长度的维度取消叠加张量?

时间:2018-01-11 13:43:07

标签: tensorflow machine-learning deep-learning reshape tensor

我需要遍历长度可变的第一维,我该如何设法做到这一点?如果不可能有任何解决方法?

1 个答案:

答案 0 :(得分:3)

动态维度

demo 不支持

  

如果value.shape[axis]未知,则引发ValueError。

但您可以尝试使用tf.unstack迭代张量切片。这是一个计算总和的例子:

# Input tensor: trying to iterate along axis=0
x = tf.placeholder(dtype=tf.float32, shape=[None, 3])
batch_size = tf.shape(x)[0]

def cond(x, i, _):
  return i < batch_size

def body(x, i, x_prev):
  # Do some operation with `x_prev` and `x[i]`. Here we just add the slices
  sum = x_prev + x[i]
  return x, i + 1, sum

# This means: starting from 0, apply the body, while the `cond` is true
_, _, c = tf.while_loop(cond, body, (x, 0, tf.zeros([3])))

# Test it
with tf.Session() as sess:
  data = np.arange(12).reshape([4, 3])
  print(data)

  result = sess.run(c, feed_dict={x: data})
  print(result)

输出:

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]

[ 18.  22.  26.]