首页 > 解决方案 > 使用gather_nd在循环中获取结果-所有输入的形状必须匹配

问题描述

我在 numpy 中有这个例子:

import numpy as np
import tensorflow as tf

a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9],
              [10, 11 , 12],
              [13, 14, 15]])

res = np.zeros((5, 2), dtype=object)

for idx in range(0, len(a)-2, 2):
    a0 = a[idx]
    a1 = a[idx + 1]
    a2 = a[idx + 2]
    c = a0 + a1 + a2

    res[idx:idx + 2] = ([idx, c])

res

array([[0, array([12, 15, 18])],
       [0, array([12, 15, 18])],
       [2, array([30, 33, 36])],
       [2, array([30, 33, 36])],
       [0, 0]], dtype=object)

我想在张量流中做到这一点:

a_tf = tf.convert_to_tensor(a)
res_tf = tf.zeros((5, 2), dtype=object)

for idx in range(0, a.shape[0]-2, 2):
    a0 = tf.gather_nd(a, [idx])
    a1 = tf.gather_nd(a, [idx + 1])
    a2 = tf.gather_nd(a, [idx + 2])
    c = a0 + a1 + a2

    res = tf.gather_nd([idx, c], [idx:idx +2])

直到与计算一致为止c

在最后一行 ( res) 它给了我:

res = tf.gather_nd([idx, c], [idx:idx +2])
                                     ^
SyntaxError: invalid syntax

我不确定如何收到结果。

更新

基本上,问题在于它[idx, c]的类型是 list 并试图做 : tf.convert_to_tensor([idx, c],给出:

InvalidArgumentError: Shapes of all inputs must match: values[0].shape = [] != values[1].shape = [3] [Op:Pack] name: packed/

标签: python-3.xtensorflowtensorflow2.0

解决方案


res = tf.gather_nd([idx, c], [idx:idx +2])

语法不正确。如果你想提取索引,它应该是

res = tf.gather_nd([idx, c], range(idx, idx +2))

后者也可能会引发错误。中的索引range(idx, idx +2)高于列表的索引[idx, c]

res此外,除非使用,否则无法创建形状为 的张量ragged tensors。这是您尝试执行的操作的可能解决方法

a_tf = tf.convert_to_tensor(a)
res_tf = tf.zeros((5, 2), dtype=object)
l = []
for idx in range(0, a.shape[0]-2, 2):
    a0 = tf.gather_nd(a, [idx])
    a1 = tf.gather_nd(a, [idx + 1])
    a2 = tf.gather_nd(a, [idx + 2])
    c = a0 + a1 + a2
    helper = [idx]
    helper.extend(c.numpy().tolist())
    l.append(helper)

print(tf.constant(l))

推荐阅读