要实现随机森林算法,你可以使用scikit-learn库中的RandomForestClassifier类。下面是一个示例代码:
from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.datasets import load_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) # 创建随机森林分类器 rf = RandomForestClassifier(n_estimators=100, random_state=42) # 在训练集上训练模型 rf.fit(X_train, y_train) # 在测试集上进行预测 y_pred = rf.predict(X_test) # 输出预测结果 print("预测结果:", y_pred) # 输出准确率 accuracy = sum(y_pred == y_test) / len(y_test) print("准确率:", accuracy)
在上面的代码中,我们首先加载了一个经典的鸢尾花数据集。然后使用train_test_split
函数将数据集划分为训练集和测试集。接下来,我们使用RandomForestClassifier
类创建一个随机森林分类器,并设置参数n_estimators
为100,表示森林中树的数量。然后使用训练集对模型进行训练,最后使用测试集进行预测,并计算准确率。