是否有任何解决方法可以沿可变长度的维度拆开张量?
Is there any workaround to unstack a tensor along a dimension with variable length?
我需要遍历长度可变的第一个维度,我该怎么做?如果不可能,有什么解决方法吗?
tf.unstack
沿动态维度不支持:
If value.shape[axis]
is not known, ValueError is raised.
但您可以尝试使用 tf.while_loop
迭代张量切片。下面是计算总和的示例:
# 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.]
我需要遍历长度可变的第一个维度,我该怎么做?如果不可能,有什么解决方法吗?
tf.unstack
沿动态维度不支持:
If
value.shape[axis]
is not known, ValueError is raised.
但您可以尝试使用 tf.while_loop
迭代张量切片。下面是计算总和的示例:
# 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.]