1. 程式人生 > >softmax 輸出結果轉換成標籤,argmax轉one

softmax 輸出結果轉換成標籤,argmax轉one

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]] #-----------