from sklearn import preprocessing
import numpy as np
enc = preprocessing.OneHotEncoder(categories='auto')
# 训练onehot编码,指定标签
enc.fit([[1],[2],[3]])
# 将标签转换成 onehot编码
result =enc.transform([[1],[3],[2]])
print(result.toarray())
#--------
# [[1. 0. 0.]
# [0. 0. 1.]
# [0. 1. 0.]]
#--------
# sortmax 结果转 onehot
a = [[0.2,0.3,0.5],
[0.7,0.3,0.5],
[0.7,0.9,0.5]
]
# sortmax 结果转 onehot
def props_to_onehot(props):
if isinstance(props, list):
props = np.array(props)
a = np.argmax(props, axis=1)
b = np.zeros((len(a), props.shape[1]))
b[np.arange(len(a)), a] = 1
return b
print(props_to_onehot(a))
#----------
# [[0. 0. 1.]
# [1. 0. 0.]
# [0. 1. 0.]]
#---------
# 将onehot转换成标签
print("----softmax -> label ----")
print(enc.inverse_transform(props_to_onehot(a)))
#----------
# [[3]
# [1]
# [2]]
#-----------
softmax 输出结果转换成标签,argmax转one-hot
猜你喜欢
转载自blog.csdn.net/afgasdg/article/details/84346931
今日推荐
周排行