what does np.eye(n)[nparray] mean? [duplicate]

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?

2

1 Answer

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 
3

You Might Also Like