【问题标题】:Reusing model fitted by cross_val_score in sklearn using joblib使用joblib在sklearn中重用由cross_val_score拟合的模型
【发布时间】:2016-07-12 23:01:18
【问题描述】:

我在python中创建了以下函数:

def cross_validate(algorithms, data, labels, cv=4, n_jobs=-1):
    print "Cross validation using: "
    for alg, predictors in algorithms:
        print alg
        print
        # Compute the accuracy score for all the cross validation folds. 
        scores = cross_val_score(alg, data, labels, cv=cv, n_jobs=n_jobs)
        # Take the mean of the scores (because we have one for each fold)
        print scores
        print("Cross validation mean score = " + str(scores.mean()))

        name = re.split('\(', str(alg))
        filename = str('%0.5f' %scores.mean()) + "_" + name[0] + ".pkl"
        # We might use this another time 
        joblib.dump(alg, filename, compress=1, cache_size=1e9)  
        filenameL.append(filename)
        try:
            move(filename, "pkl")
        except:
            os.remove(filename) 

        print 
    return

我认为为了进行交叉验证,sklearn 必须适合您的功能。

但是,当我稍后尝试使用它时(f是我上面保存在joblib.dump(alg, filename, compress=1, cache_size=1e9))中的pkl文件:

alg = joblib.load(f)  
predictions = alg.predict_proba(train_data[predictors]).astype(float)

我在第一行没有收到错误(所以看起来负载正在工作),但随后它在下一行告诉我 NotFittedError: Estimator not fitted, callfitbefore exploiting the model.

我做错了什么?我不能重复使用适合计算交叉验证的模型吗?我查看了Keep the fitted parameters when using a cross_val_score in scikits learn,但要么我不明白答案,要么这不是我想要的。我想要的是用 joblib 保存整个模型,以便以后无需重新拟合即可使用它。

【问题讨论】:

    标签: python scikit-learn joblib


    【解决方案1】:

    Cross_val_score 不保留拟合模型 Cross_val_predict 确实 没有 cross_val_predict_proba 但你可以这样做

    predict_proba for a cross-validated model

    【讨论】:

      【解决方案2】:

      交叉验证必须适合您的模型并不完全正确;而是 k 折交叉验证在部分数据集上拟合您的模型 k 次。如果你想要模型本身,你实际上需要在整个数据集上再次拟合模型;这实际上不是交叉验证过程的一部分。所以实际上调用不会是多余的

      alg.fit(data, labels)
      

      在交叉验证后拟合您的模型。

      另一种方法是不使用专用函数cross_val_score,您可以将其视为交叉验证网格搜索的特例(参数空间中只有一个点)。在这种情况下,GridSearchCV 默认会在整个数据集上重新拟合模型(它有一个参数 refit=True),并且在其 API 中还有 predictpredict_proba 方法。

      【讨论】:

      • 那不是真的。当然,交叉验证必须适合您的模型,无论是在部分数据集上还是整体上,都不会影响模型的“拟合”特征
      【解决方案3】:

      您的模型未拟合的真正原因是函数 cross_val_score 在拟合副本之前首先复制您的模型:Source link

      所以你的原始模型没有安装。

      【讨论】:

        猜你喜欢
        • 2017-07-04
        • 2020-06-02
        • 2017-04-30
        • 2019-04-26
        • 2017-07-14
        • 2019-10-11
        • 1970-01-01
        • 2015-11-04
        • 2016-02-03
        相关资源
        最近更新 更多