gpt4 book ai didi

python - 如何在 Python 中对 IsolationForest 模型执行 "save"操作?

转载 作者:行者123 更新时间:2023-11-30 09:49:50 27 4
gpt4 key购买 nike

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

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

例如,对于GMM,我会保存每个分量的weights_means_covs_,所以以后我就不需要再次训练模型了。

为了澄清这一点,我将其用于在线欺诈检测,其中针对同一数据“类别”会多次调用此 python 脚本,并且我不想每次都训练模型需要执行预测或测试操作。

提前致谢。

最佳答案

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

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

from sklearn import datasets
from sklearn.svm import SVC
iris = datasets.load_iris()
X = iris.data[:100, :2]
y = iris.target[:100]
model = SVC()
model.fit(X,y)
import pickle
with open('mymodel','wb') as f:
pickle.dump(model,f)

但是,您应该保存额外的数据,以便将来重新训练模型,否则会遭受可怕的后果(例如被锁定到旧版本的 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

对于依赖 tree.pyx 的集成估计器尤其如此使用 Cython 编写的模块(例如 IsolationForest),因为它创建了与实现的耦合,不能保证 sklearn 版本之间的稳定性。它过去曾经历过向后不兼容的变化。

如果您的模型变得非常大并且加载变得很麻烦,您还可以使用更高效的 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:

关于python - 如何在 Python 中对 IsolationForest 模型执行 "save"操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47156906/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com