One-Hot 编码即独热编码,又称一位有效编码,其方法是使用N位状态寄存器来对N个状态进行编码,每一个状态都由他独立的寄存器位,而且在任意时候,其中只有一位有效。这样作的好处主要有:1. 解决了分类器很差处理属性数据的问题; 2. 在必定程度上也起到了扩充特征的做用。html
将离散型特征进行one-hot编码的做用,是为了让距离计算更合理,但若是特征是离散的,而且不用one-hot编码就能够很合理的计算出距离,那么就不必进行one-hot编码。离散特征进行one-hot编码,编码后的特征,其实每一维度的特征均可以看作是连续的特征。就能够跟对连续型特征的归一化方法同样,对每一维特征进行归一化。好比归一化到[-1,1]或归一化到均值为0,方差为1。算法
基于树的方法是不须要进行特征的归一化,例如随机森林,bagging 和 boosting等。基于参数的模型或基于距离的模型,都是要进行特征的归一化。Tree Model不太须要one-hot编码: 对于决策树来讲,one-hot的本质是增长树的深度。浏览器
one hot encoding的优势就是它的值只有0和1,不一样的类型存储在垂直的空间。缺点就是,当类别的数量不少时,特征空间会变得很是大。在这种状况下,通常能够用PCA来减小维度。并且one hot encoding+PCA这种组合在实际中也很是有用。总的来讲,要是one hot encoding的类别数目不太多,建议优先考虑。机器学习
# 简单来讲 LabelEncoder 是对不连续的数字或者文本进行编号 # sklearn.preprocessing.LabelEncoder():标准化标签,将标签值统一转换成range(标签值个数-1)范围内 from sklearn.preprocessing import LabelEncoder le = LabelEncoder() le.fit([1,5,67,100]) le.transform([1,1,100,67,5]) out: array([0, 0, 3, 2, 1], dtype=int64) #OneHotEncoder 用于将表示分类的数据扩维: from sklearn.preprocessing import OneHotEncode ohe = OneHotEncoder() ohe.fit([[1],[2],[3],[4]]) ohe.transform([[2],[3],[1],[4]]).toarray() out:array([[ 0., 1., 0., 0.], [ 0., 0., 1., 0.], [ 1., 0., 0., 0.], [ 0., 0., 0., 1.]])
- 源码:学习
Examples -------- Given a dataset with three features and four samples, we let the encoder find the maximum value per feature and transform the data to a binary one-hot encoding. >>> from sklearn.preprocessing import OneHotEncoder >>> enc = OneHotEncoder() >>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], \ [1, 0, 2]]) # doctest: +ELLIPSIS OneHotEncoder(categorical_features='all', dtype=<... 'numpy.float64'>, handle_unknown='error', n_values='auto', sparse=True) >>> enc.n_values_ array([2, 3, 4]) >>> enc.feature_indices_ array([0, 2, 5, 9]) >>> enc.transform([[0, 1, 1]]).toarray() array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.]])
Examples -------- `LabelEncoder` can be used to normalize labels. >>> from sklearn import preprocessing >>> le = preprocessing.LabelEncoder() >>> le.fit([1, 2, 2, 6]) LabelEncoder() >>> le.classes_ array([1, 2, 6]) >>> le.transform([1, 1, 2, 6]) #doctest: +ELLIPSIS array([0, 0, 1, 2]...) >>> le.inverse_transform([0, 0, 1, 2]) array([1, 1, 2, 6]) It can also be used to transform non-numerical labels (as long as they are hashable and comparable) to numerical labels. >>> le = preprocessing.LabelEncoder() >>> le.fit(["paris", "paris", "tokyo", "amsterdam"]) LabelEncoder() >>> list(le.classes_) ['amsterdam', 'paris', 'tokyo'] >>> le.transform(["tokyo", "tokyo", "paris"]) #doctest: +ELLIPSIS array([2, 2, 1]...) >>> list(le.inverse_transform([2, 2, 1])) ['tokyo', 'tokyo', 'paris']