Skip to content Skip to sidebar Skip to footer

Normalizing Variable Using /= Throws Ufunc Error

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

Solution 1:

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.

Post a Comment for "Normalizing Variable Using /= Throws Ufunc Error"