- one-hot编码
One-Hot 编码是分类变量作为二进制向量的表示。首先要求将分类值映射到整数值。然后,每个整数值被表示为二进制向量。
OneHot 编码要求每个类别之间相互独立,如果之间存在某种连续型的关系。显然会影响特征相关性。
编码转换:
pd.get_dummies(df)
OneHotEncoder()
from sklearn.preprocessing import OneHotEncoder
#将值变为数组形式,这样才能进行处理
values = df['class'].values
# 注意 OneHotEncoder(sparse=False),不然返回的就是索引值的形式
onehot_encoder = OneHotEncoder(sparse=False)
values = values.reshape(len(values), 1) #这一步很有必要,不然会报错
onehot_encoded = onehot_encoder.fit_transform(values)
print(onehot_encoded)
#把onehot编码换成lable型编码
int_endode = np.argmax(onehot_encoded, axis=1)
print(int_endode)
>>>[0 1 0 2]
- LabelEncoder编码
不将类别变量作为二进制表达,将类别型进行排序并赋值。
编码转换:
from sklearn.preprocessing import LabelEncoder
df['class'] = LabelEncoder().fit_transform(df['class'])
#把lable型编码换成onehot型
import keras
encoded = keras.utils.to_categorical(df['class'])
print(encoded)