构建随机森林模型代码
时间: 2024-05-20 07:09:06 浏览: 16
随机森林是一种集成学习的方法,它通过同时构建多个决策树,再综合这些决策树的结果来做出分类或回归预测。下面是一个简单的Python代码实现随机森林模型的过程:
1.导入必要的库
```
from sklearn.ensemble import RandomForestClassifier #随机森林分类器
from sklearn.datasets import make_classification #生成数据集
from sklearn.model_selection import train_test_split #划分训练集和测试集
```
2.生成数据集
```
X, y = make_classification(n_samples=1000, n_features=4, n_informative=2, n_redundant=0, random_state=0, shuffle=False)
```
3.划分训练集和测试集
```
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
```
4.构建随机森林模型
```
clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0)
clf.fit(X_train, y_train)
```
5.评估模型性能
```
print("Accuracy on training set: {:.3f}".format(clf.score(X_train, y_train)))
print("Accuracy on test set: {:.3f}".format(clf.score(X_test, y_test)))
```
6.使用模型进行预测
```
y_pred = clf.predict(X_test)
```
相关推荐
![](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)