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

LabelEncoder

直接上代码

# coding:utf-8

from sklearn import preprocessing

label_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-8

from sklearn import preprocessing

label_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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值