Numpy计算自定义矩阵乘法

发布于 2025-02-14 00:12:23 字数 349 浏览 0 评论 0原文

我有两个矩阵a,b,我想创建一个3-D数组c,以便

C[k,i,j]=A[k,j]*B[k,i]

我正在考虑使用np.einsum ,但找不到方法,我不确定在这里它是否有用。

一个天真的环是可能的,但听起来很效率。

更新

C=np.einsum('kj,ki->kij',A,B)

作品非常优雅,这是@warren Weckesser的答案之上

I have two matrices A,B, and I'd like to create a 3-d array C such that

C[k,i,j]=A[k,j]*B[k,i]

I was thinking about using np.einsum but couldn't find a way and I'm not sure it's useful here.

A naïve loop is possible, but sounds quite inefficient.

UPDATE

C=np.einsum('kj,ki->kij',A,B)

works and is quite elegant, this is on top of @Warren Weckesser 's answer

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感情旳空白 2025-02-21 00:12:23

basic 广播将起作用,

In [55]: A  # shape is (2, 3)
Out[55]: 
array([[4, 9, 5],
       [2, 0, 9]])

In [56]: B  # shape is (2, 4)
Out[56]: 
array([[8, 8, 0, 3],
       [6, 8, 3, 8]])

例如,:] 具有形状(2、1、3)和b [::::,none]具有形状(2,4,, 1)。通过广播,这些表达式的产物将具有形状(2、4、3)。


In [57]: C = A[:,None,:] * B[:,:,None]

In [58]: C
Out[58]: 
array([[[32, 72, 40],
        [32, 72, 40],
        [ 0,  0,  0],
        [12, 27, 15]],

       [[12,  0, 54],
        [16,  0, 72],
        [ 6,  0, 27],
        [16,  0, 72]]])

In [59]: C.shape
Out[59]: (2, 4, 3)

Basic broadcasting will work, e.g.

In [55]: A  # shape is (2, 3)
Out[55]: 
array([[4, 9, 5],
       [2, 0, 9]])

In [56]: B  # shape is (2, 4)
Out[56]: 
array([[8, 8, 0, 3],
       [6, 8, 3, 8]])

A[:,None,:] has shape (2, 1, 3), and B[:,:,None] has shape (2, 4, 1). With broadcasting, the product of those expressions will have shape (2, 4, 3).


In [57]: C = A[:,None,:] * B[:,:,None]

In [58]: C
Out[58]: 
array([[[32, 72, 40],
        [32, 72, 40],
        [ 0,  0,  0],
        [12, 27, 15]],

       [[12,  0, 54],
        [16,  0, 72],
        [ 6,  0, 27],
        [16,  0, 72]]])

In [59]: C.shape
Out[59]: (2, 4, 3)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文