-1

I am following the Deep Learning course on Coursera.

I found out that when making a matrix division, like the following:

x_norm = np.linalg.norm(x, axis=1, keepdims=True)
x = x / x_norm

It works fine. But when I was the statement instead:

x /= x_norm

It does not work, why is that?

  • Does this answer your question? [Can't use /= on numpy array](https://stackoverflow.com/questions/48948308/cant-use-on-numpy-array) – monk May 01 '22 at 00:28
  • 2
    What do you mean by "does not work'? Is there an error, or just a unexpected value? Does the error mention `broadcasting`? (I get a `casting error` message.) – hpaulj May 01 '22 at 00:28
  • @hpaulj There is an error: ```TypeError: ufunc 'true_divide' output (typecode 'd') could not be coerced to provided output parameter (typecode 'l') according to the casting rule ''same_kind''.``` – Dhai Eddine Zebbiche May 01 '22 at 00:30
  • Does this answer your question? [Why can I not use inplace division operator when dividing numpy vector by numpy norm](https://stackoverflow.com/questions/60548336/why-can-i-not-use-inplace-division-operator-when-dividing-numpy-vector-by-numpy) – Michael Szczesny May 01 '22 at 08:45

1 Answers1

1

If x is an integer dtype array, you'll get this casting error:

In [1]: x = np.arange(1,4)
In [2]: x /= 10
Traceback (most recent call last):
  Input In [2] in <cell line: 1>
    x /= 10
UFuncTypeError: Cannot cast ufunc 'true_divide' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'

No such problems if the array if floats:

In [3]: y = x.astype(float)
In [4]: y /= 10
In [5]: y
Out[5]: array([0.1, 0.2, 0.3])

*= 0.1 would also raise a casting error. Anything that tries to put a float in an int array. Assignments like x[:] = 1.1 silently cast the floats to integer - that's a more frequent cause of puzzlement.

hpaulj
  • 221,503
  • 14
  • 230
  • 353