如何在张量流中创建对组合
how create pair combinations in tensorflow
我有多个dim张量,我想根据第i个dim创建对组合张量,然后创建两个张量,例如,
a=tf.constant([[[1,1],[2,2]],
[[3,3],[4,4]],
[[5,5],[6,6]],shape=(3,2,2)) ,
我根据 0 dim 创建对组合(索引是 [0,1,2]
,所以对是 (0,1),(0,2),(1,2)
,所以新张量 b 的 0 dim 来自旧索引 [0,0,1]
,新张量 d 的 0 dim 来自旧索引 [1,2,2]
,完成的结果是:
b=tf.constant([[[1,1],[2,2]],
[[1,1],[2,2]],
[[3,3],[4,4]]],shape=(3,2,2))
c=tf.constant([[[3,3],[4,4]],
[[3,3],[4,4]],
[[5,5],[6,6]]],shape=(3,2,2))
使用tf.gather()
:
import tensorflow as tf
a = tf.constant([[[1,1],[2,2]],
[[3,3],[4,4]],
[[5,5],[6,6]]])
pair = ((0,1),(0,2),(1,2))
pair = tf.convert_to_tensor(pair)
inds = pair[:,0]
b = tf.gather(a, inds)
inds = pair[:,1:]
c = tf.gather(a, inds)
我有多个dim张量,我想根据第i个dim创建对组合张量,然后创建两个张量,例如,
a=tf.constant([[[1,1],[2,2]],
[[3,3],[4,4]],
[[5,5],[6,6]],shape=(3,2,2)) ,
我根据 0 dim 创建对组合(索引是 [0,1,2]
,所以对是 (0,1),(0,2),(1,2)
,所以新张量 b 的 0 dim 来自旧索引 [0,0,1]
,新张量 d 的 0 dim 来自旧索引 [1,2,2]
,完成的结果是:
b=tf.constant([[[1,1],[2,2]],
[[1,1],[2,2]],
[[3,3],[4,4]]],shape=(3,2,2))
c=tf.constant([[[3,3],[4,4]],
[[3,3],[4,4]],
[[5,5],[6,6]]],shape=(3,2,2))
使用tf.gather()
:
import tensorflow as tf
a = tf.constant([[[1,1],[2,2]],
[[3,3],[4,4]],
[[5,5],[6,6]]])
pair = ((0,1),(0,2),(1,2))
pair = tf.convert_to_tensor(pair)
inds = pair[:,0]
b = tf.gather(a, inds)
inds = pair[:,1:]
c = tf.gather(a, inds)