2017-05-12 9 views
1

가장 예측적인 특성을 얻는 데 도움이되는 XGBClassifier에 대한 최상의 하이퍼 매개 변수를 얻으려고합니다. RandomizedSearchCV를 사용하여 KFold를 통해 반복 및 유효성 검사를 시도하고 있습니다.RandomizedSearchCV를 사용하는 XGBClassifier에 대한 Python 하이퍼 매개 변수 최적화

이 프로세스를 총 5 회 (numFolds = 5) 실행하면 콜렉터 (아래 명시)라는 데이터 프레임에 최상의 결과가 저장되기를 바랍니다. 그래서 각 반복, 나는 최고의 결과와 수집기 데이터 프레임에 추가 할 점수를 원할 것입니다.

from scipy import stats 
from scipy.stats import randint 
from sklearn.model_selection import RandomizedSearchCV 
from sklearn.metrics import 
precision_score,recall_score,accuracy_score,f1_score,roc_auc_score 

clf_xgb = xgb.XGBClassifier(objective = 'binary:logistic') 
param_dist = {'n_estimators': stats.randint(150, 1000), 
       'learning_rate': stats.uniform(0.01, 0.6), 
       'subsample': stats.uniform(0.3, 0.9), 
       'max_depth': [3, 4, 5, 6, 7, 8, 9], 
       'colsample_bytree': stats.uniform(0.5, 0.9), 
       'min_child_weight': [1, 2, 3, 4] 
      } 
clf = RandomizedSearchCV(clf_xgb, param_distributions = param_dist, n_iter = 25, scoring = 'roc_auc', error_score = 0, verbose = 3, n_jobs = -1) 

numFolds = 5 
folds = cross_validation.KFold(n = len(X), shuffle = True, n_folds = numFolds) 

collector = pd.DataFrame() 
estimators = [] 
results = np.zeros(len(X)) 
score = 0.0 

for train_index, test_index in folds: 
    X_train, X_test = X[train_index], X[test_index] 
    y_train, y_test = y[train_index], y[test_index] 
    clf.fit(X_train, y_train) 
    estimators.append(clf.best_estimator_) 
    estcoll = pd.DataFrame(estimators) 


    estcoll['score'] = score 
    pd.concat([collector,estcoll]) 
    print "\n", len(collector), "\n" 
score /= numFolds 

어떤 이유로 데이터 프레임에 아무 것도 저장되지 않아 도움이됩니다.

또한 전차에는 3.5K 행, 테스트에는 2K를 순환하는 약 350 가지 속성이 있습니다. 베이지안 (Bayesian) 하이퍼 파라미터 최적화 프로세스를 통해이를 실행하면 결과가 향상 될 수 있습니까? 아니면 처리 시간 만 절약 할 수 있을까요?

답변

2

RandomizedSearchCV() 당신이 실현하는 것보다 더 많은 일을 할 것입니다. 맞는 CV 오브젝트의 cv_results 속성을 살펴보십시오. at the documentation page

코드는 거의 변경되지 않았습니다. 두 가지 변화는 내가 추가 :

  1. 내가 당신의 5 배 교차 유효성 검사 (25 개) 총 맞는 의미 매개 변수의 5 개 세트를 할 것 (25)이에서 n_iter=5을 변경했습니다.
  2. 나는 RandomizedSearchCV 전에 kfold 객체를 정의하고 cv PARAM

_ 내 대답은 크게 코드에서 벗어난 곳

clf_xgb = xgb.XGBClassifier(objective = 'binary:logistic') 
param_dist = {'n_estimators': stats.randint(150, 1000), 
       'learning_rate': stats.uniform(0.01, 0.6), 
       'subsample': stats.uniform(0.3, 0.9), 
       'max_depth': [3, 4, 5, 6, 7, 8, 9], 
       'colsample_bytree': stats.uniform(0.5, 0.9), 
       'min_child_weight': [1, 2, 3, 4] 
      } 

numFolds = 5 
kfold_5 = cross_validation.KFold(n = len(X), shuffle = True, n_folds = numFolds) 

clf = RandomizedSearchCV(clf_xgb, 
         param_distributions = param_dist, 
         cv = kfold_5, 
         n_iter = 5, # you want 5 here not 25 if I understand you correctly 
         scoring = 'roc_auc', 
         error_score = 0, 
         verbose = 3, 
         n_jobs = -1) 

은 여기로 RandomizedSearchCV의 수영장 건설에 그것을 참조. randomizedsearchcv 개체를 한 번만 끼우면 반복 할 필요가 없습니다. CV 루프는 cv 인수로 처리합니다.

clf.fit(X_train, y_train) 

모든 교차 가중 결과는 현재 clf.cv_results_입니다. 예를 들어clf.cv_results_['mean_train_score'] 또는 교차 검증 된 테스트 세트 (홀드 아웃 데이터) 점수 clf.cv_results_['mean_test_score']을 사용하여 교차 유효성 검사 (평균 5 폴드)를 얻을 수 있습니다. mean_fit_time, paramsclf과 같은 유용한 정보도 얻을 수 있습니다. 자동으로 사용자의 best_estimator_을 특성으로 기억합니다.

다음은 모델 피팅을위한 최상의 하이퍼 매개 변수 세트를 결정하는 것과 관련이 있습니다. 하이퍼 파라미터의 단일 세트는 n_iter의 단일 반복에서 사용되는 5 폴드 각각에 대해 일정하기 때문에 반복 내에서 폴드 사이의 다른 점수를 피할 필요가 없습니다.

+0

감사합니다. 이 오류가 발생하는 이유를 알고 있으며이를 억제/수정해야합니까? /model_selection/_validation.py:252 : FitFailedWarning : 분류 기준 적합 실패. 이 매개 변수에 대한이 기차 테스트 파티션의 점수는 0.000000으로 설정됩니다. 세부 사항 : XGBoostError (매개 변수 colsample_bytree의 값 1.8782가 바운드 [0,1]을 초과했습니다.) "세부 정보 : \ n % r"% (오류 _ 점수, e), FitFailedWarning) – zad0xlik

+0

게시 한 오류 메시지에 'XGBoostError 매개 변수 colsample_bytree의 값 1.8782가 바운드 [0,1]'을 (를) 초과합니다.그 이유는''colsample_bytree ': stats.uniform (0.5, 0.9)'가 때때로 그 매개 변수에 대해 필요한 [0,1] 범위를 벗어나는 값을 생성하기 때문입니다. –