【问题标题】:Python for-loop to find the best values for SVC (C and gamma)Python for 循环查找 SVC(C 和 gamma)的最佳值
【发布时间】:2018-08-06 23:10:02
【问题描述】:

我有一个数据集 X 和标签 y 用于训练和评分 sklearn.SVC 模型。数据分为X_trainX_test。我运行for-loop 来找到两个 SVC 参数的最佳可能值组合(即最佳分数):Cgamma。我可以打印出最高分,但如何打印用于该特定分数的 C 和 gamma 值?

for C in np.arange(0.05, 2.05, 0.05):
    for gamma in np.arange(0.001, 0.101, 0.001):
        model = SVC(kernel='rbf', gamma=gamma, C=C)
        model.fit(X_train, y_train)
        score = model.score(X_test, y_test)
        if score > best_score:
            best_score = score
print('Highest Accuracy Score: ', best_score)   

【问题讨论】:

  • 您可以为此使用 GridSearch。

标签: python machine-learning scikit-learn svc


【解决方案1】:

存储它们?

best_C = None
best_gamma = None
for C in np.arange(0.05, 2.05, 0.05):
    for gamma in np.arange(0.001, 0.101, 0.001):
        model = SVC(kernel='rbf', gamma=gamma, C=C)
        model.fit(X_train, y_train)
        score = model.score(X_test, y_test)
        if score > best_score:
            best_score = score
            best_C = C
            best_gamma = gamma
print('Highest Accuracy Score: ', best_score)  
print(best_C)
print(best_gamma)

【讨论】:

    【解决方案2】:

    你可以改成:

       if score > best_score:
            best_score = score
            best_C = C
            best_gamma = gamma 
    

    或者创建一个元组:

    if score > best_score:
        best_score = score, C, gamma 
    

    【讨论】:

      猜你喜欢
      • 2018-09-21
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 2019-09-18
      • 2013-10-05
      • 2018-08-17
      相关资源
      最近更新 更多