随机森林算法模型代码
时间: 2024-10-29 11:06:28 浏览: 23
随机森林是一种集成学习方法,通过构建多个决策树并取其平均结果来进行预测。以下是使用Python的scikit-learn库创建随机森林模型的一个简单示例:
```python
# 导入所需的库
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载数据集(这里以鸢尾花为例)
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)
# 创建随机森林分类器
clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=42)
# 训练模型
clf.fit(X_train, y_train)
# 预测
y_pred = clf.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy * 100:.2f}%")
#
阅读全文