版权声明:有错误还请斧正,感激不尽。 https://blog.csdn.net/Gentle_Guan/article/details/78698259
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