【问题标题】:numpy function to use for mathematical dot product to produce scalar用于数学点积以产生标量的 numpy 函数
【发布时间】:2021-04-16 11:17:46
【问题描述】:

问题

在以下情况下,数学点积使用什么 numpy 函数?

【问题讨论】:

标签: numpy dot-product


【解决方案1】:

定义样本(2,3)数组:

In [299]: dldx = np.arange(6).reshape(2,3)
In [300]: w
Out[300]: 
array([[0.1, 0.2, 0.3],
       [0. , 0. , 0. ]])

元素乘法:

In [301]: dldx*w
Out[301]: 
array([[0. , 0.2, 0.6],
       [0. , 0. , 0. ]])

在最后一个轴(大小为 3)上求和生成一个 2 元素数组:

In [302]: (dldx*w).sum(axis=1)
Out[302]: array([0.8, 0. ])

您的 (6) 是第一项,去掉了 0。有人可能会争辩说,在 (5) 中使用点/内部有点草率。

np.einsum 借鉴了物理学的思想,其中维度可能更高。这种情况可以表示为

In [303]: np.einsum('ij,ik->i',dldx,w)
Out[303]: array([1.8, 0. ])

innerdot 做更多我们想要的计算。我们只需要对角线:

In [304]: np.dot(dldx,w.T)
Out[304]: 
array([[0.8, 0. ],
       [2.6, 0. ]])
In [305]: np.inner(dldx,w)
Out[305]: 
array([[0.8, 0. ],
       [2.6, 0. ]])

matmul/@ 术语中,第 2 个维度是一个“批量”维度,因此我们必须添加维度:

In [306]: dldx[:,None,:]@w[:,:,None]
Out[306]: 
array([[[0.8]],

       [[0. ]]])

这是(2,1,1),所以我们需要挤出1。

【讨论】:

    猜你喜欢
    • 2020-10-31
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    相关资源
    最近更新 更多