one-hot编码sklearn实现详解

one-hot编码是特征处理中的必备,在项目中我们是这么应用的,

# sklearn用法
from sklearn import preprocessing

enc = OneHotEncoder(sparse = False)
ans = enc.fit_transform([[0, 0, 3],
                         [1, 1, 0],
                         [0, 2, 1],
                         [1, 0, 2]])

解析的原理可参考:link
在sklearn中onehot编码的核心逻辑在_fit_transform方法中

def _fit_transform(self, X):

 #获取入参的行数和列数
n_samples, n_features = X.shape
#获取每列的最大值加1"""
 n_values = np.max(X, axis=0) + 1
#cumsum累加,用于之后构建稀疏矩阵"""
indices = np.cumsum(n_values)
#构建稀疏矩阵的列值
column_indices = (X + indices[:-1]).ravel()
#构建【0 0 0 1 1 1 2 2 2 3 3 3】
row_indices = np.repeat(np.arange(n_samples, dtype=np.int32),
                        n_features)
#one-hot编码后要么是0 要么是1  先构建全1的矩阵
data = np.ones(n_samples * n_features)
#Coordinate Format (COO)稀疏矩阵的存储格式
out = sparse.coo_matrix((data, (row_indices, column_indices)),
                        shape=(n_samples, indices[-1]),
                        dtype=self.dtype).tocsr()

举例说明,比如最开始的例子
我们先来看第一个特征,即第一列 [0,1,0,1],也就是说它有两个取值 0 或者 1,那么 one-hot 就会使用两位来表示这个特征,[1,0] 表示 0, [0,1] 表示 1,在上例输出结果中的前两位 [1,0…] 也就是表示该特征为 0
第二个特征,第二列 [0,1,2,0],它有三种值,那么 one-hot 就会使用三位来表示这个特征,[1,0,0] 表示 0, [0,1,0] 表示 1,[0,0,1] 表示 2,在上例输出结果中的第三位到第六位 […0,1,0,0…] 也就是表示该特征为 1
第二个特征,第三列 [3,0,1,2],它有四种值,那么 one-hot 就会使用四位来表示这个特征,[1,0,0,0] 表示 0, [0,1,0,0] 表示 1,[0,0,1,0] 表示 2,[0,0,0,1] 表示 3,在上例输出结果中的最后四位 […0,0,0,1] 也就是表示该特征为 3

在_fit_transform方法中是如何实现的呢,如下图

《one-hot编码sklearn实现详解》

之后就是将采用了Coordinate Format (COO)稀疏矩阵的存储格式的矩阵还原出来,
通过这样one-hot就完成了

    原文作者:HelloData
    原文地址: https://segmentfault.com/a/1190000019458973
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞