Scikit: how to check if an object is a RandomizedSearchCV or a RandomForestClassifier?

时间:2015-09-14 16:01:16

标签: python-2.7 types scikit-learn random-forest grid-search

I have a few classifiers that have been created using Grid Search, and others that have been created directly as Random Forests.

The random forests return type sklearn.ensemble.forest.RandomForestClassifier, and the random forests created with gridSearch return type sklearn.grid_search.RandomizedSearchCV.

I am trying to programmatically check the type of the estimator (in order to decide if I need to use best_estimator_ on feature importances), but can't seem to find a good way to do so.

if type(estimator) == 'sklearn.grid_search.RandomizedSearchCV' was my first guess, but is clearly wrong.

1 个答案:

答案 0 :(得分:3)

type()函数不返回classinfo,它返回类型对象。因此,将等式与类似的classinfo进行比较是行不通的。

您需要做的是使用 isinstance(object,classinfo)来测试估算工具的类型。

如果类型与classinfo匹配,则此函数返回True,否则返回False。

假设你创建了一个

类型的估算器
  

sklearn.ensemble.forest.RandomForestClassifier

然后

  

isinstance(estimator,sklearn.ensemble.forest.RandomForestClassifier)

将返回True,而

  

isinstance(估计器,sklearn.grid_search.RandomizedSearchCV)

会返回False。

然后,您可以在if语句等测试中使用该结果。

记得

  

导入sklearn

可以访问您可能需要测试的所有scikit-learn classinfo。