2015-05-07 7 views
21

Sto utilizzando GridSearch CV per ottimizzare i parametri di un classificatore in scikit. Una volta che ho finito, mi piacerebbe sapere quali parametri sono stati scelti come i migliori.Come ottenere il miglior estimatore su GridSearchCV (Random Forest Classifier Scikit)

Ogni volta che faccio così ottengo un AttributeError: 'RandomForestClassifier' object has no attribute 'best_estimator_', e non posso dire perché, come sembra essere un attributo legittimo sul documentation.

from sklearn.grid_search import GridSearchCV 

X = data[usable_columns] 
y = data[target] 

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) 

rfc = RandomForestClassifier(n_jobs=-1,max_features= 'sqrt' ,n_estimators=50, oob_score = True) 

param_grid = { 
    'n_estimators': [200, 700], 
    'max_features': ['auto', 'sqrt', 'log2'] 
} 

CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= 5) 

print '\n',CV_rfc.best_estimator_ 

Resa:

`AttributeError: 'GridSearchCV' object has no attribute 'best_estimator_' 

risposta

45

Bisogna adattare i vostri dati prima di poter ottenere la migliore combinazione di parametri.

from sklearn.grid_search import GridSearchCV 
from sklearn.datasets import make_classification 
from sklearn.ensemble import RandomForestClassifier 
# Build a classification task using 3 informative features 
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) 


rfc = RandomForestClassifier(n_jobs=-1,max_features= 'sqrt' ,n_estimators=50, oob_score = True) 

param_grid = { 
    'n_estimators': [200, 700], 
    'max_features': ['auto', 'sqrt', 'log2'] 
} 

CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= 5) 
CV_rfc.fit(X, y) 
print CV_rfc.best_params_ 
+0

Ha funzionato davvero, grazie! Qualche idea sul perché? (Pensavo che gridSearch avrebbe trovato i parametri, ma non sono riuscito a recuperare i parametri prima del montaggio) –

+9

Diversi set di dati avranno combinazioni di parametri ottimizzate diverse, ovvero senza dati, non esiste una combinazione di parametri ottimale – Ryan

+0

Qual è il senso per passare n_estimators to RandomForestClassifier tenendo conto che lo si passa anche a GridSearchCV in param_grid? – sergzach