随机森林预测分类python代码
时间: 2023-09-11 17:09:47 浏览: 44
下面是使用随机森林进行分类预测的 Python 代码示例:
```python
# 导入需要的库
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
# 读取数据
data = pd.read_csv('data.csv')
# 分离特征和目标变量
X = data.drop('target', axis=1)
y = data['target']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建随机森林分类器模型
rf_model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
# 在训练集上训练模型
rf_model.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = rf_model.predict(X_test)
# 输出模型的准确率
accuracy = rf_model.score(X_test, y_test)
print('模型的准确率为:', accuracy)
```
其中,`data.csv` 是包含了特征和目标变量的数据集,`X` 是特征矩阵,`y` 是目标变量向量,`train_test_split` 函数用于划分训练集和测试集,`RandomForestClassifier` 类用于创建随机森林分类器模型,`fit` 方法用于在训练集上训练模型,`predict` 方法用于在测试集上进行预测,`score` 方法用于计算模型在测试集上的准确率。