基于sklearn的序列处理 : LabelEncoder 与 OneHotEncoder

来源:互联网 发布:淘宝商城阿依莲品牌店 编辑:程序博客网 时间:2024/06/05 22:35

LabelEncoder

直接上代码

# coding:utf-8from sklearn import preprocessinglabel_encode = preprocessing.LabelEncoder()  # 建立模型label_encode.fit([['-1'], [13], [456],['a']])# label_encode.transform([1]) # 错误 不可无中生有print label_encode.transform([[13], [456], ['a']])  # 训练模型 数据转换"""[1 2 3]"""print label_encode.inverse_transform(2)  # 数据逆向转换"""456"""

OneHotEncoder

# coding:utf-8from sklearn import preprocessinglabel_onehot = preprocessing.OneHotEncoder()# label_onehot.fit([[-1],[13],[456]]) # 错误 不可出负数label_onehot.fit([[1], [13], [456]])print label_onehot.transform([[1], [13], [12]]).toarray() # 无中生有 全为0 (类似于噪声?"""[[ 1.  0.  0.] [ 0.  1.  0.] [ 0.  0.  0.]]"""print label_onehot.transform([[1], [13], [456]]).toarray()"""[[ 1.  0.  0.] [ 0.  1.  0.] [ 0.  0.  1.]]"""print type(label_onehot.transform([[1], [13], [456]])),"\n",label_onehot.transform([[1], [13], [456]])"""<class 'scipy.sparse.csr.csr_matrix'>   (0, 0)    1.0   (1, 1)    1.0  (2, 2)    1.0 这里的输出为 坐标 填充数字 比对着上一个输出看"""

比较

两个差别都在代码里了
对于非负数类型编码 利用onehotEncode
对于字符以及混合类型编码 利用labelEncode

阅读全文
1 0