It seems you are trying to lose the last two axes of the first array against the only two axes of the second weight array with that matrix-multiplication. We could translate that idea into NumPy code with np.tensordot and assuming arr1 and arr2 as the input arrays respectively, like so -

np.tensordot(arr1,arr2,axes=([1,2],[0,1]))

Another simpler way to put into NumPy code would be with np.einsum, like so -

np.einsum('ijk,jk',arr1,arr2)
Answer from Divakar on Stack Overflow
Discussions

arrays - How do I multiply a 3D matrix and 2D matrix using numpy in Python? - Stack Overflow
My 3d array has shape (3, 2, 3), my 2d array is (2, 3). The multiplication i want to conduct is np.dot(2d, 3d[i,:,:].T) so it should return a result with shape (3, 2, 2). I could write a loop, but ... More on stackoverflow.com
🌐 stackoverflow.com
November 15, 2019
python - Numpy multiply 3d matrix by 2d matrix - Stack Overflow
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. More on stackoverflow.com
🌐 stackoverflow.com
June 11, 2018
python - Numpy - multiple 3d array with a 2d array - Stack Overflow
I'm trying the following: Given a matrix A (x, y ,3) and another matrix B (3, 3), I would like to return a (x, y, 3) matrix in which the 3rd dimension of A is multiplied by the values of B (simila... More on stackoverflow.com
🌐 stackoverflow.com
python - Multiply a 3d tensor with a 2d matrix using torch.matmul - Stack Overflow
I have two tensors in PyTorch, z is a 3d tensor of shape (n_samples, n_features, n_views) in which n_samples is the number of samples in the dataset, n_features is the number of features for each s... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › numpy-3d-matrix-multiplication
NumPy - 3D matrix multiplication - GeeksforGeeks
July 23, 2025 - It is the fundamental package for scientific computing with Python. A 3D matrix is nothing but a collection (or a stack) of many 2D matrices, just like how a 2D matrix is a collection/stack of many 1D vectors. So, matrix multiplication of 3D matrices involves multiple multiplications of 2D ...
🌐
YouTube
youtube.com › codemore
How do I multiply a 3D matrix and 2D matrix using numpy in Python - YouTube
Download this code from https://codegive.com Certainly! Multiplying a 3D matrix and a 2D matrix using NumPy in Python involves using the numpy.dot() function...
Published: November 21, 2023
Views: 113
🌐
Blogger
debmoran.blogspot.com › home › multiply › numpy
Numpy Multiply 3d Array By 2d Array - Deb Moran's Multiplying Matrices
July 30, 2021 - What you can do there is reshape your 2D array B such that it is a 3D array with an inner dimension of length 1. A handful of simple operations. In order to perform matrix multiplication of 2-dimensional arrays we can use the numpy dot function.
Find elsewhere
Top answer
1 of 1
2

Yes that's possible. If you have mutiple batch dimensions in both operatns, you can use the broadcasting. In this case the last two dimensions of each operand are interpreted as a matrix size. (I recommend looking it up in the documentation.)

So you need an additional dimension for your vectors b, to make them a n x 1 "matrix" (column vector):

# original implementation
b1 = b.unsqueeze(1)
r1 = z * b1
r1 = torch.sum(r1, dim=-1)
print(r1.shape)

# using torch.matmul
r2 = torch.matmul(z, b.unsqueeze(2))[...,0]
print(r2.shape)
print((r1-r2).abs().sum())  # should be zero if we do the same operation

Alternatively, torch.einsum also makes this very straightforward.

# using torch.einsum
r3 = torch.einsum('ijk,ik->ij', z, b)
print((r1-r3).abs().sum())  # should be zero if we do the same operation

einsum is a very powerful operation that can do a lot of things: you can permute tensor dimensions, sum along them, or perform scalar products, all with or without broadcasting. It is derived from the Einstein summation convention mostly used in physics. The rough idea is that you give every dimension of your operans a name, and then, using these names define what the output should look like. I think it is best to read the documentation. In our case we have a 4 x 3 x 2 tensor as well as a 4 x 2 tensor. So the let's call the dimensions of the first tensor ijk. Here i and k should be considered the same as the dimensions of the second tensor, so this one can be described as ik. Finally the output should have clearly be ij (it mus be a 4 x 3 tensor). From this "signature" ijk, ik -> ij it is clear that the dimension i is preserved, and the dimensions k must be "summe/multiplied" away (scalar product).

🌐
Javatpoint
javatpoint.com › numpy-3d-matrix-multiplication
Numpy-3d Matrix Multiplication - Javatpoint
Numpy-3d Matrix Multiplication with tutorial, tkinter, button, overview, canvas, frame, environment set-up, first python program, etc.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.matmul.html
numpy.matmul — NumPy v2.5 Manual
Vector-matrix product for stacks of vectors and matrices. ... Sum products over arbitrary axes. ... Einstein summation convention. ... The behavior depends on the arguments in the following way. If both arguments are 2-D they are multiplied like conventional matrices.
Top answer
1 of 4
3

The problem is that numpy views multidimensional arrays as stacks of matrices, and always the last two dimensions are assumed to be the linear space dimensions. This means that the dot product will not work by collapsing the first dimension of your 3d array.

Instead the simplest thing you can do is to reshape your 3d array into a 2d one, doing the matrix multiplication, and reshaping back into a 3d array. This will also make use of optimised BLAS code which is one of the great advantages of numpy.

import numpy as np 

S_pinv = np.random.rand(3, 4)
images = np.random.rand(4, 5, 6)

# error: 
# (S_pinv @ images).shape 
res_shape = S_pinv.shape[:1] + images.shape[1:]  # (3, 5, 6) 
res = (S_pinv @ images.reshape(images.shape[0], -1)).reshape(res_shape)
print(res.shape)  # (3, 5, 6)

So instead of (3,n) x (n,h,w) we do (3,n) x (n, h*w) -> (3, h*w) which we reshape back to (3, h, w). Reshaping is free, because this doesn't mean any actual manipulation of data in memory (only a reinterpretation of the single block of memory that underlies the array), and as I said proper matrix products are highly optimized in numpy.


Since you asked for a more intuitive way, here's an alternative making use of numpy.einsum. It will probably be slower, but it's very transparent if you get a little bit used to its notation:

res_einsum = np.einsum('tn,nhw -> thw', S_pinv, images)
print(np.array_equal(res, res_einsum))  # True

This notation names each of the dimensions of the input arrays: for S_pinv the first and second dimensions are named t and n, respectively, and similarly n, h and w for images. The output is set to have dimensions thw which means that any remaining dimensions that are not present in the output shape will be summed along after multiplying the input arrays. This is exactly what you need.


As you noted in a comment, you could also transpose your arrays so that np.dot finds the right dimensions in the right place. But this will also be slow because this might lead to copies in memory, or at least suboptimal looping over your arrays.

I made a quick timing comparison using the following defininitions:

def reshaped(S_pinv, images): 
    res_shape = S_pinv.shape[:1] + images.shape[1:] 
    return (S_pinv @ images.reshape(images.shape[0], -1)).reshape(res_shape)

def einsummed(S_pinv, images): 
    return np.einsum('tn,nhw -> thw', S_pinv, images) 

def transposed(S_pinv, images): 
    return (S_pinv @ images.transpose(2, 0, 1)).transpose(1, 2, 0)          

And here's the timing test using IPython's built-in %timeit magic, and some more realistic array sizes:

>>> S_pinv = np.random.rand(3, 100) 
... images = np.random.rand(100, 200, 300) 
... args = S_pinv, images 
... %timeit reshaped(*args) 
... %timeit einsummed(*args) 
... %timeit transposed(*args)                                          
5.92 ms ± 460 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
15.9 ms ± 190 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
44.5 ms ± 329 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
2 of 4
0

answer is np.swapaxes

import numpy as np

q= np.random.random([2, 5,5])
q.shape

w = np.random.random([3,2])
w.shape

w@q

and we have ValueError but

import numpy as np

q= np.random.random([5, 2,5])
q.shape

w = np.random.random([3,2])
w.shape

res = (w@q).swapaxes(0,1)
res.shape # =[3, 5, 5]
🌐
Data Science Dojo
discuss.datasciencedojo.com › python
How can arrays with different dimensions be multiplied? - Python - Data Science Dojo Discussions
February 28, 2023 - Yes, you can multiply arrays of different dimensions using NumPy’s .reshape() method. It will first reshape the arrays to match their dimensions and then apply multiplication. A sample code is provided below for your understanding. This code generates a 3D array ‘a’ with shape (5,5,3) and a 2D array ‘b’ with shape (5,5).
🌐
PyTorch Forums
discuss.pytorch.org › uncategorized
How can i compute 3D tensor * 2D tensor multiplication? - Uncategorized - PyTorch Forums
February 21, 2017 - In numpy, when i have a 3D tensor X with shape [A, B, C] and a 2D tensor Y with shape [C, D], then np.dot(X, Y) gives a 3D tensor with shape [A, B, D]. In PyTorch, i can do this as below. result = torch.mm(X.view(-1, C), Y) result = result.view(-1, B, D) Is there simpler way to handle this?
🌐
DigitalOcean
digitalocean.com › community › tutorials › numpy-matrix-multiplication
NumPy Matrix Multiplication: Methods and Examples | DigitalOcean
August 4, 2022 - Perform matrix multiplication in NumPy using dot(), matmul(), and @ operator. Complete guide with examples for 2D, 3D arrays and performance tips.
🌐
YouTube
youtube.com › watch
Understanding Numpy Matmul in 3D through Examples - YouTube
Here I take you through many examples of Numpy matrix multiplication with combinations of 3D, 2D, and 1D arrays. By the end of the video, you'll have a deep ...
Published: August 23, 2023
🌐
Programiz
programiz.com › python-programming › examples › multiply-matrix
Python Program to Multiply Two Matrices | Programiz
March 14, 2024 - Multiplication of two matrices X and Y is defined only if the number of columns in X is equal to the number of rows Y. If X is a n x m matrix and Y is a m x l matrix then, XY is defined and has the dimension n x l (but YX is not defined).
🌐
Educative
educative.io › blog › numpy-matrix-multiplication
NumPy matrix multiplication: Get started in 5 minutes
April 30, 2026 - Batch matrix multiplication means performing matrix multiplication across a stack of matrices at once. ... NumPy treats higher-dimensional arrays (3D or more) as a stack of matrices.