類別變數轉換成one hot標籤的方法

2022-06-23 21:15:10 字數 1220 閱讀 9435

one_hot 類別變數中n個不同類別轉換為n個變數

dummy variable 在某一設定的參考準則下,對n個不同的類別,轉換為n-1個變數

pandas 將標籤轉化為獨熱編碼

pd.get_dummies(df_nmf['cluster']).head(20)
tensorflow 將標籤轉化為獨熱編碼

from keras.utils import to_categorical

encoded=to_categorical(df_nmf['cluster'])

機器學習包的獨熱編碼使用

from sklearn.preprocessing import labelencoder

from sklearn.preprocessing import onehotencoder

data = ['cold', 'cold', 'warm', 'cold', 'hot', 'hot', 'warm', 'cold', 'warm', 'hot']

values = np.array(data)

print(values)

# integer encode

label_encoder = labelencoder()

integer_encoded = label_encoder.fit_transform(values)

print(integer_encoded)

onehot_encoder = onehotencoder(sparse=false)

integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)

onehot_encoded = onehot_encoder.fit_transform(integer_encoded)

print(onehot_encoded)

# invert first example

inverted = label_encoder.inverse_transform([np.argmax(onehot_encoded[0, :])])

print(inverted)