3

python と scikit-learn を使用して、グリッド検索を行いたいと思います。しかし、私のモデルのいくつかは空になってしまいます。これらのモデルを無視するようにグリッド検索機能を作成するにはどうすればよいですか?

モデルが空の場合に 0 を返すスコアリング関数を使用できると思いますが、方法がわかりません。

predictor = sklearn.svm.LinearSVC(penalty='l1', dual=False, class_weight='auto')
param_dist = {'C': pow(2.0, np.arange(-10, 11))}
learner = sklearn.grid_search.GridSearchCV(estimator=predictor,
                                           param_grid=param_dist,
                                           n_jobs=self.n_jobs, cv=5,
                                           verbose=0)
learner.fit(X, y)

私のデータは、このlearnerオブジェクトがC空のモデルに対応するを選択するようになっています。モデルが空でないことを確認する方法はありますか?

編集:「空のモデル」とは、使用する機能を0つ選択したモデルを意味します。特にl1正規化されたモデルでは、これは簡単に起こります。したがって、この場合、CSVM の が十分に小さければ、最適化問題は係数の最適解として 0 ベクトルを見つけます。したがって、 は s のpredictor.coef_ベクトルになります0

4

2 に答える 2

4

次のようなカスタム スコアラーを実装してみてください。

import numpy as np

def scorer_(estimator, X, y):
    # Your criterion here
    if np.allclose(estimator.coef_, np.zeros_like(estimator.coef_)):
        return 0
    else:
        return estimator.score(X, y)

learner = sklearn.grid_search.GridSearchCV(...
                                           scoring=scorer_)
于 2015-09-06T11:13:31.613 に答える
1

そのような組み込み関数はないと思います。ただし、カスタム gridsearcher を作成するのは簡単です。

from sklearn.cross_validation import KFold                                                                                                                   
from sklearn.grid_search import GridSearchCV                                                                                                                 
from sklearn.cross_validation import cross_val_score                                                                                                         
import itertools                                                                                                                                             
from sklearn import metrics                                                                                                                                  
import operator                                                                                                                                              


def model_eval(X, y, model, cv):                                                                                                                             
        scores = []                                                                                                                                          
        for train_idx, test_idx in cv:                                                                                                                       
                X_train, y_train = X[train_idx], y[train_idx]                                                                                                
                X_test, y_test = X[test_idx], y[test_idx]                                                                                                    
                model.fit(X_train, y_train)                                                                                                                  
                nonzero_coefs = len(np.nonzero(model.coef_)[0]) #check for nonzero coefs                                                                     
                if nonzero_coefs == 0: #if they're all zero, don't evaluate any further; move to next hyperparameter combo                                   
                        return 0                                                                                                                             
                predictions = model.predict(X_test)                                                                                                          
                score = metrics.accuracy_score(y_test, predictions)                                                                                          
                scores.append(score)                                                                                                                         
        return np.array(scores).mean()                                                                                                                       


X, y = make_classification(n_samples=1000,                                                                                                                   
                           n_features=10,                                                                                                                    
                           n_informative=3,                                                                                                                  
                           n_redundant=0,                                                                                                                    
                           n_repeated=0,                                                                                                                     
                           n_classes=2,                                                                                                                      
                           random_state=0,                                                                                                                   
                           shuffle=False)                                                                                                                    


C = pow(2.0, np.arange(-20, 11))                                                                                                                             
penalty = {'l1', 'l2'}                                                                                                                                       

parameter_grid = itertools.product(C, penalty)                                                                                                               

kf = KFold(X.shape[0], n_folds=5) #use the same folds  to evaluate each hyperparameter combo                                                                 

hyperparameter_scores = {}                                                                                                                                   
for C, penalty in parameter_grid:                                                                                                                            
        model = svm.LinearSVC(dual=False, C=C, penalty=penalty)                                                                                              
        result = model_eval(X, y, model, kf)                                                                                                                 
        hyperparameter_scores[(C, penalty)] = result                                                                                                         

sorted_scores = sorted(hyperparameter_scores.items(), key=operator.itemgetter(1))                                                                            

best_parameters, best_score = sorted_scores[-1]                                                                                                              
print best_parameters                                                                                                                                        
print best_score     
于 2015-09-06T09:45:01.533 に答える