最简单的onehot函数

Published on Aug. 22, 2023, 12:06 p.m.

2021-06-17 记事

最简单的 #onehot 函数

<h1>方案1</h1>
def one_hot(a, num_classes):
    return np.squeeze(np.eye(num_classes)[a.reshape(-1)])

one_hot(np.array([0,1]),2)
<h1>sk方案 #sklearn</h1>
import sklearn.preprocessing
a = [1,0,3]
label_binarizer = sklearn.preprocessing.LabelBinarizer()
label_binarizer.fit(range(max(a)+1))
b = label_binarizer.transform(a)
print('{0}'.format(b))


https://stackoverflow.com/questions/29831489/convert-array-of-indices-to-1-hot-encoded-numpy-array

用Python将list中的string转换为int


results = list(map(int, results))