在 Python 中,你可以使用 scikit-learn 库来实现随机森林算法。以下是一个简单的示例,说
明如何使用随机森林进行分类任务:
python
# 导入必要的库
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
# 加载数据集(这里以 iris 数据集为例)
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(树的数量)和其他参数
clf = RandomForestClassifier(n_estimators=100, 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}')
在这个示例中,我们使用了内置的 iris 数据集,这是一个多类分类问题的标准数据集。我们
将数据集划分为训练集和测试集,并使用随机森林分类器进行训练。然后,我们在测试集上
进行预测,并计算了模型的准确率。
你可以根据自己的需要调整 RandomForestClassifier 的参数,例如 n_estimators(树的数
量)、max_depth(树的最大深度)等。这些参数可以影响模型的性能和过拟合/欠拟合的程
度。