1

我有一个数组output和一个 id subject_ids

output = [[[1, 2, 3]], [[4, 5, 6]], [[7, 8, 9]]]

subject_ids = [[0, 1], [1, 2], [0, 2]]

ID中的数字分别代表开始和结束位置,然后我想根据开始和结束位置得到它们之间的向量。

例如,在这种情况下,我应该得到and [[1, 2, 3], [4, 5, 6]][[4, 5, 6], [7, 8, 9]][[1, 2, 3], [4, 5, 6], [7, 8, 9]]

我应该怎么办?我试过tf.sliceand tf.gather,但似乎没有用。

4

2 回答 2

1

如果您只想使用 Tensorflow,请尝试与and结合tf.gather使用:tf.rangetf.ragged.stack

import tensorflow as tf

output = tf.constant([
                      [[1, 2, 3]], 
                      [[4, 5, 6]], 
                      [[7, 8, 9]]
                      ])

subject_ids = tf.constant([[0, 1], [1, 2], [0, 2]])

ragged_ouput = tf.ragged.stack([tf.gather(output, tf.range(subject_ids[i, 0], subject_ids[i, 1] + 1)) for i in tf.range(0, tf.shape(subject_ids)[0])], axis=0)
ragged_ouput = tf.squeeze(ragged_ouput, axis=2)
print(ragged_ouput)
[[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]]

更新1:

import tensorflow as tf
tf.config.run_functions_eagerly(True)

output = tf.constant([
                      [[1, 2, 3]], 
                      [[4, 5, 6]], 
                      [[7, 8, 9]]
                      ])

subject_ids = tf.constant([[0, 1], [1, 2], [0, 2]])

def slice_tensor(x):
  return tf.ragged.stack([tf.gather(output, tf.range(x[0], x[1] + 1))], axis=0)

ragged_ouput = tf.map_fn(slice_tensor, subject_ids, fn_output_signature=tf.RaggedTensorSpec(shape=[1, None, None, 3],
                                                                    dtype=tf.int32,
                                                                    ragged_rank=2,
                                                                    row_splits_dtype=tf.int64))
ragged_ouput = tf.squeeze(ragged_ouput, axis=1)
tf.print(ragged_ouput, summarize=-1)
[[[[1, 2, 3]], [[4, 5, 6]]], [[[4, 5, 6]], [[7, 8, 9]]], [[[1, 2, 3]], [[4, 5, 6]], [[7, 8, 9]]]]
于 2022-01-02T19:00:39.487 回答
0

How about just

>>> [output[np.arange(x, y+1)] for x, y in subject_ids] 
[array([[[1, 2, 3]],
        [[4, 5, 6]]]),
        
 array([[[4, 5, 6]],
        [[7, 8, 9]]]),
        
 array([[[1, 2, 3]],
        [[4, 5, 6]],
        [[7, 8, 9]]])]
于 2022-01-02T15:32:44.343 回答