我正在尝试使用贝叶斯优化(Hyperopt)来获得 SVM 算法的最佳参数。但是,我发现每次运行时最佳参数都会发生变化。
下面提供了一个简单的可重现案例。你能解释一下吗?
import numpy as np
from hyperopt import fmin, tpe, hp, STATUS_OK, Trials
from sklearn.svm import SVC
from sklearn import svm, datasets
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.model_selection import StratifiedShuffleSplit
iris = datasets.load_iris()
X = iris.data[:, :2]
y = iris.target
def hyperopt_train_test(params):
clf = svm.SVC(**params)
return cross_val_score(clf, X, y).mean()
space4svm = {
'C': hp.loguniform('C', -3, 3),
'gamma': hp.loguniform('gamma', -3, 3),
}
def f(params):
acc = hyperopt_train_test(params)
return {'loss': -acc, 'status': STATUS_OK}
trials = Trials()
best = fmin(f, space4svm, algo=tpe.suggest, max_evals=1000, trials=trials)
print ('best:')
print (best)
以下是一些最佳值。
最佳:{'C':0.08776548401545513,'gamma':1.447360198193232}
最佳:{'C':0.23621788050791617,'gamma':1.2467882092108042}
最佳:{'C':0.3134163250819116,'gamma':1.0984778155489887}