在 TensorFlow 中提取子张量

Extracting a sub-tensor in TensorFlow

我有一个 2 x 4 tensorA = [[0,1,0,1],[1,0,1,0]]。 我想从维度 d 中提取索引 i。 在 Torch 中我可以做到:tensorA:select(d,i)

例如,tensorA:select(0,0) 将 return [0,1,0,1]tensorA:select(1,1) 会 return [1,0].

我如何在 TensorFlow 中执行此操作? 我能找到的最简单的方法是:tf.gather(tensorA, indices=[i], axis=d)

但是为此使用收集似乎有点矫枉过正。有谁知道更好的方法吗?

您可以简单地使用 value = tensorA[d,i]。在引擎盖下,tensorflow 调用 tf.strided_slice

您可以使用以下食谱:

用分号替换除d以外的所有轴,并将值i放在d轴上,例如:

tensorA[0, :]  # same as tensorA:select(0,0)
tensorA[:, 1]  # same as tensorA:select(1,1)
tensorA[:, 0]  # same as tensorA:select(1,0)

但是,当我尝试这样做时,我遇到了语法错误:

i = 1
selection = [:,i]  # this raises SyntaxError
tensorA[selection]

所以我改用了切片,如

i = 1
selection = [slice(0,2,1), i]
tensorA[selection]  # same as tensorA:select(1,i)

这个函数可以解决问题:

def select(t, axis, index):
    shape = K.int_shape(t)
    selection = [slice(shape[a]) if a != axis else index for a in 
                 range(len(shape))]
    return t[selection]

例如:

import numpy as np
t = K.constant(np.arange(60).reshape(2,5,6))
sub_tensor = select(t, 1, 1)
print(K.eval(sub_tensor)  

打印

[[6., 7., 8., 9., 10., 11.],

[36., 37., 38., 39., 40., 41.]]