[Python] How to one-hot encode a vector with arbitrary number of unique values?

Discussão em 'Python' iniciado por Stack, Abril 27, 2025.

  1. Stack

    Stack Membro Participativo

    Given a output vector y that can have any number of discrete values, say from the set {1, 2, 3, 4}. Let the vector have this instance:

    y = [1, 1, 2, 4, 2, 3, 1]


    Is there a numpy-tonic library way of generating a one-hot encoded representation of this vector? I.e. such that

    y_enc =
    y1 y2 y3 y4
    1 0 0 0
    1 0 0 0
    0 1 0 0
    0 0 0 1
    0 1 0 0
    0 0 1 0
    1 0 0 0


    For the case {0, 1} i have a small example but I cant see this going in the right direction:

    >>> k
    array([[0.],
    [0.],
    [0.],
    [0.],
    [1.]])
    >>> z = np.zeros((5,2))
    >>> z
    array([[0., 0.],
    [0., 0.],
    [0., 0.],
    [0., 0.],
    [0., 0.]])
    >>> for i,ki in enumerate(k):
    ... if (ki == 0):
    ... z[0] += 1
    ... if (ki == 1):
    ... z[1] += 1
    ...
    >>> z
    array([[1., 0.],
    [1., 0.],
    [1., 0.],
    [1., 0.],
    [0., 1.]])
    >>>

    Continue reading...

Compartilhe esta Página