Skip to main content
 首页 » 编程设计

python之LabelEncoder() 不会存储参数

2025年05月04日21飞鱼

LabelEncoder 不会“记住”参数。当我用它拟合和转换数据然后询问参数时,我得到的只是{}。这使得不可能在新数据上重新使用编码器。

例子:

from sklearn.preprocessing import LabelEncoder 
 
encode = LabelEncoder() 
encode.fit_transform(['one', 'two', 'three']) 
print(encode.get_params()) 

不确定预期的格式,但我期待类似 {['one', 0], ['two', 1], ['three', 2]}

实际结果:{}

我在:

Darwin-16.7.0-x86_64-i386-64bit 
Python 3.6.1 |Anaconda 4.4.0 (x86_64)| (default, May 11 2017, 13:04:09)  
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] 
NumPy 1.12.1 
SciPy 0.19.0 
Scikit-Learn 0.18.1 

请您参考如下方法:

标签编码器将参数存储在classes_ 属性中。您可以获得转换这些类并创建字典的编码值。此编码器将处理具有相同标签的新数据,否则会引发 ValueError。对要编码的标签使用 transform 方法即可。

from sklearn import preprocessing 
 
encode = preprocessing.LabelEncoder() 
encode.fit_transform(['one', 'two', 'three']) 
keys = encode.classes_ 
values = encode.transform(encode.classes_) 
dictionary = dict(zip(keys, values)) 
print(dictionary) 

输出:{'three': 1, 'two': 2, 'one': 0}