怎么把随机森林里每个类别的原始值和预测值输出
时间: 2023-06-14 20:08:15 浏览: 54
在随机森林中,每个类别的原始值可以通过访问每个决策树的输出来获得。具体来说,你可以使用`predict()`方法对随机森林进行预测,并使用`estimators_`属性来访问每个决策树。然后,你可以将每个决策树的输出相加,并除以树的数量,以获得每个类别的平均原始值。
下面是一个示例代码,展示如何输出每个类别的原始值和预测值:
```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
import numpy as np
# 加载鸢尾花数据集
iris = load_iris()
# 创建随机森林分类器
rf = RandomForestClassifier(n_estimators=100, random_state=42)
# 拟合模型并进行预测
rf.fit(iris.data, iris.target)
predictions = rf.predict(iris.data)
# 计算每个类别的原始值
raw_values = np.zeros((len(iris.data), len(np.unique(iris.target))))
for i, tree in enumerate(rf.estimators_):
raw_values[:, i%3] += tree.predict(iris.data)
raw_values /= len(rf.estimators_)
# 输出每个类别的原始值和预测值
for i, name in enumerate(iris.target_names):
print(f"{name}:")
print(f" Raw values: {raw_values[:, i]}")
print(f" Predictions: {predictions == i}")
```
在这个示例中,我们首先使用随机森林对鸢尾花数据集进行拟合,并进行预测。然后,我们使用`estimators_`属性访问每个决策树,并计算每个类别的原始值。最后,我们输出每个类别的原始值和预测值。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![csv](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)