有没有办法在 scikit-learn 中保存预处理对象?

Is there a way to save the preprocessing objects in scikit-learn?

我正在构建一个神经网络,目的是对未来的新数据进行预测。我首先使用 sklearn.preprocessing 预处理训练数据,然后训练模型,然后进行一些预测,然后关闭程序。将来,当有新数据进来时,我必须使用相同的预处理尺度来转换新数据,然后再将其放入模型中。目前,我必须加载所有旧数据,适应预处理器,然后使用这些预处理器转换新数据。有没有办法让我保存预处理对象对象(如 sklearn.preprocessing.StandardScaler),这样我就可以只加载旧对象而不必重新制作它们?

正如 lejlot 所提到的,您可以使用库 pickle 将训练好的网络作为文件保存在您的硬盘中,然后您只需要加载它就可以开始进行预测了。

下面是一个关于如何使用 pickle 保存和加载 python 对象的示例:

import pickle
import numpy as np

npTest_obj = np.asarray([[1,2,3],[6,5,4],[8,7,9]])

strTest_obj = "pickle example XXXX"


if __name__ == "__main__":
    # store object information
    pickle.dump(npTest_obj, open("npObject.p", "wb"))
    pickle.dump(strTest_obj, open("strObject.p", "wb"))

    # read information from file
    str_readObj = pickle.load(open("strObject.p","rb"))
    np_readObj = pickle.load(open("npObject.p","rb"))
    print(str_readObj)
    print(np_readObj)

我觉得除了pickle,你也可以用joblib来做这个。正如 Scikit-learn 手册中所述 3.4. Model persistence

In the specific case of scikit-learn, it may be better to use joblib’s replacement of pickle (dump & load), which is more efficient on objects that carry large numpy arrays internally as is often the case for fitted scikit-learn estimators, but can only pickle to the disk and not to a string:

from joblib import dump, load
dump(clf, 'filename.joblib') 

稍后您可以加载回已腌制的模型(可能在另一个 Python 进程中):

clf = load('filename.joblib') 

更多信息请参考其他帖子,,