【问题标题】:Extracting a sub-tensor in TensorFlow在 TensorFlow 中提取子张量
【发布时间】:2018-03-07 18:29:55
【问题描述】:

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

例如,tensorA:select(0,0) 将返回 [0,1,0,1]tensorA:select(1,1) 将返回 [1,0]

如何在 TensorFlow 中做到这一点? 我能找到的最简单的方法是:tf.gather(tensorA, indices=[i], axis=d)

但是为此使用 collect 似乎有点过头了。有谁知道更好的方法吗?

【问题讨论】:

标签: python matrix tensorflow tensor


【解决方案1】:

您可以使用以下配方:

用分号替换除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)

但是,当我尝试这个时,我遇到了 SyntaxError :

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

【讨论】:

  • 本能地,我首先尝试tensorA[*selection] 解包列表选择。然而解包不起作用(SyntaxError:无效语法)。谁能解释一下为什么?
【解决方案2】:

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

【讨论】:

  • 我认为这行不通。它不会返回第 d 行和第 i 列中的元素吗?如果是这样,这不是我要找的。​​span>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
  • 1970-01-01
相关资源
最近更新 更多