![](https://csdnimg.cn/release/download_crawler_static/89319813/bg1.jpg)
随机森林是一种集成学习方法,它通过构建多个决策树并组合它们的输出来改进预测性能。
在 Python 中,你可以使用 scikit-learn 库来构建和使用随机森林模型。以下是一个简单的随
机森林分类器的示例代码:
python
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
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)
# 创建随机森林分类器
# 参数 n_estimators 指定了要构建的树的数量
rf_classifier = RandomForestClassifier(n_estimators=100, random_state=42)
# 使用训练数据拟合模型
rf_classifier.fit(X_train, y_train)
# 对测试集进行预测
y_pred = rf_classifier.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
这个示例代码首先加载了鸢尾花数据集,然后将其划分为训练集和测试集。接着,它创建了
一个随机森林分类器,并使用训练数据拟合了模型。最后,它使用模型对测试集进行了预测,
并计算了预测的准确率。
注意,随机森林分类器的性能可能会受到其参数的影响,如 n_estimators(树的数量)、
max_depth(树的最大深度)等。在实际应用中,你可能需要调整这些参数以优化模型的性
能。