python - 我可以使用 np.dot 生成 np.outer 的结果吗?

标签 python numpy matrix-multiplication

我正在努力提高我对 numpy 函数的理解。我了解 numpy.dot 的行为。我想根据 numpy.dot 理解 numpy.outer 的行为。

基于这篇维基百科文章 https://en.wikipedia.org/wiki/Outer_product我希望 array_equal 在以下代码中返回 True。然而事实并非如此。

X = np.matrix([
    [1,5],
    [5,9],
    [4,1]
])

r1 = np.outer(X,X)
r2 = np.dot(X, X.T)
np.array_equal(r1, r2)

如何分配 r2 以便 np.array_equal 返回 True?另外,为什么 numpy 的 np.outer 实现与维基百科上的外乘定义不匹配?

使用 numpy 1.9.2

最佳答案

In [303]: X=np.array([[1,5],[5,9],[4,1]])
In [304]: X
Out[304]: 
array([[1, 5],
       [5, 9],
       [4, 1]])
In [305]: np.inner(X,X)
Out[305]: 
array([[ 26,  50,   9],
       [ 50, 106,  29],
       [  9,  29,  17]])
In [306]: np.dot(X,X.T)
Out[306]: 
array([[ 26,  50,   9],
       [ 50, 106,  29],
       [  9,  29,  17]])

Wiki 外部链接主要讨论向量、一维数组。你的 X 是二维的。

In [310]: x=np.arange(3)
In [311]: np.outer(x,x)
Out[311]: 
array([[0, 0, 0],
       [0, 1, 2],
       [0, 2, 4]])
In [312]: np.inner(x,x)
Out[312]: 5
In [313]: np.dot(x,x)   # same as inner
Out[313]: 5
In [314]: x[:,None]*x[None,:]   # same as outer
Out[314]: 
array([[0, 0, 0],
       [0, 1, 2],
       [0, 2, 4]])

请注意,Wiki 外部不涉及求和。内部确实如此,在此示例中 5 是外部的 3 个对角线值的总和。

dot 还涉及求和 - 所有乘积都遵循特定轴的求和。

一些 wiki 外部方程使用显式索引。 einsum 函数可以实现这些计算。

In [325]: np.einsum('ij,kj->ik',X,X)
Out[325]: 
array([[ 26,  50,   9],
       [ 50, 106,  29],
       [  9,  29,  17]])
In [326]: np.einsum('ij,jk->ik',X,X.T)
Out[326]: 
array([[ 26,  50,   9],
       [ 50, 106,  29],
       [  9,  29,  17]])
In [327]: np.einsum('i,j->ij',x,x)
Out[327]: 
array([[0, 0, 0],
       [0, 1, 2],
       [0, 2, 4]])
In [328]: np.einsum('i,i->',x,x)
Out[328]: 5

如评论中所述,np.outer使用ravel,例如

return a.ravel()[:, newaxis]*b.ravel()[newaxis,:]

这与我之前为 x 演示的广播乘法相同。

关于python - 我可以使用 np.dot 生成 np.outer 的结果吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33617922/

相关文章:

python - 以最快的方式生成所有 base 26 三元组

python - numpy/python中的时间序列平均

python - pypy import clr 在 Windows 上失败

python - Gtk-警告 ** : cannot open display: :0. 0 --- Ubuntu 14.04

python - 使用 PYTHON 将 3 维 DataFrame 转换为 3 维数组时出现问题

python - Pandas 无法从 Numpy 时间戳数组创建 DataFrame

python - 如何消除 ndarray 的虚拟维度?

c++ - 矩阵 - 返回并作为参数传递 c++

pandas - pandas 数据帧之间的矩阵乘法

c - NUMA 架构上不同数据类型的 OpenMP 性能