gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:34:02 25 4
gpt4 key购买 nike

我需要循环长度可变的第一个维度,我该如何做到这一点?如果不可能有什么解决方法吗?

最佳答案

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.]

关于tensorflow - 是否有任何解决方法可以沿着可变长度的维度取消堆叠张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48208489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com