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

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

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

问题

  1. 惊讶的是我找不到这个答案但我想要基本上创建一个协方差矩阵但是每个值都不是协方差我希望每个单元格都是两个向量的乘积所以如果我有一个1x5的向量我想得到一个5x5的矩阵
  2. 例如
  3. 输入
  4. [1, 2, 3, 4, 5]
  5. 输出
  6. [[ 1, 2, 3, 4, 5],
  7. [ 2, 4, 6, 8, 10],
  8. [ 3, 6, 9, 12, 15],
  9. [ 4, 8, 12, 16, 20],
  10. [ 5, 10, 15, 20, 25]]
  11. 有没有一种快速的方法而不需要构建循环
英文:

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. [1, 2, 3, 4, 5]

Output:

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

Is there a fast way without building a loop?

答案1

得分: 2

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

  1. a = np.array([1, 2, 3, 4, 5])
  2. res = np.outer(a,a)
  3. print(res)
  4. array([[ 1, 2, 3, 4, 5],
  5. [ 2, 4, 6, 8, 10],
  6. [ 3, 6, 9, 12, 15],
  7. [ 4, 8, 12, 16, 20],
  8. [ 5, 10, 15, 20, 25]])

或者如果你愿意使用 broadcasting

  1. res = a[:,None]*a
  2. print(res)
  3. array([[ 1, 2, 3, 4, 5],
  4. [ 2, 4, 6, 8, 10],
  5. [ 3, 6, 9, 12, 15],
  6. [ 4, 8, 12, 16, 20],
  7. [ 5, 10, 15, 20, 25]])
英文:

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

  1. a = np.array([1, 2, 3, 4, 5])
  2. res = np.outer(a,a)
  3. print(res)
  4. array([[ 1, 2, 3, 4, 5],
  5. [ 2, 4, 6, 8, 10],
  6. [ 3, 6, 9, 12, 15],
  7. [ 4, 8, 12, 16, 20],
  8. [ 5, 10, 15, 20, 25]])

Or if you are ok with broadcasting then :

  1. res = a[:,None]*a
  2. print(res)
  3. array([[ 1, 2, 3, 4, 5],
  4. [ 2, 4, 6, 8, 10],
  5. [ 3, 6, 9, 12, 15],
  6. [ 4, 8, 12, 16, 20],
  7. [ 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:

确定