繁体   English   中英

如何预处理新实例进行分类,以使特征编码与使用Scikit-learn的模型相同?

[英]How to pre-process new instances for classification, so that the feature encoding is the same as the model with Scikit-learn?

我正在使用对数据进行多分类的模型来创建模型,该模型具有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)

当我要预测新实例时,我需要转换新实例的数据,以使特征与模型中的特征匹配相同的编码。 有没有简单的方法可以实现这一目标?

另外,如果我想保留模型并检索它,那么是否存在一种简单的保存编码格式的方法,以便使用它来转换检索到的模型上的新实例?

当我要预测新实例时,我需要转换新实例的数据,以使特征与模型中的特征匹配相同的编码。 有没有简单的方法可以实现这一目标?

如果不能完全肯定你是如何分类的“管道”的工作,但你可以用你适合LabelEncoder方法上的一些新的数据- le将改变新的数据,所提供的标签在训练集中存在哪些。

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']

另外,如果我想保留模型并检索它,那么是否存在一种简单的保存编码格式的方法,以便使用它来转换检索到的模型上的新实例?

您可以像这样保存模型/模型的一部分:

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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM