【问题标题】:Does cross_val_score not fit the actual input model?cross_val_score 不适合实际的输入模型吗?
【发布时间】:2020-10-25 07:15:59
【问题描述】:

我正在处理一个大型数据集的项目。

我需要在 Sklearn 的 KFold 交叉验证库中训练 SVM 分类器。

import pandas as pd
from sklearn import svm
from sklearn.metrics import accuracy_score
from sklearn.model_selection import cross_val_score


x__df_chunk_synth = pd.read_csv('C:/Users/anujp/Desktop/sort/semester 4/ATML/Sem project/atml_proj/Data/x_train_syn.csv')
y_df_chunk_synth = pd.read_csv('C:/Users/anujp/Desktop/sort/semester 4/ATML/Sem project/atml_proj/Data/y_train_syn.csv')

svm_clf = svm.SVC(kernel='poly', gamma=1, class_weight=None, max_iter=20000, C = 100, tol=1e-5)
X = x__df_chunk_synth
Y = y_df_chunk_synth
scores = cross_val_score(svm_clf, X, Y,cv = 5, scoring = 'f1_weighted')
print(scores)
    
pred = svm_clf.predict(chunk_test_x)
accuracy = accuracy_score(chunk_test_y,pred)

print(accuracy)

我正在使用上述代码。 我知道我正在使用 cross_val_score 函数训练我的分类器,因此每当我试图在外部调用分类器以预测测试数据时,都会出现错误:

sklearn.exceptions.NotFittedError: This SVC instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.

还有其他选择以正确的方式做同样的事情吗?

请帮我解决这个问题。

【问题讨论】:

    标签: python machine-learning scikit-learn svm k-fold


    【解决方案1】:

    确实model_selection.cross_val_score 使用输入模型来拟合数据,因此不必拟合。但是,它不适合用作输入的实际对象,而是它的 副本,因此在尝试预测时会出现错误 This SVC instance is not fitted yet...

    查看在cross_val_score中调用的cross_validate中的源代码,在评分步骤中,estimator首先经过clone

    scores = parallel(
        delayed(_fit_and_score)(
            clone(estimator), X, y, scorers, train, test, verbose, None,
            fit_params, return_train_score=return_train_score,
            return_times=True, return_estimator=return_estimator,
            error_score=error_score)
        for train, test in cv.split(X, y, groups))
    

    这会创建模型的深层副本(这就是未拟合实际输入模型的原因):

    def clone(estimator, *, safe=True):
        """Constructs a new estimator with the same parameters.
        Clone does a deep copy of the model in an estimator
        without actually copying attached data. It yields a new estimator
        with the same parameters that has not been fit on any data.
        ...
    

    【讨论】:

    • 非常感谢您的回复。所以我的理解是,我们通过查看分数来使用 KFold 验证进行超参数调整。一旦我们获得了最佳参数,我们需要使用该参数并创建另一个分类器来训练训练数据。然后这个经过训练的分类器可以进一步用于预测测试数据。如果我理解错了,请纠正我。
    • 是的,通常您应该使用GridSearch 对模型进行微调以获得最佳参数。然后拟合一个新的分类器并预测看不见的(测试)数据。 @raj
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2016-12-15
    相关资源
    最近更新 更多