9

I am going thru some code

y_enc = np.eye(21)[label]

where label is ndarray of shape (224, 224) y_enc is ndarray of shape (224, 224, 21)

Even with the shapes printed, I am having trouble understanding this statement. np.eye is supposed to generate a diagonal matrix of dimension 21 x 21. what does it mean to have [label] following it?

bhomass
  • 3,414
  • 8
  • 45
  • 75
  • please provide reference to that other question. – bhomass Sep 10 '17 at 05:32
  • 1
    This is indexing a NumPy array using another array as described here: https://docs.scipy.org/doc/numpy/user/basics.indexing.html#index-arrays . The first array is the Identity matrix of dimension 21 x 21. The second array selects the one-hot row corresponding to each label. – zardosht Oct 11 '18 at 10:26

1 Answers1

11

From Documentation. numpy.eye

Return a 2-D array with ones on the diagonal and zeros elsewhere.

Example:

>>np.eye(3)
array([[ 1.,  0.,  0.],
   [ 0.,  1.,  0.],
   [ 0.,  0.,  1.]])
>>> np.eye(3)[1]
array([ 0.,  1.,  0.])

[label] is array element indexing. So with only one element in it, it returns given number of rows element as array.

>>> np.eye(3)[1]
array([ 0.,  1.,  0.])
>>> np.eye(3)[2]
array([ 0.,  0.,  1.])

as it is 2d array you can also access the specific element by giving 2 index number on [row_index, column_index]

>>> np.eye(3)[2,1]
0.0
>>> np.eye(3)[2,2]
1.0
>>> np.eye(3)[1,1]
1.0
R.A.Munna
  • 1,699
  • 1
  • 15
  • 29
  • don't think you quite nailed it. label is itself an adarray. not just a list of indices. Also, the indices of label way exceeds 21. As I said, y_enc ends up with a shape of (224, 224, 21) – bhomass Sep 10 '17 at 05:34
  • ok. than how you explain about this error. `>>> a=np.eye(21)[224,224,21] Traceback (most recent call last): File "", line 1, in IndexError: too many indices for array ` – R.A.Munna Sep 10 '17 at 15:53
  • You didn't answer the question, bro. Try this and answer how does this command generates the result. `a = np.array([[2,0],[1,2]]);np.eye(3)[a]`. – Diansheng Jul 02 '18 at 09:50