假设我有一个1 * 3向量1,3,5(如果你有一个像[1,3,5]这样的列表),我该如何生成一个9 * 2矩阵:1,1] ],[1,3],[1,5],[3,1],[3,3],[3,5],[5,1],[5,3],[5,5 ?
新矩阵中的元素……
我也提出了一个答案,类似于@giser_yugang,但没有使用tf.meshgrid和tf.concat。
import tensorflow as tf inds = tf.constant([1,3,5]) num = tf.shape(inds)[0] ind_flat_lower = tf.tile(inds,[num]) ind_mat = tf.reshape(ind_flat_lower,[num,num]) ind_flat_upper = tf.reshape(tf.transpose(ind_mat),[-1]) result = tf.transpose(tf.stack([ind_flat_upper,ind_flat_lower])) with tf.Session() as sess: print(sess.run(result)) [[1 1] [1 3] [1 5] [3 1] [3 3] [3 5] [5 1] [5 3] [5 5]]
您可以使用 tf.meshgrid() 和 tf.transpose() 生成两个矩阵。然后重塑并连接它们。
tf.meshgrid()
tf.transpose()
import tensorflow as tf a = tf.constant([[1,3,5]]) A,B=tf.meshgrid(a,tf.transpose(a)) result = tf.concat([tf.reshape(B,(-1,1)),tf.reshape(A,(-1,1))],axis=-1) with tf.Session() as sess: print(sess.run(result)) [[1 1] [1 3] [1 5] [3 1] [3 3] [3 5] [5 1] [5 3] [5 5]]
您可以使用 product 从 itertools
product
itertools
from itertools import product np.array([np.array(item) for item in product([1,3,5],repeat =2 )]) array([[1, 1], [1, 3], [1, 5], [3, 1], [3, 3], [3, 5], [5, 1], [5, 3], [5, 5]])