scikit-learn使用joblib持久化模型过程中的问题详解

本文介绍了在机器学习过程中如何使用scikit-learn的joblib库进行模型持久化和加载,包括如何通过设置压缩参数来减少模型文件大小,以及正确加载模型的方法。文章还提供了示例代码和模型文件压缩后的文件结构展示。

在机器学习过程中,一般用来训练模型的过程比较长,所以我们一般会将训练的模型进行保存(持久化),然后进行评估,预测等等,这样便可以节省大量的时间。


在模型持久化过程中,我们使用scikit-learn提供的joblib.dump()方法,但是在使用过程中会出现很多问题。如我们使用如下语句:

[python]  view plain copy
  1. from sklearn.externals import joblib
  2. joblib.dump(clf,'../../data/model/randomforest.pkl')  
此语句将产生大量的模型文件,如下图所示


然后,我们再使用joblib.load(‘../../data/model/randomforest.pkl’)进行加载.当设置参数时,模型持久化便会压缩成一个文件。

以下是我们进行模型持久化的正确操作语句:

[python]  view plain copy
  1. from sklearn.externals import joblib

  2. #save model  
  3. joblib.dump(clf,'../../data/model/randomforest.pkl',compress=3)  
  4. #load model to clf  
  5. clf = joblib.load('../../data/model/randomforest.pkl')  
<ol start="1" class="dp-py" style="font-family: Consolas, 'Courier New', Courier, mono, serif; font-size: 18px; line-height: 26px; padding: 0px; border: none; list-style-position: initial; list-style-image: initial; color: rgb(92, 92, 92); margin: 0px 0px 1px 45px !important;"><li class="alt" style="border-style: none none none solid; border-left-width: 3px; border-left-color: rgb(108, 226, 108); list-style: decimal-leading-zero outside; color: inherit; line-height: 18px; margin: 0px !important; padding: 0px 3px 0px 10px !important;"><pre name="code" class="python" style="color: rgb(51, 51, 51); font-size: 18px; line-height: 26px;">
  • from sklearn.externals import joblib

  • #load model to clf  
  • clf = joblib.load('../../data/model/randomforest.pkl')
       

    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

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

    抵扣说明:

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

    余额充值