简体   繁体   English

使用 numpy 矩阵将 3D 数组的切片与二维数组的切片相乘

[英]Matrix multiply slices of 3D array with slices of 2D array using numpy

A is a 2 dimensional array with dimensions (s, a) and B is a 3 dimensional array with (s, a, a). A 是具有维度 (s, a) 的 2 维数组,B 是具有 (s, a, a) 的 3 维数组。

I want B[i, :, :] @ A[i, :] for every i in range(s).对于范围内的每个 i,我想要 B[i, :, :] @ A[i, :]。 The result should be arranged in an array of shape (s, a).结果应排列成形状 (s, a) 的数组。 In code:在代码中:

s = 4
a = 3

A = np.random.uniform(size = [s,a])
B = np.random.uniform(size= [s ,a, a])

C = np.zeros_like(A)
for i in range(A.shape[0]):
  C[i,:] = (A[i,:] @ B[i,:,:])

I am looking for C.我正在寻找 C。 The catch is that everything should happen in numpy, without slicing A and B.问题是所有事情都应该发生在 numpy 中,而不需要切片 A 和 B。

Numpy does batched multiplication to last two dimensions if the first n-2 dimensions match.如果前 n-2 个维度匹配,Numpy 会批量乘法到最后两个维度。 You create a extra dimension with None and use matmul您使用None创建一个额外的维度并使用 matmul

(A[:,None,:]@B).reshape(A.shape[0],-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM