'Normalizing difference between x_train /= 255.0 and x_train = x_train/255.0

I have some simple code, which loads the mnist data and normalizes the images.

    mnist = tf.keras.datasets.mnist

    (x_train, y_train),(x_test, y_test) = mnist.load_data()
    x_train = x_train/255.0
    x_test = x_test/255.0

The code above works, however, if I try to use the shorthand for division, I get an error:

    mnist = tf.keras.datasets.mnist

    (x_train, y_train),(x_test, y_test) = mnist.load_data()
    x_train /= 255.0
    x_test /= 255.0

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

By playing around, I found a fix to it, in that typecasting x_train to float32, would get rid of the error, but I only stumbled upon the fix by accident. I don't understand why the code below fixes the issue

    mnist = tf.keras.datasets.mnist

    (x_train, y_train),(x_test, y_test) = mnist.load_data(path=path)
    x_train = x_train.astype('float32')
    x_test = x_test.astype('float32')
    x_train /= 255.0
    x_test /= 255.0

Could someone explain what's happening here? Why do the two versions behave differently? Why's an explicit case required in the second instance but not the first?
I didn't have much luck finding this behaviour documented anywhere.

Edit: I'm not sure what additional 'debugging details' I'm required to provide, since I've basically provided the entire code, the results as well as the details which I did not understand. I've also received no comments explaining why the question was closed, and/or what additional information is expected here. I would like some constructive criticism so as to atleast be able to ask the question in a better manner, if the present form isn't satisfactory by itself.



Solution 1:[1]

If you don't want to change type to float32 you can do this:

mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
div = x_train / 255.0
x_train = div

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1