2017-08-23 7 views
1

J'ai essayé d'implémenter ce code dans python 2.7. Cela me donne cette erreur. J'apprécierais l'aide. Je dernière version de sklearn (0.18.1) et xgboost (0,6)xgboost.cv donne TypeError: L'objet 'StratifiedKFold' n'est pas itérable

import xgboost as xgb 
from sklearn.model_selection import StratifiedKFold 
from sklearn.metrics import f1_score, roc_auc_score, confusion_matrix 

nfold = 3 
kf = StratifiedKFold(nfold, shuffle=True) 

dtrain = xgb.DMatrix(x_train, label=y_train) 
dtest = xgb.DMatrix(x_test) 

params = { 
    'objective' : 'binary:logistic', 
    'eval_metric': 'auc', 
    'min_child_weight':10, 
    'scale_pos_weight':scale, 
} 
hist = xgb.cv(params, dtrain, num_boost_round=10000, folds=kf, early_stopping_rounds=50, as_pandas=True, verbose_eval=100, show_stdv=True, seed=0) 

Je reçois cette erreur:

TypeErrorTraceback (most recent call last) 
<ipython-input-52-41c415e116d7> in <module>() 
     5  'scale_pos_weight':scale, 
     6 } 
----> 7 hist = xgb.cv(params, dtrain, num_boost_round=10000, folds=kf, early_stopping_rounds=50, as_pandas=True, verbose_eval=100, show_stdv=True, seed=0) 
     8 
     9 

/opt/conda/lib/python2.7/site-packages/xgboost/training.pyc in cv(params, dtrain, num_boost_round, nfold, stratified, folds, metrics, obj, feval, maximize, early_stopping_rounds, fpreproc, as_pandas, verbose_eval, show_stdv, seed, callbacks) 
    369 
    370  results = {} 
--> 371  cvfolds = mknfold(dtrain, nfold, params, seed, metrics, fpreproc, stratified, folds) 
    372 
    373  # setup callbacks 

/opt/conda/lib/python2.7/site-packages/xgboost/training.pyc in mknfold(dall, nfold, param, seed, evals, fpreproc, stratified, folds) 
    236   idset = [randidx[(i * kstep): min(len(randidx), (i + 1) * kstep)] for i in range(nfold)] 
    237  elif folds is not None: 
--> 238   idset = [x[1] for x in folds] 
    239   nfold = len(idset) 
    240  else: 

TypeError: 'StratifiedKFold' object is not iterable 

Répondre

1

Dans la fonction xgb.cv, essayez de remplacer

folds=kf 

avec

folds=list(kf.split(x_train,y_train)) 

Le split method est appliqué afin d'obtenir la scission dans l'entraînement et la validation. Nous le convertissons ensuite en list pour que ce soit un objet itérable. Si cela ne fonctionne pas, essayez sans list. C'est-à-dire:

folds=kf.split(x_train,y_train) 
0

Comme l'erreur le suggère, kf est un objet 'StratifiedKFold'.

Cet objet a une méthode .split() qui vous donnera un générateur contenant les différents indices train/éléments valides.

folds_generator = kf.split(x_train, y_train) 

Cependant, la lecture de la xgb.cv doc,

folds : list, provides a possibility to use a list of pre-defined CV folds (each element must be a vector of test fold's indices). When folds are supplied, the nfold and stratified parameters are ignored.

plis a besoin d'un argument de la 'liste' de type. Vous pouvez convertir votre générateur à une liste avec le code suivant

folds_list = list(folds_generator)