沿着阵列轴矩阵向量乘法 [英] Matrix vector multiplication along array axes

查看:275
本文介绍了沿着阵列轴矩阵向量乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在当前项目中,我有形状(I,J,K,N)和昏暗的N A方阵。

in a current project I have a large multidimensional array of shape (I,J,K,N) and a square matrix of dim N.

我需要执行与方形矩阵阵列的最后轴线的矩阵向量乘法

I need to perform a matrix vector multiplication of the last axis of the array with the square matrix.

所以,显而易见的解决方案是:

So the obvious solution would be:

for i in range(I):
    for j in range(J):
        for k in range(K):
            arr[i,j,k] = mat.dot(arr[i,j,k])

,但当然这是相当缓慢的。所以,我也试过numpy的的tensordot,但收效甚微。
我期望是这样的:

but of course this is rather slow. So I also tried numpy's tensordot but had little success. I would expect that something like:

arr = tensordot(mat,arr,axes=((0,1),(3))) 

应该做的伎俩,但我得到的形状不匹配错误。

should do the trick but I get a shape mismatch error.

有人有更好的解决办法,或知道如何正确使用tensordot?

Has someone a better solution or knows how to correctly use tensordot?

感谢您!

推荐答案

这应该做你的循环,但矢量循环:

This should do what your loops, but with vectorized looping:

from numpy.core.umath_tests import matrix_multiply

arr[..., np.newaxis] = matrix_multiply(mat, arr[..., np.newaxis])

matrix_multiply 和它的姊妹 inner1d 是隐藏的,无证,numpy的宝石,虽然全套线性代数gufuncs应该看到numpy的1.8的光。 matrix_multiply 不上休息就其输入的最后两个维度矩阵​​乘法,和广播。唯一棘手的部分是设置一个额外的维度,因此,它认为列向量相乘的时候,并添加它也分配回数组,所以不存在形状不匹配。

matrix_multiply and its sister inner1d are hidden, undocumented, gems of numpy, although a full set of linear algebra gufuncs should see the light with numpy 1.8. matrix_multiply does matrix multiplication on the last two dimensions of its inputs, and broadcasting on the rest. The only tricky part is setting an additional dimension, so that it sees column vectors when multiplying, and adding it also on assignment back into array, so that there is no shape mismatch.

这篇关于沿着阵列轴矩阵向量乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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