微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 在多个程序中正确使用Scikit的LabelEncoder

我手头的基本任务是

a)读取一些制表符分隔的数据.

b)做一些基本的预处理

c)对于每个分类列,使用LabelEncoder创建映射.这有点像这样

mapper={}
#Converting Categorical Data
for x in categorical_list:
     mapper[x]=preprocessing.LabelEncoder()

for x in categorical_list:
     df[x]=mapper[x].fit_transform(df.__getattr__(x))

其中df是pandas数据帧,categorical_list是需要转换的列标题列表.

d)训练分类器并使用泡菜将其保存到磁盘

e)现在在另一个程序中,加载了保存的模型.

f)加载测试数据并执行相同的预处理.

g)LabelEncoder用于转换分类数据.

h)该模型用于预测.

现在问题是,步骤g)是否正常工作?

正如LabelEncoder的文档所说

It can also be used to transform non-numerical labels (as long as 
they are hashable and comparable) to numerical labels.

那么每个条目每次都会哈希到完全相同的值吗?

如果不是,有什么好办法可以解决这个问题.有没有办法重新编码编码器的映射?或者与LabelEncoder完全不同的方式?

解决方法:

根据LabelEncoder实现,当且仅当您在测试时使用具有完全相同的唯一值集的数据的LabelEncoders时,您描述的管道才能正常工作.

重新使用在火车期间获得的LabelEncoders有一种不太常见的方法. LabelEncoder只有一个属性,即classes_.你可以腌制它,然后恢复像

培养:

encoder = LabelEncoder()
encoder.fit(X)
numpy.save('classes.npy', encoder.classes_)

测试

encoder = LabelEncoder()
encoder.classes_ = numpy.load('classes.npy')
# Now you should be able to use encoder
# as you would do after `fit`

这似乎比使用相同数据重新调整它更有效.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐