how would the following code work?
k = np.array([[ 0., 0.07142857, 0.14285714],
[ 0.21428571, 0.28571429, 0.35714286],
[ 0.42857143, 0.5, 0.57142857],
[ 0.64285714, 0.71428571, 0.78571429],
[ 0.85714286, 0.92857143, 1. ]])
y = np.array([[0, 3, 1, 2],
[2, 1, 0, 3]])
b = k[y]
The shapes are:
k shape: (5, 3)
y shape: (2, 4)
b shape: (2, 4, 3)
Why would a numpy matrix accept another matrix as its index and how would k find the correct output? Why is a tensor produced instead?
The output of b is
[[[ 0. 0.07142857 0.14285714]
[ 0.64285714 0.71428571 0.78571429]
[ 0.21428571 0.28571429 0.35714286]
[ 0.42857143 0.5 0.57142857]]
[[ 0.42857143 0.5 0.57142857]
[ 0.21428571 0.28571429 0.35714286]
[ 0. 0.07142857 0.14285714]
[ 0.64285714 0.71428571 0.78571429]]]
This is called integer array indexing.
Integer array indexing allows selection of arbitrary items in the array based on their N-dimensional index. Each integer array represents a number of indexes into that dimension.
Example -
x = array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
rows = np.array([[0, 0],
[3, 3]], dtype=np.intp)
columns = np.array([[0, 2],
[0, 2]], dtype=np.intp)
x[rows, columns]
Output -
array([[ 0, 2],
[ 9, 11]])
In this case as you can see we are selecting the corner elements by giving the "coordinates" of the elements. And if you try just giving a single 2d matrix it'll just evaluate it like -
x[rows]
Output -
array([[[ 0, 1, 2],
[ 0, 1, 2]],
[[ 9, 10, 11],
[ 9, 10, 11]]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With