python numpy ValueError: operands could not be broadcast together with shapes

The ValueError: operands could not be broadcast together with shapes error occurs in NumPy when the shapes of the arrays being operated on are incompatible. Here is an example of code that would raise this error:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5])

c = a + b

In this example, a has shape (3,) and b has shape (2,). When the + operator is used on these two arrays, NumPy tries to broadcast the smaller array (b) to match the shape of the larger array (a) by repeating its elements. However, the shapes are not compatible, so the error is raised.

Watch a course Python - The Practical Guide

To fix this error, you need to make sure that the shapes of the arrays being operated on are compatible. One way to do this is to reshape the arrays so that they have the same number of dimensions and the same size along each dimension. Another way is to use numpy function like numpy.newaxis, numpy.expand_dims, numpy.atleast_1d, numpy.atleast_2d etc.

a = np.array([1, 2, 3])
b = np.array([4, 5])

c = a[:, np.newaxis] + b

This will work as the shape of b (2,) will be broadcast to (2,1) and matches the shape of a (3,1)

You can also use numpy's broadcasting functionality by reshaping the arrays to have compatible shapes.

a = np.array([1, 2, 3])
b = np.array([4, 5])

c = a + b[:, None]

This will work as the shape of b (2,) will be broadcast to (1,2) and matches the shape of a (3,1)