我有一个简单的张量a = tf.constant([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]])
,并且想对其进行切片,但是我需要对每一行进行不同的处理。此切片操作由另一个张量b = tf.constant([[0, 1], [2, 4], [2, 5]])
描述,这意味着从张量a
的第一行开始,我需要从0
到1
的元素,而从{{ 1}}至2
,依此类推。所以最终的最终结果将是
4
我的第一个想法是填充切片的开始和结束之间的范围,但不幸的是,由于结果行的长度不同,因此无法使用[
[1],
[8, 9],
[13, 14, 15]
]
进行填充。
有人知道该怎么做吗?
答案 0 :(得分:1)
import tensorflow as tf
a = tf.constant([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]])
b = tf.constant([[0, 1], [2, 4], [2, 5]])
# As you iterate, provided a and b have same length
# [1, 2, 3, 4, 5] sliced as [0:1]
# [6, 7, 8, 9, 10] sliced as [2:4]
# [11, 12, 13, 14, 15] sliced as [2:5]
[data.numpy().tolist()[start:end] for data, (start, end) in zip(a,b)]
输出:
[[1], [8, 9], [13, 14, 15]]
答案 1 :(得分:0)
如果 b
的大小在图编译时已知,那么您可以单独对每一行进行切片。
import tensorflow as tf
a = tf.constant([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]])
b = tf.constant([[0, 1], [2, 4], [2, 5]])
r = []
for i in range(3):
bi = b[i]
r.append(a[i][bi[0]: bi[1]])
print(r)