随机森林的预测python
时间: 2024-10-09 11:15:39 浏览: 20
基于python 实现随机森林的气温预测
随机森林是一种集成学习方法,它由许多决策树组成,每个树对数据进行独立预测,然后将它们的结果汇总得出最终结果。在Python中,可以使用sklearn库来实现随机森林模型,步骤大致如下:
1. 导入必要的库:
```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import pandas as pd
```
2. 加载数据集并预处理:
```python
data = pd.read_csv('your_data.csv') # 替换为实际文件路径
X = data.drop('target_column', axis=1) # 特征列
y = data['target_column'] # 目标变量
# 数据分割(训练集和测试集)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
3. 创建随机森林模型并训练:
```python
model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
model.fit(X_train, y_train)
```
4. 预测和评估:
```python
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
阅读全文