One hot 编码 - xd21303/Notebook GitHub Wiki

1、sklearn

import numpy as np
from sklearn.preprocessing import OneHotEncoder

c = np.array([1, 1, 0, 2])
onehot_encoder = OneHotEncoder(sparse=False)  # 必须False
onehot_encoded = onehot_encoder.fit_transform(c.reshape(len(c), 1))
print(onehot_encoded)
[[0. 1. 0.]
 [0. 1. 0.]
 [1. 0. 0.]
 [0. 0. 1.]]

2、keras

from keras.utils import to_categorical

encoded = to_categorical(c)
print(encoded)

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

3 、pandas

c = np.array([1, 1, 0, 2])
c = pd.get_dummies(c)
print(np.array(c))

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

注意,这个是int型,前面两个都是float型