Tensorflow 复制二维张量y[i]中的行,其中i是另一个张量y中的索引?
我正在寻找一个tf操作,它将输入张量x中的元素复制y[I]次,其中I是第二个张量中的索引。更准确地说,操作应实现以下目标:Tensorflow 复制二维张量y[i]中的行,其中i是另一个张量y中的索引?,tensorflow,Tensorflow,我正在寻找一个tf操作,它将输入张量x中的元素复制y[I]次,其中I是第二个张量中的索引。更准确地说,操作应实现以下目标: x = tf.constant([[1, 4], [2, 5], [3, 6]]) y = tf.constant([3, 2, 4]) z = <operation>(x, y) # [[1, 4], [1, 4], [1, 4], [2, 5], [2, 5],
x = tf.constant([[1, 4], [2, 5], [3, 6]])
y = tf.constant([3, 2, 4])
z = <operation>(x, y) # [[1, 4], [1, 4], [1, 4],
[2, 5], [2, 5],
[3, 6], [3, 6], [3, 6], [3, 6]]
x=tf.常数([[1,4],[2,5],[3,6]]
y=tf.常数([3,2,4])
z=(x,y)#[[1,4],[1,4],[1,4],
[2, 5], [2, 5],
[3, 6], [3, 6], [3, 6], [3, 6]]
我可以使用什么操作?谢谢:)关键思想是根据
y
构建索引的一维张量,然后执行tf。收集:
def repeat(t, times):
num_elements = tf.shape(t)[0]
def cond_fn(i, _):
return i < num_elements
def body_fn(i, indices_ta):
repeated_i = tf.tile(i[tf.newaxis], times[i, tf.newaxis])
return (i + 1, indices_ta.write(i, repeated_i))
indices_ta = tf.TensorArray(times.dtype, num_elements, infer_shape=False)
_, indices_ta = tf.while_loop(
cond_fn,
body_fn,
loop_vars=(0, indices_ta))
return tf.gather(t, indices_ta.concat())
def重复(t次):
num_elements=tf.shape(t)[0]
def cond_fn(一)
返回i
太棒了!谢谢这是一个有效的解决方案。然而,我担心性能——while循环的性能不是很好吗?如果是这样,有没有没有没有while循环的解决方案?也就是说,没有while循环的索引[3,2,4]到[0 0 0 0 0 0 0 0 0 0 0 1 1 2 2]的一维张量的构造我不确定是否有一种方法可以在没有while循环的情况下做到这一点(除了从头开始滚动自定义TF op)。通过直接索引到t
(或者更好地索引到TensorArray
,使用t
切片)可以稍微改变实现,但是很难说这是否会更有效。