Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalizing variable using /= throws ufunc error

Tags:

python

kaggle

I'm slowly getting into some machine learning but in one exercise using computer vision on the kaggle cats and dogs dataset something happened that I don't quite understand.

when I then try to normalize the image values from the pickle it works when writing

X = X/255.0

but throws an error when I write

 X /=255.0

TypeError: ufunc 'true_divide' output (typecode 'd') could not be coerced to provided output parameter (typecode 'B') according to the casting rule ''same_kind''

As far as I understand x /= 255.0 should be the same as X = X/255.0 so where did I go wrong? Is a float vs int thing?

Explanations are much appreciated

like image 739
Nick Avatar asked Apr 15 '26 04:04

Nick


1 Answers

Take a look at Augmented Assignments from the python docs: https://docs.python.org/3/reference/simple_stmts.html#index-14

...

An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once.

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

Unlike normal assignments, augmented assignments evaluate the left-hand side before evaluating the right-hand side. For example, a[i] += f(x) first looks-up a[i], then it evaluates f(x) and performs the addition, and lastly, it writes the result back to a[i].

...

So you're partially correct, it's a float vs int thing, combined with whether the operation is performed in-place.

x/=255.0 doesn't work because the operation is performed in-place. Let's look at your error message: TypeError: ufunc 'true_divide' output (typecode 'd') could not be coerced to provided output parameter (typecode 'B') according to the casting rule ''same_kind''

Looking at the table below (https://docs.python.org/2/library/array.html), the type codes it's referencing are "int" and "float". x/=255.0 attempts to coerce an int (x) into a float (result of dividing x by 255.0). This is an unsafe cast, and you get your error message. type code to type conversion chart

But x=x/255.0 is fine, because operation isn't performed in-place. On the right hand side we get the result of x/255.0, and we simply assign this value to x, as you would assign any float to any variable.

like image 70
miara Avatar answered Apr 17 '26 23:04

miara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!