【问题标题】:Saving the preprocessing steps in the end model [duplicate]在最终模型中保存预处理步骤[重复]
【发布时间】:2020-10-25 17:02:03
【问题描述】:

我正在尝试将我的文本分类模型保存为 pickle 文件。我有一组特定的预处理步骤,我想将它们保存在我的最终模型中,以将其应用于看不见的数据进行预测。目前我尝试使用 sklearn 管道,其中包括预处理、应用计数矢量化器和应用算法。我的问题是,这是否是将预处理步骤保存在最终模型中的正确方法,还是应该将其保存为单独的文件。下面是我的代码

from sklearn import model_selection
X_train, X_test, y_train, y_test = model_selection.train_test_split(df_train.data, df_train.label, test_size=0.2)
vect = CountVectorizer(stop_words='english', max_features=10000, , ngram_range=(1,2))
X_train_dtm = vect.fit_transform(X_train)
X_test_dtm = vect.transform(X_test)

from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier
rf_classifier = RandomForestClassifier(n_estimators=100)
rf_classifier.fit(X_train_dtm, y_train)
rf_predictions = rf_classifier.predict(X_test_dtm)
print("RF Accuracy:")
metrics.accuracy_score(y_test, rf_predictions)


import pickle
from sklearn.pipeline import Pipeline
pipe = Pipeline([("prep", prep),("CV", vect), ("RF", rf_classifier)])
with open('PII_model.pickle', 'wb') as picklefile:
    pickle.dump(pipe, picklefile)

我有一个预处理方法,我调用了它,并将它包含在我的 sklearn 管道中

prep = prep(df_train)

【问题讨论】:

    标签: python machine-learning scikit-learn pickle


    【解决方案1】:

    一般来说,这是正确的方法。但是您可以改进它,从一开始就将所有内容都放在管道中:

    vect = CountVectorizer(stop_words='english', 
                           max_features=10000, 
                           ngram_range=(1,2))
    rf_classifier = RandomForestClassifier(n_estimators=100)
    pipe = Pipeline([("prep", prep),("CV", vect), ("RF", rf_classifier)])    
    pipe.fit(X_train_dtm, y_train)
    
    rf_predictions = pipe.predict(X_test_dtm)
    print("RF Accuracy:")
    metrics.accuracy_score(y_test, rf_predictions)
    
    with open('PII_model.pickle', 'wb') as picklefile:
        pickle.dump(pipe, picklefile)
    

    将所有内容放在一个管道中的另一个好处 - 您可以轻松地使用 GridSearch 来调整模型的参数。

    您还可以在此处找到有关如何组织pipeline with mixed types 的官方文档。

    【讨论】:

    • 我只是有一个后续问题。如上所述,我尝试将我的预处理步骤保存在管道中,并且在预测新数据时,我没有看到我的预处理步骤被应用。此外,当我尝试使用和不使用预处理步骤保存模型时,我看不到 pickle 文件大小有任何差异。所以我想知道我是否必须首先有一个函数来应用我的预处理(prep=prep(df_train)),然后加载泡菜文件。
    • 似乎,是的,您需要在安装管道之前应用您的预处理功能。还有另一种方法 - 您可以将逻辑包装到自定义转换器中。然后你可以将你的转换器包含到 sklearn 管道中。为了实现,你只需要扩展scikit-learn.org/stable/modules/generated/… 来定义一个新的转换器。这是一个很好的文档,其中包含如何实现它的示例 (cloud.google.com/ai-platform/prediction/docs/…)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    相关资源
    最近更新 更多