2017-08-14 15 views
1

我用hyperopt搜索SVM分類器的最佳參數,但Hyperopt表示最好的'內核'是'0'。 {'kernel':'0'}顯然是不合適的。Hyperopt解決的最佳參數不適用

有沒有人知道它是由我的錯還是一袋hyperopt造成的?

代碼如下。

from hyperopt import fmin, tpe, hp, rand 
import numpy as np 
from sklearn.metrics import accuracy_score 
from sklearn import svm 
from sklearn.cross_validation import StratifiedKFold 

parameter_space_svc = { 
    'C':hp.loguniform("C", np.log(1), np.log(100)), 
    'kernel':hp.choice('kernel',['rbf','poly']), 
    'gamma': hp.loguniform("gamma", np.log(0.001), np.log(0.1)),  
} 

from sklearn import datasets 
iris = datasets.load_digits() 

train_data = iris.data 
train_target = iris.target 

count = 0 

def function(args): 
    print(args) 
    score_avg = 0 
    skf = StratifiedKFold(train_target, n_folds=3, shuffle=True, random_state=1) 
    for train_idx, test_idx in skf: 
    train_X = iris.data[train_idx] 
    train_y = iris.target[train_idx] 
    test_X = iris.data[test_idx] 
    test_y = iris.target[test_idx] 
    clf = svm.SVC(**args) 
    clf.fit(train_X,train_y) 
    prediction = clf.predict(test_X) 
    score = accuracy_score(test_y, prediction) 
    score_avg += score 

    score_avg /= len(skf) 
    global count 
    count = count + 1 
    print("round %s" % str(count),score_avg) 
    return -score_avg 

best = fmin(function, parameter_space_svc, algo=tpe.suggest, max_evals=100) 
print("best estimate parameters",best) 

輸出低於。

best estimate parameters {'C': 13.271912841932233, 'gamma': 0.0017394328334592358, 'kernel': 0} 

回答

1

首先,您使用的sklearn.cross_validation已棄用的0.18版本。所以請更新到sklearn.model_selection

現在對於主要問題,best from fmin總是返回使用hp.choice定義的參數的索引。

所以在你的情況下,'kernel':0意味着第一個值('rbf')被選爲內核的最佳值。

看到這個問題,它證實了這一點:

  • ​​

best獲得的原始值,使用space_eval()功能如下:

from hyperopt import space_eval 
space_eval(parameter_space_svc, best) 

Output: 
{'C': 13.271912841932233, 'gamma': 0.0017394328334592358, 'kernel': 'rbf'} 
+0

哦,我不知道這是已被棄用使用'sklearn.cross_validation'。你的指導非常有幫助,我必須能夠獲得合適的內核價值。非常感謝。 –

+0

@橫尾修平是的,如果你使用v 0.18或更高版本,當你使用'cross_validation'時,你會得到一個警告。 –