How to graph grid scores from GridSearchCV?

前端 未结 10 1090
旧时难觅i
旧时难觅i 2021-01-30 03:19

I am looking for a way to graph grid_scores_ from GridSearchCV in sklearn. In this example I am trying to grid search for best gamma and C parameters for an SVR algorithm. My c

10条回答
  •  星月不相逢
    2021-01-30 04:15

    from sklearn.svm import SVC
    from sklearn.grid_search import GridSearchCV
    from sklearn import datasets
    import matplotlib.pyplot as plt
    import seaborn as sns
    import numpy as np
    
    digits = datasets.load_digits()
    X = digits.data
    y = digits.target
    
    clf_ = SVC(kernel='rbf')
    Cs = [1, 10, 100, 1000]
    Gammas = [1e-3, 1e-4]
    clf = GridSearchCV(clf_,
                dict(C=Cs,
                     gamma=Gammas),
                     cv=2,
                     pre_dispatch='1*n_jobs',
                     n_jobs=1)
    
    clf.fit(X, y)
    
    scores = [x[1] for x in clf.grid_scores_]
    scores = np.array(scores).reshape(len(Cs), len(Gammas))
    
    for ind, i in enumerate(Cs):
        plt.plot(Gammas, scores[ind], label='C: ' + str(i))
    plt.legend()
    plt.xlabel('Gamma')
    plt.ylabel('Mean score')
    plt.show()
    
    • Code is based on this.
    • Only puzzling part: will sklearn always respect the order of C & Gamma -> official example uses this "ordering"

    Output:

提交回复
热议问题