【问题标题】:How to run GridSearchCV with multiple values in cv如何在 cv 中使用多个值运行 GridSearchCV
【发布时间】:2021-11-21 20:04:02
【问题描述】:

我正在对贷款预测数据使用逻辑回归。我正在使用 GridSearchCV 进行超参数调整,我一直在尝试找到一个可以为 cv 添加多个值的源。例如;我想以 3、5、6、7、10 折运行我的模型。这是我的代码:

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
parameters = {'penalty': ['l1', 'l2'],
                      'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000],
                      'solver' : ['liblinear', 'newton-cg', 'lbfgs', 'saga', 'sag'],
                      'multi_class' : ['auto'],
                      'max_iter'    : [5,15,25],
                  
                     }
s_scaled_X_train = s_scaler.fit_transform(X_train)
s_scaled_X_test = s_scaler.transform(X_test)

logmodel = GridSearchCV(LogisticRegression(), parameters, cv = 10, refit = True)

我试图寻找可以找到解决方案的来源,了解如何在此处的 cv 值中添加更多数字。

logmodel = GridSearchCV(LogisticRegression(), parameters, cv = 10, refit = True)

我尝试了类似的方法:

bb = [3, 5, 6, 7, 10]
cv_folds = bb

我尝试将其添加到日志模型中。

logmodel = GridSearchCV(LogisticRegression(), parameters, cv = cv_folds, refit = True)

这是我运行时遇到的错误

 TypeError: cannot unpack non-iterable int object

【问题讨论】:

    标签: python machine-learning scikit-learn logistic-regression gridsearchcv


    【解决方案1】:

    我认为 Grid Search CV 中没有任何内置方式来调整 cv 的数量,但您可以使用 for-loop 来检查哪个 cv 更好,如下所示:

    import warnings
    warnings.filterwarnings("ignore")
    
    cv_folds = [3, 5, 6, 7, 10]
    
    for x in cv_folds:
        logmodel = GridSearchCV(LogisticRegression(random_state = 12), parameters, cv = x, refit = True)
        logmodel.fit(X_train, y_train)
        
        print('The best score with CV =', x, 'is', logmodel.score(X_test, y_test), 'with parameters =\n\n', logmodel.best_params_, '\n\n')
    

    它将返回如下输出:

    The best score with CV = 3 is 0.9824561403508771 with parameters =
    
     {'C': 100, 'max_iter': 15, 'multi_class': 'auto', 'penalty': 'l1', 'solver': 'liblinear'} 
    
    
    The best score with CV = 5 is 0.9824561403508771 with parameters =
    
     {'C': 100, 'max_iter': 15, 'multi_class': 'auto', 'penalty': 'l1', 'solver': 'liblinear'} 
    
    
    The best score with CV = 6 is 0.9883040935672515 with parameters =
    
     {'C': 1000, 'max_iter': 15, 'multi_class': 'auto', 'penalty': 'l1', 'solver': 'liblinear'} 
    
    
    The best score with CV = 7 is 0.9941520467836257 with parameters =
    
     {'C': 100, 'max_iter': 25, 'multi_class': 'auto', 'penalty': 'l1', 'solver': 'liblinear'} 
    
    
    The best score with CV = 10 is 0.9883040935672515 with parameters =
    
     {'C': 1000, 'max_iter': 15, 'multi_class': 'auto', 'penalty': 'l1', 'solver': 'liblinear'}
    

    我们可以看到 CV = 7 给出了非常好的结果。

    【讨论】:

      猜你喜欢
      • 2019-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 2021-12-15
      • 2010-10-01
      • 2018-07-14
      • 2017-09-18
      相关资源
      最近更新 更多