One error you may encounter when using Python is:
ValueError: operands could not be broadcast together with shapes (2,2) (2,3)
This error occurs when you attempt to perform matrix multiplication using a multiplication sign (*) in Python instead of the numpy.dot() function.
The following examples shows how to fix this error in each scenario.
How to Reproduce the Error
Suppose we have a 2×2 matrix C, which has 2 rows and 2 columns:
Suppose we also have a 2×3 matrix D, which has 2 rows and 3 columns:
Here is how to multiply matrix C by matrix D:
This results in the following matrix:
Suppose we attempt to perform this matrix multiplication in Python using a multiplication sign (*) as follows:
import numpy as np #define matrices C = np.array([7, 5, 6, 3]).reshape(2, 2) D = np.array([2, 1, 4, 5, 1, 2]).reshape(2, 3) #print matrices print(C) [[7 5] [6 3]] print(D) [[2 1 4] [5 1 2]] #attempt to multiply two matrices together C*D ValueError: operands could not be broadcast together with shapes (2,2) (2,3)
We receive a ValueError. We can refer to the NumPy documentation to understand why we received this error:
When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e. rightmost) dimensions and works its way left. Two dimensions are compatible when
Â
- they are equal, or
- one of them is 1
If these conditions are not met, a ValueError: operands could not be broadcast together exception is thrown, indicating that the arrays have incompatible shapes.
Since our two matrices do not have the same value for their trailing dimensions (matrix C has a trailing dimension of 2 and matrix D has a trailing dimension of 3), we receive an error.
How to Fix the Error
The easiest way to fix this error is to simply using the numpy.dot() function to perform the matrix multiplication:
import numpy as np #define matrices C = np.array([7, 5, 6, 3]).reshape(2, 2) D = np.array([2, 1, 4, 5, 1, 2]).reshape(2, 3) #perform matrix multiplication C.dot(D) array([[39, 12, 38], [27, 9, 30]])
Notice that we avoid a ValueError and we’re able to successfully multiply the two matrices.
Also note that the results match the results that we calculated by hand earlier.
Additional Resources
The following tutorials explain how to fix other common errors in Python:
How to Fix: columns overlap but no suffix specified
How to Fix: ‘numpy.ndarray’ object has no attribute ‘append’
How to Fix: if using all scalar values, you must pass an index
How to Fix: ValueError: cannot convert float NaN to integer