Python 从tensorflow中的向量构造成对矩阵

Python 从tensorflow中的向量构造成对矩阵,python,numpy,tensorflow,matrix,Python,Numpy,Tensorflow,Matrix,假设我有一个1*3的向量[[1,3,5](或者一个类似[1,3,5]的列表,如果你有),我如何生成一个9*2矩阵:[[1,1],[1,3],[1,5],[3,1],[3,5],[5,5] 新矩阵中的元素是原始矩阵中元素的成对组合 另外,原始矩阵可以是零,就像这样[[0,1],[0,3],[0,5] 实现应该推广到任何维度的向量 非常感谢 您可以从itertools from itertools import product np.array([np.array(item) for item in

假设我有一个1*3的向量
[[1,3,5]
(或者一个类似
[1,3,5]
的列表,如果你有),我如何生成一个9*2矩阵:
[[1,1],[1,3],[1,5],[3,1],[3,5],[5,5]

新矩阵中的元素是原始矩阵中元素的成对组合

另外,原始矩阵可以是零,就像这样
[[0,1],[0,3],[0,5]

实现应该推广到任何维度的向量


非常感谢

您可以从
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]])

您可以使用
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]]

我还提出了一个类似于@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]]

谢谢但是我问的是tensorflow的实现。tf.reforme(B,(-1,1))很有趣,我在官方文档中没有找到类似的用法示例。@Clement 116此用法文档已经存在。类似于示例中的
reformate(t[2,-1])
reformate(t[1,9])
。@clement116不客气。如果你没有问题,请接受。