【问题标题】:Calculate the dot product of an array of matrices and the rows or columns of another matrix计算矩阵数组与另一个矩阵的行或列的点积
【发布时间】:2019-10-12 13:12:07
【问题描述】:

有两个 ndarray,数组 d 形状为 (3,10,10) 和数组 e 形状为 (3,10),我如何计算 d 的第一个 10x10 矩阵的点积和e的第一行、d的第二个10x10矩阵和e的第二行等

例如,有以下两个数组:

d = np.array([np.diag([1,1,1,1,1,1,1,1,1,1]), 
              np.diag([2,2,2,2,2,2,2,2,2,2]), 
              np.diag([3,3,3,3,3,3,3,3,3,3])])     
e = np.arange(30).reshape((3,10))

如何计算 3x10 数组:

array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [20, 22, 24, 26, 28, 30, 32, 34, 36, 38],
       [60, 63, 66, 69, 72, 75, 78, 81, 84, 87]])

我尝试使用np.dotnp.tensordot 并在这样做之前将新轴转置并添加到e,但我不知道如何解决这个问题。

【问题讨论】:

    标签: python numpy linear-algebra tensor dot-product


    【解决方案1】:

    我们可以使用np.einsum -

    np.einsum('ijk,ij->ik',d,e)
    

    玩弄它的 optimize 标志以使用 BLAS。

    或者np.matmul-

    np.matmul(d,e[...,None])[...,0]
    

    注意:在 Python 3.x 上,np.matmul 可以替换为 @ operator

    【讨论】:

    • 谢谢!您知道使用np.tensordot 可能会如何工作吗?我不知道我的错误是什么,或者这是否可以使用该函数。
    • @AlexR tensordot 不起作用,因为我们需要保持第一个轴远离它们对齐。阅读此处了解更多信息 - stackoverflow.com/questions/41870228
    猜你喜欢
    • 2022-01-13
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 2020-05-19
    相关资源
    最近更新 更多