如何在Python中“保存”IsolationForest模型?

2024-06-25 23:09:51 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,我正在使用sklearn.ensemble.IsolationForest,来预测数据的异常值。在

是否可以将模型训练(拟合)到我的干净数据中,然后保存它以供以后使用? 例如保存模型的一些属性,这样下次就不必再调用fit函数来训练我的模型了。在

例如,对于GMM,我将保存每个组件的weights_means_和{},这样以后我就不需要再训练模型了。在

为了说明这一点,我将其用于在线欺诈检测,对于相同的“类别”数据,这个python脚本将被多次调用,我不想每次需要执行预测或测试操作时都训练模型。在

提前谢谢。在


Tags: 数据函数模型脚本属性组件sklearn类别
2条回答

https://docs.python.org/2/library/pickle.html

使用Pickle库。在

适合你的模型。在

pickle.dump(obj, file[, protocol])保存它

pickle.load(file)加载它

对你的异常值进行分类

sklearn估计器实现一些方法,使您更容易保存估计器的相关训练属性。有些估计器自己实现__getstate__方法,但是其他一些,比如GMM只使用base implementation,它只保存对象的内部字典:

def __getstate__(self):
    try:
        state = super(BaseEstimator, self).__getstate__()
    except AttributeError:
        state = self.__dict__.copy()

    if type(self).__module__.startswith('sklearn.'):
        return dict(state.items(), _sklearn_version=__version__)
    else:
        return state

将模型保存到光盘的推荐方法是使用^{}模块:

^{pr2}$

但是,您应该保存额外的数据,以便将来可以重新训练您的模型,否则将遭受严重后果(例如被锁定到旧版本的sklearn)。在

documentation

In order to rebuild a similar model with future versions of scikit-learn, additional metadata should be saved along the pickled model:

The training data, e.g. a reference to a immutable snapshot

The python source code used to generate the model

The versions of scikit-learn and its dependencies

The cross validation score obtained on the training data

尤其是在cysk6>中,它保证了在cysk6>之间的耦合是不稳定的。它在过去看到了向后不兼容的变化。在

如果您的模型变得非常大并且加载变得很麻烦,您还可以使用更高效的joblib。根据文件:

In the specific case of the scikit, it may be more interesting to use joblib’s replacement of pickle (joblib.dump & joblib.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:

相关问题 更多 >