python 随机森林
时间: 2023-10-15 17:02:58 浏览: 49
随机森林是一种集成学习方法,它通过组合多个决策树来进行分类和回归任务。在Python中,你可以使用scikit-learn库来实现随机森林算法。下面是一个简单的示例代码:
```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建随机森林分类器
rf_clf = RandomForestClassifier(n_estimators=100, random_state=42)
# 在训练集上训练模型
rf_clf.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = rf_clf.predict(X_test)
# 评估模型性能
accuracy = rf_clf.score(X_test, y_test)
print("Accuracy:", accuracy)
```
在上面的示例中,我们首先加载了一个经典的鸢尾花数据集(load_iris)作为示例数据。然后,我们将数据集划分为训练集和测试集,并创建了一个包含100个决策树的随机森林分类器(RandomForestClassifier)。接下来,我们使用训练集来训练模型(fit),并在测试集上进行预测(predict)。最后,我们使用score函数计算模型的准确率。你可以根据自己的需求调整参数来改进模型的性能。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)