我认为您可以使用tf.gather_nd 来效仿。您只需将“您的”索引转换为适合tf.gather_nd 的表示。以下示例与您的具体示例相关联,即形状为(2, 2, 2) 的输入张量,但我认为这让您了解如何编写任意形状的输入张量的转换,尽管我不确定它有多容易实现这一点(没有考虑太久)。另外,我并不是说这是最简单的解决方案。
import tensorflow as tf
import numpy as np
values = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])
values_tf = tf.constant(values)
indices = np.array([[1, 0], [0, 0]])
converted_idx = []
for k in range(values.shape[0]):
outer = []
for l in range(values.shape[1]):
inds = [k, l, indices[k][l]]
outer.append(inds)
print(inds)
converted_idx.append(outer)
with tf.Session() as sess:
result = tf.gather_nd(values_tf, converted_idx)
print(sess.run(result))
打印出来
[[1 2]
[4 6]]
编辑:在这里处理任意形状是一个递归解决方案,应该可以工作(仅在您的示例中测试):
def convert_idx(last_dim_vals, ori_indices, access_to_ori, depth):
if depth == len(last_dim_vals.shape) - 1:
inds = access_to_ori + [ori_indices[tuple(access_to_ori)]]
return inds
outer = []
for k in range(ori_indices.shape[depth]):
inds = convert_idx(last_dim_vals, ori_indices, access_to_ori + [k], depth + 1)
outer.append(inds)
return outer
您可以将它与我发布的原始代码一起使用,如下所示:
...
converted_idx = convert_idx(values, indices, [], 0)
with tf.Session() as sess:
result = tf.gather_nd(values_tf, converted_idx)
print(sess.run(result))