Why the following operands could not be broadcasted together?

安稳与你 提交于 2020-12-30 08:58:14

问题


The arrays are of following dimensions: dists: (500,5000) train: (5000,) test:(500,)

Why does the first two statements throw an error whereas the third one works fine?

  1. dists += train + test

Error: ValueError: operands could not be broadcast together with shapes (5000,) (500,)

  1. dists += train.reshape(-1,1) + test.reshape(-1,1)

Error: ValueError: operands could not be broadcast together with shapes (5000,1) (500,1)

  1. dists += train + test.reshape(-1,1) This works fine!

Why does this happen?


回答1:


It's to do with NumPy's broadcasting rules. Quoting the NumPy manual:

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when

  1. they are equal, or
  2. one of them is 1

The first statement throws an error because NumPy looks at the only dimension, and (5000,) and (500,) are inequal and cannot be broadcast together.

In the second statement, train.reshape(-1,1) has the shape (5000,1) and test.reshape(-1,1) has the shape (500,1). The trailing dimension (length one) is equal, so that's ok, but then NumPy checks the other dimension and 5000 != 500, so the broadcasting fails here.

In the third case, your operands are (5000,) and (500,1). In this case NumPy does allow broadcasting. The 1D-array is extended along the trailing length-1 dimension of the 2D-array.

FWIW, the shape and broadcasting rules can be a bit tricky sometimes, and I've often been confused with similar matters.



来源:https://stackoverflow.com/questions/50758165/why-the-following-operands-could-not-be-broadcasted-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!