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

Ric*_*ray 5 python machine-learning 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)
Run Code Online (Sandbox Code Playgroud)

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

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

AGS*_*AGS 5

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

如果不完全确定您的分类"管道"如何运作,但您可以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']
Run Code Online (Sandbox Code Playgroud)

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

您可以保存模型的模型/部件,如下所示:

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])
Run Code Online (Sandbox Code Playgroud)