Numpy 将 3d 矩阵乘以 2d 矩阵 [英] Numpy multiply 3d matrix by 2d matrix

查看:63
本文介绍了Numpy 将 3d 矩阵乘以 2d 矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我得到了形状为 (3,2,2) 的矩阵 A,例如

<预><代码>[[[1,1],[1,1]],[[2,2],[2,2]],[[3,3],[3,3]]]

和形状为 (2,2) 的矩阵 B,例如

[[1, 1], [0,1]]

我想实现形状为 (3,2,2) 的 c,例如:

c = np.zeros((3,2,2))对于范围内的 i(len(A)):c[i] = np.dot(B, A[i,:,:])

这给了

[[[2.2.][1.1.]][[4.4.][2.2.]][[6.6.][3.3.]]]

实现这一目标的最有效方法是什么?

谢谢.

解决方案

使用 np.tensordot 然后交换轴.因此,请使用其中之一 -

np.tensordot(B,A,axes=((1),(1))).swapaxes(0,1)np.tensordot(A,B,axes=((1),(1))).swapaxes(1,2)

我们可以在交换轴后将 A 重塑为 2D,使用带有 np.dot 的 2D 矩阵乘法并重塑和交换轴以获得边际性能提升.

时间 -

# 原始方法def orgapp(A,B):m = A.shape[0]n = B.shape[0]r = A.shape[2]c = np.zeros((m,n,r))对于范围内的 i(len(A)):c[i] = np.dot(B, A[i,:,:])返回 c在 [91] 中:n = 10000...: A = np.random.rand(n,2,2)...: B = np.random.rand(2,2)在 [92]: %timeit orgapp(A,B)100 个循环,最好的 3 个:每个循环 12.2 毫秒在 [93] 中:%timeit np.tensordot(B,A,axes=((1),(1))).swapaxes(0,1)1000 个循环,最好的 3 个:每个循环 191 µs在 [94] 中:%timeit np.tensordot(A,B,axes=((1),(1))).swapaxes(1,2)1000 个循环,最好的 3 个:每个循环 208 µs#@Bitwise 的解决方案在 [95] 中:%timeit np.flip(np.dot(A,B).transpose((0,2,1)),1)1000 个循环,最好的 3 个:每个循环 697 µs

For example, I got matrix A of shape (3,2,2), e.g.

[
[[1,1],[1,1]], 
[[2,2],[2,2]], 
[[3,3],[3,3]]
]

and matrix B of shape (2,2), e.g.

[[1, 1], [0,1]]

I would like to achieve c of shape (3,2,2) like:

c = np.zeros((3,2,2))
for i in range(len(A)):
    c[i] = np.dot(B, A[i,:,:])

which gives

[[[2. 2.]
  [1. 1.]]

 [[4. 4.]
 [2. 2.]]

 [[6. 6.]
 [3. 3.]]]

What is the most efficient way to achieve this?

Thanks.

解决方案

Use np.tensordot and then swap axes. So, use one of these -

np.tensordot(B,A,axes=((1),(1))).swapaxes(0,1)
np.tensordot(A,B,axes=((1),(1))).swapaxes(1,2)

We can reshape A to 2D after swapping axes, use 2D matrix multiplication with np.dot and reshape and swap axes to maybe gain marginal performance boost.

Timings -

# Original approach
def orgapp(A,B):
    m = A.shape[0]
    n = B.shape[0]
    r = A.shape[2]
    c = np.zeros((m,n,r))
    for i in range(len(A)):
        c[i] = np.dot(B, A[i,:,:])
    return c  

In [91]: n = 10000
    ...: A = np.random.rand(n,2,2)
    ...: B = np.random.rand(2,2)

In [92]: %timeit orgapp(A,B)
100 loops, best of 3: 12.2 ms per loop

In [93]: %timeit np.tensordot(B,A,axes=((1),(1))).swapaxes(0,1)
1000 loops, best of 3: 191 µs per loop

In [94]: %timeit np.tensordot(A,B,axes=((1),(1))).swapaxes(1,2)
1000 loops, best of 3: 208 µs per loop

# @Bitwise's solution
In [95]: %timeit np.flip(np.dot(A,B).transpose((0,2,1)),1)
1000 loops, best of 3: 697 µs per loop

这篇关于Numpy 将 3d 矩阵乘以 2d 矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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