当我想要预测一个新实例时,我需要转换新实例的数据,以便特征与模型中的特征匹配相同的编码。有没有一种简单的方法可以实现这一目标?
如果不完全确定您的分类“管道”如何运作,但您可以使用适合您的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])