Python for循环查找SVC(C和gamma)的最佳值

时间:2018-02-27 10:26:21

标签: python machine-learning scikit-learn svc

我有一个数据集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)   

2 个答案:

答案 0 :(得分:1)

您可以将其更改为:

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

或者创建一个元组:

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

答案 1 :(得分: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)