将两个相等大小的向量转换为它们的成对乘积矩阵在Python中可以这样做:

huangapple go评论57阅读模式
英文:

How do I turn 2 equal sized vectors into a matrix that's the pairwise product of the two vectors in Python?

问题

惊讶的是我找不到这个答案但我想要基本上创建一个协方差矩阵但是每个值都不是协方差我希望每个单元格都是两个向量的乘积所以如果我有一个1x5的向量我想得到一个5x5的矩阵

例如

输入

    [1, 2, 3, 4, 5]

输出

    [[ 1,  2,  3,  4,  5],
     [ 2,  4,  6,  8, 10],
     [ 3,  6,  9, 12, 15],
     [ 4,  8, 12, 16, 20],
     [ 5, 10, 15, 20, 25]]

有没有一种快速的方法而不需要构建循环
英文:

Surprised I can't find this answer, but I am looking to basically create a covariance matrix, but instead of each value being a covariance, I want each cell to be the product of the two vectors. So if I have 1x5 vector, I want to end up with a 5x5 matrix.

For example:

Input:

[1, 2, 3, 4, 5]

Output:

[[ 1,  2,  3,  4,  5],
 [ 2,  4,  6,  8, 10],
 [ 3,  6,  9, 12, 15],
 [ 4,  8, 12, 16, 20],
 [ 5, 10, 15, 20, 25]]

Is there a fast way without building a loop?

答案1

得分: 2

只需使用 numpy.outer。它计算两个向量的外积。

a = np.array([1, 2, 3, 4, 5])
res = np.outer(a,a)
print(res)

array([[ 1,  2,  3,  4,  5],
       [ 2,  4,  6,  8, 10],
       [ 3,  6,  9, 12, 15],
       [ 4,  8, 12, 16, 20],
       [ 5, 10, 15, 20, 25]])

或者如果你愿意使用 broadcasting

res = a[:,None]*a
print(res)

array([[ 1,  2,  3,  4,  5],
       [ 2,  4,  6,  8, 10],
       [ 3,  6,  9, 12, 15],
       [ 4,  8, 12, 16, 20],
       [ 5, 10, 15, 20, 25]])
英文:

Simply use numpy.outer. It computes the outer product of two vectors.

a = np.array([1, 2, 3, 4, 5])
res = np.outer(a,a)
print(res)

array([[ 1,  2,  3,  4,  5],
       [ 2,  4,  6,  8, 10],
       [ 3,  6,  9, 12, 15],
       [ 4,  8, 12, 16, 20],
       [ 5, 10, 15, 20, 25]])

Or if you are ok with broadcasting then :

res = a[:,None]*a
print(res)

array([[ 1,  2,  3,  4,  5],
       [ 2,  4,  6,  8, 10],
       [ 3,  6,  9, 12, 15],
       [ 4,  8, 12, 16, 20],
       [ 5, 10, 15, 20, 25]])

huangapple
  • 本文由 发表于 2023年6月2日 04:00:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385310.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定