python中如何使用numpy将label转为one-hot
首先生成identity matrix,可以通过np.eye(num_classes)或np.identity(num_classes)
之后将label作为行数的索引放在后面的方括号中即可
import numpy as np
label = [1, 0, 3, 2, 3]
label_onehot = np.eye(4, dtype=np.uint8)[label]
label_onehot
这里label用list或array形式 label = np.array([1, 0, 3, 2, 3]) 都可以,不影响。
运行结果:
array([[0, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 1]], dtype=uint8)