您可以先对列的索引重新排序。
import tensorflow as tf
a = [[[1,1],[2,2],[3,3]],
[[4,4],[5,5],[6,6]],
[[7,7],[8,8],[9,9]]]
b = [[[10,10],[11,11]],
[[12,12],[13,13]],
[[14,14],[15,15]]]
a_tf = tf.constant(a)
b_tf = tf.constant(b)
a_tf_column = tf.range(a_tf.shape[1])*2
# [0 2 4]
b_tf_column = tf.range(b_tf.shape[1])*2+1
# [1 3]
column_indices = tf.concat([a_tf_column,b_tf_column],axis=-1)
# Before TF v1.13
column_indices = tf.contrib.framework.argsort(column_indices)
## From TF v1.13
# column_indices = tf.argsort(column_indices)
# [0 3 1 4 2]
那么您应该为tf.gather_nd() 创建新索引。
column,row = tf.meshgrid(column_indices,tf.range(a_tf.shape[0]))
combine_indices = tf.stack([row,column],axis=-1)
# [[[0,0],[0,3],[0,1],[0,4],[0,2]],
# [[1,0],[1,3],[1,1],[1,4],[1,2]],
# [[2,0],[2,3],[2,1],[2,4],[2,2]]]
最后你应该连接a和b的值并使用tf.gather_nd()得到结果。
combine_value = tf.concat([a_tf,b_tf],axis=1)
result = tf.gather_nd(combine_value,combine_indices)
with tf.Session() as sess:
print(sess.run(result))
# [[[1,1],[10,10],[2,2],[11,11],[3,3]],
# [[4,4],[12,12],[5,5],[13,13],[6,6]],
# [[7,7],[14,14],[8,8],[15,15],[9,9]]]