Programming Machine Learning: matplotlib broadcast error on page 58

When I try to run the code multiple_regression_without_bias.py from page 58 of the book, I get the following error:

File “[path snipped]/multilple_regression_without_bias.py”, line 13, in gradient
return 2 * np.matmul(X.T * (predict(X, w) - Y)) / X.shape[0]
ValueError: operands could not be broadcast together with shapes (3,30) (30,1)

This happens whether I run the code I’ve typed in or the code I’ve downloaded from the PragProg website.

For information, my versions are:
Python 3.9.7
Numpy 1.26.3

Any help or advice would be greatly appreciated.

Hello, @tihnessa! Sorry for the slow reply. I was on travel.

Somehow, the code you’re using isn’t the same as in the current book and downloadable code. It’s not:

return 2 * np.matmul(X.T * (predict(X, w) - Y)) / X.shape[0]

but rather:

return 2 * np.matmul(X.T, (predict(X, w) - Y)) / X.shape[0]

(Note the comma after X.T, as opposed to the multiplication).

I have no idea what happened here. Maybe this was a bug in the book that I later fixed, and you have an older version of the book+code? Or maybe you were experimenting with the code and changed that line? In any case, that seems to be the issue.

Can you please confirm that you got it fixed?