python:有效地将矩阵堆栈的切片i乘以矩阵的第i列 [英] python: Multiply slice i of a matrix stack by column i of a matrix efficiently

查看:132
本文介绍了python:有效地将矩阵堆栈的切片i乘以矩阵的第i列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import numpy as np
M,N,R = 2,3,4

# For a 3-dimensional array A:
A = np.reshape(np.r_[0:M*N*R], [M,N,R], order = 'C')

# and 2-dimensional array B:
B = np.reshape(np.r_[0:M*R], [R,M], order = 'C')

我希望将A的切片iB的列i相乘而得到的N*M矩阵.我尝试过np.dotnp.einsum,但无法获得所需的信息.

I would like the N*M matrix that results from multiplying slice i of A by column i of B. I have tried np.dot, and np.einsum and have been unable to obtain what I need.

有人可以帮忙吗?谢谢!

Could anybody help, please? Thanks!

推荐答案

使用

With np.einsum, we would have -

np.einsum('ijk,ki->ji',A,B)

让我们使用给定的样本并使用np.dot-

Let's verify the results using the given sample and using matrix-multiplication with np.dot -

In [35]: A.shape
Out[35]: (2, 3, 4)

In [36]: B.shape
Out[36]: (4, 2)

In [37]: A[0].dot(B[:,0])
Out[37]: array([ 28,  76, 124])

In [38]: A[1].dot(B[:,1])
Out[38]: array([226, 290, 354])

In [39]: np.einsum('ijk,ki->ji',A,B)
Out[39]: 
array([[ 28, 226],
       [ 76, 290],
       [124, 354]])

关于何时在np.dot/np.tensordot之类的dot-based工具上使用einsum的方面,这是

For aspects related to when to use einsum over dot-based tools like np.dot/np.tensordot, here's a related post.

这篇关于python:有效地将矩阵堆栈的切片i乘以矩阵的第i列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆