Search code examples
pythonmachine-learningkerasone-hot-encoding

One Hot encoding for [-1,1] labels


I have binary labels for a classification problem as -1 and 1. How can I perform one hot encoding for this?

Used following but it only returns [0,1] always.

Y_TRAIN_One_hot = keras.utils.np_utils.to_categorical(Y_TRAIN, 2)


Solution

  • The problem here is that the to_categorical function creates a one hot encoding of integers 0 to n, not of arbitrary labels.

    What you are looking for is probably:

    Y_TRAIN = [-1, 1, 1, -1]
    one_hot = np.unique(Y_TRAIN, return_inverse=True)[1]
    # array([0, 1, 1, 0])