如何对新实例进行分类预处理,使特征编码与Scikit-learn的模型一致?

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

我正在使用 multi-class class数据化创建模型,它有 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?

如果不完全确定你的分类 'pipeline' 是如何运作的,但你可以只对一些新数据使用你的拟合 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']

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?

您可以像这样保存 models/parts 个模型:

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