write GRADED FUNCTION: one_hot

Question:

How I can to get this result

[[ 0. 0. 0. 0. 0.],
 [ 1. 0. 0. 0. 0.],
 [ 0. 1. 0. 0. 0.],
 [ 0. 0. 1. 0. 1.],
 [ 0. 0. 0. 1. 0.]]

because my variant is incorrect

[[[0. 1. 0. 0. 0.],
  [0. 0. 1. 0. 0.],
  [0. 0. 0. 1. 0.],
  [0. 0. 0. 0. 1.],
  [0. 0. 0. 1. 0.]]]
def one_hot(Y, n_classes):
    """
    Arguments:
    Y -- array of input labels of shape (1, n_samples)
    n_classes -- number of classes

    Returns:
    onehot, a matrix of labels by samples. For each column, the ith index will be 
        "hot", or 1, to represent that index being the label; shape - (n_classes, n_samples)
    """
    x = np.eye(n_classes)[Y]
    return x

print(one_hot(np.asarray([1, 2, 3, 4, 3]).reshape(1, 5), 5))

Answers:

You need to apply the indices to the columns, not to the rows. You can do it by using [:, Y] instead of [Y]

def one_hot(Y, n_classes):
    x = np.eye(n_classes)[:, Y]
    return x

Output

[[[0. 0. 0. 0. 0.]]

 [[1. 0. 0. 0. 0.]]

 [[0. 1. 0. 0. 0.]]

 [[0. 0. 1. 0. 1.]]

 [[0. 0. 0. 1. 0.]]]
Answered By: Guy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.