Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: Using a matrix as indices for another matrix to create a tensor?

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]]]
like image 416
kwotsin Avatar asked Sep 03 '25 06:09

kwotsin


1 Answers

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]]])
like image 72
hashcode55 Avatar answered Sep 04 '25 21:09

hashcode55