Convert vector of integer values to one hot representation

When converting a vector of integer values to a one hot representation, such as in a classification problem, In python, you can use numpy to convert as follows.

python


import numpy as np

target_vector = [0,2,1,3,4]               #A vector representation of the classification of integer values
n_labels = len(np.unique(target_vector))  #Number of classification classes= 5
np.eye(n_labels)[target_vector]           #Convert to one hot expression

One obtained by running-hot expression


array([[ 1.,  0.,  0.,  0.,  0.],   # 0
       [ 0.,  0.,  1.,  0.,  0.],   # 2
       [ 0.,  1.,  0.,  0.,  0.],   # 1
       [ 0.,  0.,  0.,  1.,  0.],   # 3
       [ 0.,  0.,  0.,  0.,  1.]])  # 4

reference

https://www.reddit.com/r/MachineLearning/comments/31fk7i/converting_target_indices_to_onehotvector/

Recommended Posts

Convert vector of integer values to one hot representation
Trivia: String representation of constant values
How to convert 0.5 to 1056964608 in one shot
Vector representation of simple words: word2vec, GloVe
Convert data with shape (number of data, 1) to (number of data,) with numpy.
Convert Windows epoch values to date with python
Convert a multidimensional list (array) to one dimension
Convert multiple jpg files to one PDF file