3.4. Model persistence

本文介绍了如何使用Python的pickle模块来保存和加载sklearn训练好的模型,以便于未来的使用。此外,还讨论了使用joblib进行序列化的优点,并提到了在模型持久化过程中需要注意的安全性和维护性问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

After training a scikit-learn model, it is desirable to have a way to persistthe model for future use without having to retrain. The following section givesyou an example of how to persist a model with pickle. We’ll also review a fewsecurity and maintainability issues when working with pickle serialization.

3.4.1. Persistence example

It is possible to save a model in the scikit by using Python’s built-inpersistence model, namely pickle:

>>>
>>> from sklearn import svm
>>> from sklearn import datasets
>>> clf = svm.SVC()
>>> iris = datasets.load_iris()
>>> X, y = iris.data, iris.target
>>> clf.fit(X, y)  
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0,
  kernel='rbf', max_iter=-1, probability=False, random_state=None,
  shrinking=True, tol=0.001, verbose=False)

>>> import pickle
>>> s = pickle.dumps(clf)
>>> clf2 = pickle.loads(s)
>>> clf2.predict(X[0])
array([0])
>>> y[0]
0

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

>>>
>>> from sklearn.externals import joblib
>>> joblib.dump(clf, 'filename.pkl') 

Later you can load back the pickled model (possibly in another Python process)with:

>>>
>>> clf = joblib.load('filename.pkl') 

Note

joblib.dump returns a list of filenames. Each individual numpy arraycontained in the clf object is serialized as a separate file on thefilesystem. All files are required in the same folder when reloading themodel with joblib.load.

3.4.2. Security & maintainability limitations

pickle (and joblib by extension), has some issues regarding maintainabilityand security. Because of this,

  • Never unpickle untrusted data
  • Models saved in one version of scikit-learn might not load in anotherversion.

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

This should make it possible to check that the cross-validation score is in thesame range as before.

If you want to know more about these issues and explore other possibleserialization methods, please refer to thistalk by Alex Gaynor.

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'attrDefEndpointImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'attrDefServiceImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eavAttrServiceImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eavAttrRepositoryImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'eavAttrMapper' defined in file [D:\pdm\in-mom-pl\in-mom-pl-infrastructure\target\classes\com\industics\mom\pl\infrastructure\persistence\mapper\EavAttrMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [D:\pdm\in-mom-pl\in-mom-pl-infrastructure\target\classes\mapper\ProcessMainMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'file [D:\pdm\in-mom-pl\in-mom-pl-infrastructure\target\classes\mapper\ProcessMainMapper.xml]'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'com.example.model.ProcessMain'. Cause: java.lang.ClassNotFoundException: Cannot find class: com.example.model.ProcessMain
最新发布
04-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值