用张量切片张量张量



我正在尝试使用此pr中添加的"高级",numpy式切片,但是我在这里遇到了与用户相同的问题:

ValueError: Shape must be rank 1 but is rank 2 for 'strided_slice_15' (op: 'StridedSlice') with input shapes: [3,2], [1,2], [1,2], [1].

也就是说,我想做这个numpy操作的等效物(在numpy中起作用(:

A = np.array([[1,2],[3,4],[5,6]]) 
id_rows = np.array([0,2])
A[id_rows]

但是,对于上述错误,这在TF中不起作用:

A = tf.constant([[1,2],[3,4],[5,6]])
id_rows = tf.constant([0,2])
A[id_rows]

您正在寻找类似的东西:

A = tf.constant([[1,2],[3,4],[5,6]])
id_rows = tf.constant([[0],[2]]) #Notice the brackets
out = tf.gather_nd(A,id_rows)

您可以在下面切片张量。

A = tf.constant([[1,2],[3,4],[5,6]])
id_rows = tf.constant(np.array([0, 2]).reshape(-1, 1))
out = tf.gather_nd(A,id_rows)
with tf.Session() as session: 
    print(session.run(out))