如何在tensorflow中进行多维切片?

如何在tensorflow中进行多维切片?,tensorflow,Tensorflow,例如: array = [[1, 2, 3], [4, 5, 6]] slice = [[0, 0, 1], [0, 1, 2]] output = [[1, 1, 2], [4, 5,6]] 我尝试了array[slice],但没有成功。我也无法让tf.gather或tf.gather\u和工作,尽管这些最初似乎是正确的函数。注意,这些都是图中的张量 如何根据切片在数组中选择这些值?您需要在切片张量中添加一个维度,您可以使用tf.pack,然后我们可以使用tf.collection\n没

例如:

array = [[1, 2, 3], [4, 5, 6]]

slice = [[0, 0, 1], [0, 1, 2]]

output = [[1, 1, 2], [4, 5,6]]
我尝试了
array[slice]
,但没有成功。我也无法让
tf.gather
tf.gather\u和
工作,尽管这些最初似乎是正确的函数。注意,这些都是图中的张量


如何根据切片在数组中选择这些值?

您需要在
切片
张量中添加一个维度,您可以使用
tf.pack
,然后我们可以使用
tf.collection\n
没有问题

将tensorflow导入为tf
张量=tf.常数([[1,2,3],[4,5,6]]
old_slice=tf.常量([[0,0,1],[0,1,2]]
#我们需要增加一个维度,我们需要一个秩为2,3,2的张量,而不是2,3
dims=tf.常数([[0,0,0],[1,1,1]]
新切片=tf.pack([dims,旧切片],2)
out=tf.聚集nd(张量,新切片)
如果我们运行以下代码:

将tf.Session()作为sess的
:
sess.run(tf.initialize\u all\u variables())
run\u tensor,run\u slice,run\u out=sess.run([tensor,new\u slice,out])
打印“输入张量:”
打印运行张量
打印“正确的聚集参数:”
打印运行片
打印“输出:”
打印输出
这将提供正确的输出:

Input tensor:
[[1 2 3]
 [4 5 6]]
Correct param for gather_nd:
[[[0 0]
  [0 0]
  [0 1]]

 [[1 0]
  [1 1]
  [1 2]]]
Output:
[[1 1 2]
 [4 5 6]]

计算结果的一种更简单的方法,也是更一般的方法,是直接利用以下参数的
batch_dims
参数:

数组=tf.常数([[1,2,3],[4,5,6]) >>>切片=tf.常数([[0,0,1],[0,1,2]] >>>输出=tf.常数([[1,1,2],[4,5,6]) >>>tf.聚集(阵列、切片、批次尺寸=1,轴=1)
>>> array = tf.constant([[1,2,3], [4,5,6]])
>>> slice = tf.constant([[0,0,1], [0,1,2]])
>>> output = tf.constant([[1,1,2], [4,5,6]])
>>> tf.gather(array, slice, batch_dims=1, axis=1)
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 1, 2],
       [4, 5, 6]], dtype=int32)>