数据预处理——独热码

模型原型

class sklearn.preprocessing.OneHotEncoder(n_values=’auto’,categorical_features=’all’,dtype=/, sparse=True,handle_unknown=’error’)
参数

  • n_values:指定每个属性的上界
    • ’auto’:自动从训练数据中推断属性值取值的上界
    • 一个整数:指定所有属性取值的上界
    • 一个整数的数组:依次指定每个属性的上界
  • categorical_features:指定哪些属性需要编码独热码
    • ’all’
    • 一个下标的数组:指定下标的属性将编码为独热码
    • 一个mask:对应为True的属性将编码为独热码
  • dtype:指定独热码编码的数值类型(默认为np.float)
  • sparse:指定结果是否为稀疏
  • handle_unknown:如果进行数据转换时,遇到了某个集合类型的属性,但是该属性未列入categorical_features时的情形,可以指定为
    • ’error’:抛出异常
    • ‘ignore’:忽略

属性

  • activefeatures:激活特征
  • featureindices:原始数据的第i个属性对应转换后数据的
  • (featureindices[i],featureindices[i+1])之间的属性
  • n_values:存放每个属性取值的种类

方法

  • fit(X,[,y]):训练OneHotEncoder
  • transform(X[,y,copy]):对原始数据执行独热码编码
  • fit_transform(X[,y])

示例

from sklearn.preprocessing import OneHotEncoder
X=[
    [1,2,3,4,5],
    [5,4,3,2,1],
    [3,3,3,3,3],
    [1,1,1,1,1]
]
print('before transform:\n',X)
encoder=OneHotEncoder(sparse=False)
encoder.fit(X)
print('active_features_:\n',encoder.active_features_)
print('feature_indices_:\n',encoder.feature_indices_)
print('n_values_:\n',encoder.n_values_)
print('after transform:\n',encoder.transform([[1,2,3,4,5]]))

猜你喜欢

转载自blog.csdn.net/weixin_39777626/article/details/79935926