将标签转为one-hot编码
我定义为一个函数,返回为布尔值,需要类型转换
def one_hot(label, N=None): # 对标签进行独热编码
label = np.asarray(label) # np.asarray() 对于传入list为深拷贝, 传入array为浅拷贝,即改变传入的值,拷贝的数据会跟着变化
if N is None:
N = ind.max() + 1
return np.arange(N) == np.repeat(ind, N, axis=1) # np.repeat 对ind在横轴(axis=1)重复N次
例如:
a = [[0],
[1],
[2]]
b = np.repeat(a,3,axis=1)
print(b)
print(np.arange(3) == np.repeat(a,3,axis=1))
print((np.arange(3) == np.repeat(a,3,axis=1)).astype(int))
#output
[[0 0 0]
[1 1 1]
[2 2 2]]
[[ True False False]
[False True False]
[False False True]]
[[1 0 0]
[0 1 0]
[0 0 1]]