[Numpy-discussion] Silent Broadcasting considered harmful

josef.pktd at gmail.com josef.pktd at gmail.com
Sun Feb 8 19:52:13 EST 2015


On Sun, Feb 8, 2015 at 7:12 PM, Eric Firing <efiring at hawaii.edu> wrote:
> On 2015/02/08 12:43 PM, josef.pktd at gmail.com wrote:
>
>>
>> For me the main behavior I had to adjust to was loosing a dimension in
>> any reduce operation, mean, sum, ...
>>
>> if x is 2d
>> x - x.mean(1)
>> we loose a dimension, and it doesn't broadcast in the right direction
>
> Though you can use:
>
> x_demeaned = x - np.mean(x, axis=1, keepdims=True)


Yes, I thought afterwards it may not be a good example, because it
illustrates that numpy developers do respond with improving things
that are clumsier than in other languages/packages like the "matrix"
languages. (and I don't want broadcasting to change or even to cause
warnings.)

keepdims didn't exist when I started out with numpy and scipy 7 or so years ago.

Nevertheless, it's still often easier to write a function that assumes
a specific shape structure than coding for general nd arrays.

def my_function_that_works_over_rows(x, axis=0):

    if x.ndim == 1:
        x = x[:, None]
    if axis !=0:
        raise ValueError('only axis=0 is supported :(')

Josef



>
>>
>> x - x.mean(0)
>> perfect, no `repeat` needed, it just broadcasts the way we need.
>>
>> Josef
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion



More information about the NumPy-Discussion mailing list