【问题标题】:Matrix multiplication-style addition in numpynumpy中的矩阵乘法式加法
【发布时间】:2020-03-12 05:47:59
【问题描述】:

我在 numpy 中有一个行向量 a 和一个列向量 b。如果我要对两个向量进行矩阵乘法,我会得到一个矩阵m,其中m[i,j] = a[i]b[j]。我想知道是否有一种简单的方法可以执行这种加法运算 - 即获得一个矩阵n,其中n[i,j] = a[i] + b[j]。是否有执行此类操作的内置方法?

【问题讨论】:

标签: python numpy


【解决方案1】:

我猜你的意思是np.add

import numpy as np    

x1 = np.arange(3).reshape((3, 1))
x2 = np.arange(3).reshape((1, 3))
result = np.add(x1, x2)

print(x1, '\n')
print(x2, '\n')
print(result)

输出:

[[0]
 [1]
 [2]] 

[[0 1 2]] 

[[0 1 2]
 [1 2 3]
 [2 3 4]]

【讨论】:

  • + 工作正常。您不需要显式调用 ufunc。
  • @user2357112supportsMonica 没错!
【解决方案2】:

将 (n,) 数组扩展为 (n,1) 的一种紧凑方法是使用 np.newaxisNone 索引:

In [30]: a = np.arange(1,5); b = np.arange(1,4)*10                                             
In [31]: a,b                                                                                   
Out[31]: (array([1, 2, 3, 4]), array([10, 20, 30]))
In [32]: a[:,None]+b                                                                           
Out[32]: 
array([[11, 21, 31],
       [12, 22, 32],
       [13, 23, 33],
       [14, 24, 34]])

地点:

In [33]: a[:,None]                                                                             
Out[33]: 
array([[1],
       [2],
       [3],
       [4]])

broadcasting 进程是:

(m,1), (n,) => (m,1),(1,n) => (m,n)

+ufunc 版本是np.add,因此它有一个outer 方法:

In [35]: np.add.outer(a,b)                                                                     
Out[35]: 
array([[11, 21, 31],
       [12, 22, 32],
       [13, 23, 33],
       [14, 24, 34]])

np.outer(a,b)np.multiply.outer(a,b)a[:,None]*b 是等效的 outer product 表达式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2014-09-22
    • 2015-01-07
    • 2017-03-04
    相关资源
    最近更新 更多