在Python中,使用随机森林算法进行数据分类通常需要以下步骤:
1. 导入必要的库:
import numpy as npimport pandas as pdfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_score
2. 加载数据集:
例如,加载鸢尾花数据集from sklearn.datasets import load_irisiris = load_iris()X = iris.datay = iris.target 移除目标列名
3. 划分训练集和测试集:

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
4. 创建随机森林模型并训练:
clf = RandomForestClassifier(n_estimators=100, random_state=42)clf.fit(X_train, y_train)
5. 预测测试集并评估模型性能:
y_pred = clf.predict(X_test)accuracy = accuracy_score(y_test, y_pred)print("Accuracy:", accuracy)
