In NumPy, you can simply use a few functions, as mentioned in this article, to perform matrix multiplication between two arrays. However, before you can multiply the two arrays in question, you need to ensure that their shapes are compatible with matrix multiplication. If they’re not compatible to be multiplied, then you’ve to make them compatible to be multiplied. In this article, we will explore how to multiply arrays of different dimensions using three different NumPy methods. In the methods below, we will have two arrays A
with dimensions (5, 5, 3)
and array B
with dimensions (5, 5)
.
1. Using "Broadcasting":
- Broadcasting is the process of making arrays with different shapes compatible with arithmetic operations.
- Here, we first import the NumPy library and assign it the alias
np
. Then, the code creates two random NumPy arrays calleda
andb
. - It then uses broadcasting to multiply
a
andb
along the last axis, resulting in a new arrayc
with dimensions(5, 5, 3)
. - The resulting shape of
c
indicates that the last axis ofb
was broadcasted to match the third axis ofa
. The commented-out line can be uncommented to print the resulting arrayc
.
2. Using "np.reshape()":
- In this technique, we first import the NumPy library and assign it the alias
np
. Then, the code creates two random NumPy arrays calleda
andb
. - It then reshapes
b
to have the same dimensions asa
usingb.reshape((5,5,1))
. - It then multiplies
a
andb_reshaped
along the last axis, resulting in a new arrayc
with dimensions(5,5,3)
. - The resulting shape of
c
indicates that the last axis ofb
was reshaped to match the third axis ofa
. The commented-out line can be uncommented to print the resulting arrayc
.
3. Using Einstein Summation "(np.einsum)":
- Here, we first import the NumPy library and assign it the alias
np
. Then, the code creates two random NumPy arrays calleda
andb
. - It then uses Einstein summation to multiply
a
andb
along the last axis, resulting in a new arrayc
with dimensions(5,5,3)
. - The resulting shape of
c
indicates that the last axis ofb
was used to multiply the last axis ofa
. The commented-out line can be uncommented to print the resulting arrayc
.