假设我有一个 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]]
?
新矩阵中的元素是原矩阵中元素的两两组合。
此外,原始矩阵可以包含零,就像这样[[0,1],[0,3],[0,5]]
。
实现应该推广到任何维度的向量。
非常感谢!
最佳答案
您可以使用tf.meshgrid()
和tf.transpose()
生成两个矩阵。然后 reshape 并连接它们。
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]]
关于python - 从 tensorflow 中的向量构造成对矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55153745/