2

pickle用来存储我的机器学习模型,如下所示:

import pickle
with open('mymodel','wb') as f:
        pickle.dump(gbc,f)

现在,我想在另一台计算机上测试这个模型。所以我正在恢复我的模型并像这样传递数据:

with open('mymodel', 'rb') as fin:
       clf = pickle.load(fin)

X_new_preds = clf.predict(dataset)

但我收到此错误:

ValueError: Number of features of the model must match the input. Model 
n_features is 20 and input n_features is 19

从上面我可以理解,在训练时我做了很多预处理,比如在数据中我有分类特征,然后我删除了多重共线性列等等。所以在我的期末考试中,我DataFrame有 20 个功能(请记住,这是经过大量预处理之后的)。

所以,我想知道,我如何使用pickle. 或者我怎样才能恢复我的模型并可以在新数据中使用。

编辑:

我也试过这个

#Using Joblib
from sklearn.externals import joblib
filename = 'finalized_model.sav'
joblib.dump(gbc, filename)
loaded_model = joblib.load(filename)
X_new_preds = clf.predict(dataset)

但得到相同的值错误。

4

1 回答 1

0

问题不在于您的模型持久性和加载。问题是您正在对数据进行一些预处理,而您没有保存这些数据。

你有两个选择:

  1. 有一份说明模型接受什么的文档,用户/客户就会知道该给模型什么。
  2. 您完成了一些预处理,您可以使用Pipeline.

这是一个管道示例,取自文档

>>> from sklearn import svm
>>> from sklearn.datasets import samples_generator
>>> from sklearn.feature_selection import SelectKBest
>>> from sklearn.feature_selection import f_regression
>>> from sklearn.pipeline import Pipeline
>>> # generate some data to play with
>>> X, y = samples_generator.make_classification(
...     n_informative=5, n_redundant=0, random_state=42)
>>> # ANOVA SVM-C
>>> anova_filter = SelectKBest(f_regression, k=5)
>>> clf = svm.SVC(kernel='linear')
>>> anova_svm = Pipeline([('anova', anova_filter), ('svc', clf)])
>>> # You can set the parameters using the names issued
>>> # For instance, fit using a k of 10 in the SelectKBest
>>> # and a parameter 'C' of the svm
>>> anova_svm.set_params(anova__k=10, svc__C=.1).fit(X, y)
...                      
Pipeline(memory=None,
         steps=[('anova', SelectKBest(...)),
                ('svc', SVC(...))])
>>> prediction = anova_svm.predict(X)
>>> anova_svm.score(X, y)                        
0.829...
>>> # getting the selected features chosen by anova_filter
>>> anova_svm.named_steps['anova'].get_support()
... 
array([False, False,  True,  True, False, False, True,  True, False,
       True,  False,  True,  True, False, True,  False, True, True,
       False, False], dtype=bool)
>>> # Another way to get selected features chosen by anova_filter
>>> anova_svm.named_steps.anova.get_support()
... 
array([False, False,  True,  True, False, False, True,  True, False,
       True,  False,  True,  True, False, True,  False, True, True,
       False, False], dtype=bool)

持久化整个管道后,您可以要求客户端以原始形式向模型(管道)提供数据。您还可以开发一些自定义转换并将它们添加到管道中,只要您遵循所需的 API。

于 2018-04-06T12:45:26.907 回答