deep-learning-book icon indicating copy to clipboard operation
deep-learning-book copied to clipboard

need more elaborative explanation for indexed array used as rvalue or lvalue

Open guihao-liang opened this issue 4 years ago • 2 comments

I'm in the process of reading the book for python machine learning (PML). And I followed the PML to learn more about numpy through the Appendix F of this book.

For section F.6, it covers fancy indexing will always return a copy of ndarray. But in section F.7 it shows you can do the assignment to fancy indexed array and the result will be written to the original array. I'm confused.

>>> ary[mask] = 1
>>> ary[~mask] = 0
>>> ary array([0, 0, 1, 1])

That's not consistent with fancy indexing should return a copy instead of a view of the array. If arr[mask] returns a copy, then the following assignment will assign results to the copy instead of the source.

After I did some research, I found the post here explains everything.

When you do c = a[b], a.__get_item__ is called with b as its only argument, and whatever gets returned is assigned to c.

When you doa[b] = c, a.__setitem__ is called with b and c as arguments and whatever gets returned is silently discarded.

I hope @rasbt can elaborately mention the python implementation difference of indexed array being used as rvalue and lvalue.

guihao-liang avatar Nov 14 '19 01:11 guihao-liang

Thanks for highlighting this unintuitive behavior. It's definitely worth explaining with regard to left- and right-value.

E.g., when we have

import numpy as np

a = np.array([1, 2, 3, 4, 5])
a[[1, 3]] = 99

a

it returns

array([ 1, 99,  3, 99,  5])

but if we have the fancy indexing on the right, it creates a copy:

a = np.array([1, 2, 3, 4, 5])
b = a[[1, 3]] 
b += 99

a
array([1, 2, 3, 4, 5])

Will leave this issue open to remind myself to update the document in the upcoming days/weeks.

rasbt avatar Nov 14 '19 02:11 rasbt

Perfect! Thanks!

guihao-liang avatar Nov 14 '19 04:11 guihao-liang