Skip to main content
 首页 » 编程设计

python之访问随机森林模型(Python、scikit-learn)中单个树的底层 (tree_) 对象

2024年10月24日14kerrycode

我需要将随机森林模型转换为基于规则的模型或基于 (if-then) 的模型。我现在已经创建了我的模型并且它已经调整好了。我面临的问题是我无法“访问”(base_estimator)或底层(tree_ object),这将使创建一个可以从森林中的树中提取规则的函数成为可能。如果您能帮我解决这个问题,我将不胜感激。要创建我使用的模型:

    estimator = RandomForestRegressor(oob_score=True, n_estimators=10,max_features='auto') 

我尝试使用 estimator.estimators_ 属性访问单个树,然后使用例如 estimator.estimators_[0].tree_ 来获取决策树( DecisionTreeRegressor 对象)用于构建森林。不幸的是,这种方法不起作用。

如果可能的话,我想要这样的东西:

   estimator = RandomForestRegressor(oob_score=True, n_estimators=10,max_features='auto') 
   estimator.fit(tarning_data,traning_target) 
   tree1 = estimator.estimators_[0] 
   leftChild = tree1.tree_.children_left 
   rightChild = tree1.tree_.children_right 

请您参考如下方法:

要访问随机森林模型中 DecisionTreeRegressor 对象的底层结构,您需要按照以下步骤操作:

estimator = RandomForestRegressor(oob_score=True,n_estimators=10,max_features='auto') 
estimator.fit(tarning_data,traning_target) 
tree1 = estimator.estimators_[0] 
leftChilds = tree1.tree_.children_left # array of left children 
rightChilds = tree1.tree_.children_right #array of right children 

即本质上是问题中已经描述的内容。