我想通过GridSearchCV优化SVM的超参数。但是,最佳估算器的分数与使用最佳参数运行 svm 时的分数有很大不同。
#### Hyperparameter search with GridSearchCV###
pipeline = Pipeline([
("scaler", StandardScaler()),
("svm", LinearSVC(loss='hinge'))])
param_grid=[{'svm__C': c_range}]
clf = GridSearchCV(pipeline, param_grid=param_grid, cv=5, scoring='accuracy')
clf.fit(X,y)
print('n Best score: ',clf.best_score_)
#### scale train and test data ###
sc = StandardScaler()
sc.fit(X)
X = scaler.transform(X)
X_test = sc.transform(X_test)
###### test best estimator with test data ###################
print("Best estimator score: ", clf.best_estimator_.score(X_test, y_test))
##### run SVM with the best found parameter #####
svc = LinearSVC(C=clf.best_params_['svm_C'])
svc.fit(X,y)
print("score with best parameter: ", svc.score(X_test,y_test))
结果如下:
最好成绩: 0.784
最佳估算器得分:0.6991
最佳参数得分:0.7968
我不明白为什么最佳估算器和 svm 的分数不同?以下结果中哪一个是正确的测试精度?为什么最佳估算器的得分为 0.6991 如此差?我做错了什么吗?
在下面的行中:
print("Best estimator score: ", clf.best_estimator_.score(X_test, y_test))
您正在传递已经缩放X_test
clf
这是一个包含另一个缩放器的pipeline
,因此本质上,您将数据缩放到与上一个预测语句的两倍,在该语句中,您将缩放的数据传递给svc
后者只是在不缩放的情况下进行模型拟合。因此,在这两种情况下提供的数据完全不同,因此您的预测也不同。
希望这有帮助!