ユニヒートコーディングを実現する方法

1757 ワード

方法一、Scikit-LiarnでOne-Hot Encodingを実現する
 
scikit-learnのLabelBinarizer関数(二値化)は、ターゲット(labels)を単熱符号化ベクトルに変換するのに便利です.以下を参照してください.
import numpy as np
from sklearn import preprocessing

# Example labels   labels
labels = np.array([1,5,3,2,1,4,2,1,3])

# Create the encoder  
lb = preprocessing.LabelBinarizer()

# Here the encoder finds the classes and assigns one-hot vectors 
#   one-hot  
lb.fit(labels)

# And finally, transform the labels into one-hot encoded vectors
#  (lables) (one-hot encoded) 
lb.transform(labels)
array([[1, 0, 0, 0, 0],
       [0, 0, 0, 0, 1],
       [0, 0, 1, 0, 0],
       [0, 1, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [0, 0, 1, 0, 0]])

方法二、Sklearnを使う.PreprocessingのOneHotEncoder
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder()
encoder.fit(np.arange(6).reshape(-1, 1))
def one_hot_encode(x):
    return encoder.transform(np.array(x).reshape(-1, 1)).toarray()
labels = [1,5,3,2,1,4,2,1,3]
a= one_hot_encode(labels)
print(a)
[[0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 1.]
 [0. 0. 0. 1. 0. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0.]]

元のラベルが0からでない場合、
方法3、numpyを用いてone-hotを実現する:
import numpy as np

_y = [1,4,3,2,6,5]
_y = np.asarray(_y,dtype=int)
b = np.zeros((_y.size, _y.max()+1))
b[np.arange(_y.size),_y] = 1
print(b)

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