python – 如何预处理新实例以进行分类,以便特征编码与Scikit-learn的模型相同?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 如何预处理新实例以进行分类,以便特征编码与Scikit-learn的模型相同?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2322字,纯文字阅读大概需要4分钟。
内容图文
![python – 如何预处理新实例以进行分类,以便特征编码与Scikit-learn的模型相同?](/upload/InfoBanner/zyjiaocheng/824/c133920d92f743b785b70b9e0467bc93.jpg)
我正在使用数据的多类分类创建模型,它具有6个功能.我使用LabelEncoder使用下面的代码预处理数据.
#Encodes the data for each column.
def pre_process_data(self):
self.encode_column('feedback_rating')
self.encode_column('location')
self.encode_column('condition_id')
self.encode_column('auction_length')
self.encode_column('model')
self.encode_column('gb')
#Gets the column using the column name, transforms the column data and resets
#the column
def encode_column(self, name):
le = preprocessing.LabelEncoder()
current_column = np.array(self.X_df[name]).tolist()
self.X_df[name] = le.fit_transform(current_column)
当我想预测一个新实例时,我需要转换新实例的数据,以使这些特征与模型中的特征匹配相同的编码.有没有一种简单的方法来实现这一目标?
此外,如果我想保留模型并检索它,那么是否有一种简单的方法来保存编码格式,以便使用它来转换检索到的模型上的新实例?
解决方法:
When I want to predict a new instance I need to transform the data of the new instance so that the features match the same encoding as those in the model. Is there a simple way of achieving this?
如果不完全确定您的分类“管道”如何运作,但您可以在一些新数据上使用您的拟合LabelEncoder方法 – 如果标签是训练集中存在的标签,则会转换新数据.
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
# training data
train_x = [0,1,2,6,'true','false']
le.fit_transform(train_x)
# array([0, 1, 1, 2, 4, 3])
# transform some new data
new_x = [0,0,0,2,2,2,'false']
le.transform(new_x)
# array([0, 0, 0, 1, 1, 1, 3])
# transform data with a new feature
bad_x = [0,2,6,'new_word']
le.transform(bad_x)
# ValueError: y contains new labels: ['0' 'new_word']
Also if I want to persist the model and retrieve it, then is there a simple way of saving the encoding format, in order to use it to transform new instances on the retrieved model?
您可以保存模型的模型/部件,如下所示:
import cPickle as pickle
from sklearn.externals import joblib
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
train_x = [0,1,2,6,'true','false']
le.fit_transform(train_x)
# Save your encoding
joblib.dump(le, '/path/to/save/model')
# OR
pickle.dump(le, open( '/path/to/model', "wb" ) )
# Load those encodings
le = joblib.load('/path/to/save/model')
# OR
le = pickle.load( open( '/path/to/model', "rb" ) )
# Then use as normal
new_x = [0,0,0,2,2,2,'false']
le.transform(new_x)
# array([0, 0, 0, 1, 1, 1, 3])
内容总结
以上是互联网集市为您收集整理的python – 如何预处理新实例以进行分类,以便特征编码与Scikit-learn的模型相同?全部内容,希望文章能够帮你解决python – 如何预处理新实例以进行分类,以便特征编码与Scikit-learn的模型相同?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。