【问题标题】:GridSearchCV: How to write the output of each configuration to a csv as it finishes and not altogether?GridSearchCV:如何在完成时将每个配置的输出写入 csv,而不是完全写入?
【发布时间】:2021-09-27 17:59:53
【问题描述】:

我正在使用 scikit-learn 的 GridSearchCV 对各种超参数运行网格搜索。 GridSearchCV 完成后,我可以通过访问 grid_search_object.cv_results_ 将网格搜索的输出写入 csv。

但是,相反,我想将每个配置的输出写入 csv,而不是全部写入。有没有办法做到这一点?

【问题讨论】:

    标签: python machine-learning scikit-learn hyperparameters


    【解决方案1】:

    解决方法是将 GridsearchCV 的 verbose 属性设置为 3,以便记录候选参数和分数并将日志的输出捕获到文件中。你可以这样做:

    from sklearn import svm, datasets
    from sklearn.model_selection import GridSearchCV
    import sys
    
    old_stdout = sys.stdout
    log_file = open("cv.log","w")
    sys.stdout = log_file
    
    iris = datasets.load_iris()
    parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
    svc = svm.SVC()
    clf = GridSearchCV(svc, parameters, verbose=3)
    clf.fit(iris.data, iris.target)
    
    sys.stdout = old_stdout
    log_file.close()
    

    这会将结果以及每次迭代的参数写入文件。您可以在下面看到cv.log 内容的示例:

    Fitting 5 folds for each of 4 candidates, totalling 20 fits
    [CV 1/5] END ................C=1, kernel=linear;, score=0.967 total time=   0.0s
    [CV 2/5] END ................C=1, kernel=linear;, score=1.000 total time=   0.0s
    [CV 3/5] END ................C=1, kernel=linear;, score=0.967 total time=   0.0s
    [CV 4/5] END ................C=1, kernel=linear;, score=0.967 total time=   0.0s
    [CV 5/5] END ................C=1, kernel=linear;, score=1.000 total time=   0.0s
    

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2017-12-03
      • 1970-01-01
      • 2016-04-19
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 2023-02-04
      相关资源
      最近更新 更多