保存的模型(随机森林)不能用作“新拟合”模型-类别变量存在问题

时间:2020-05-26 09:44:08

标签: python scikit-learn label-encoding

我在scikit-learn(随机森林)中建立了一个模型并将其保存。然后,我再次加载了该模型,并尝试将其应用于用于训练的相同数据集。我收到错误消息

“无法将字符串转换为浮点数”

因为我有几个类别变量。但是在保存模型之前,我能够将此模型毫无错误地应用于此数据集。问题似乎是在保存模型时未保存有关这两个类别变量的信息。事实上,我对这些变量使用了Labelencoder。有什么方法可以保存有关这些类别变量的信息,以使保存的模型与“新拟合”模型一样有效? 预先感谢!

1 个答案:

答案 0 :(得分:3)

这是 pipeline 的典型用例。

将您的工作流创建为单个管道,然后保存管道。

在加载管道时,您无需编码就可以直接获得关于新数据的预测。

此外,labelEncoder也不意味着转换输入数据。顾名思义,它用于目标变量。

如果您需要将分类变量转换为序数,请使用OrdinalEncoder

玩具示例:

from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import OrdinalEncoder
from sklearn.compose import make_column_transformer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline

X = [[1, 'orange', 'yes'], [1, 'apple', 'yes'],
     [-1, 'orange', 'no'], [-1, 'apple', 'no']]
y = [[1], [1], [0], [0]]

X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    random_state=42)
pipe = Pipeline(
    [('encoder', make_column_transformer((OrdinalEncoder(), [1, 2]), 
                                         remainder='passthrough')),
    # applies OrdinalEncoder using column transformer for 2nd and 3rd column
     ('rf', RandomForestClassifier(n_estimators=2,random_state=42))])

pipe.fit(X_train, y_train)

import joblib
joblib.dump(pipe, 'pipe.pkl')

loaded_pipe = joblib.load('pipe.pkl')
loaded_pipe.score(X_test, y_test)