python - Numpy array broadcasting rules -
i'm having trouble understanding rules array broadcasting in numpy.
obviously, if perform element-wise multiplication on 2 arrays of same dimensions , shape, fine. also, if multiply multi-dimensional array scalar works. understand.
but if have 2 n-dimensional arrays of different shapes, it's unclear me broadcasting rules are. documentation/tutorial explains that: in order broadcast, size of trailing axes both arrays in operation must either same size or 1 of them must one.
okay, assume trailing axis referring n in m x n array. so, means if attempt multiply 2 2d arrays (matrices) equal number of columns, should work? except doesn't...
>>> numpy import * >>> = array([[1,2],[3,4]]) >>> b = array([[2,3],[4,6],[6,9],[8,12]]) >>> print(a) [[1 2] [3 4]] >>> print(b) [[ 2 3] [ 4 6] [ 6 9] [ 8 12]] >>> >>> * b traceback (most recent call last): file "<stdin>", line 1, in <module> valueerror: shape mismatch: objects cannot broadcast single shape since both a , b have 2 columns, have thought work. so, i'm misunderstanding here term "trailing axis", , how applies n-dimensional arrays.
can explain why example doesn't work, , meant "trailing axis"?
well, meaning of trailing axes explained on linked documentation page. if have 2 arrays different dimensions number, 1 1x2x3 , other 2x3, compare trailing common dimensions, in case 2x3. if both arrays two-dimensional, corresponding sizes have either equal or 1 of them has 1. dimensions along array has size 1 called singular, , array can broadcasted along them.
in case have 2x2 , 4x2 , 4 != 2 , neither 4 or 2 equals 1, doesn't work.
Comments
Post a Comment