随机森林多分类模型代码
时间: 2023-09-17 08:06:27 浏览: 34
下面是一个使用随机森林多分类模型的 Python 代码示例:
```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 创建一个样本数据集
X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_classes=3, random_state=42)
# 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, 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("Accuracy: {:.2f}%".format(accuracy*100))
```
该代码使用 `make_classification` 函数生成一个具有 10 个特征和 3 个类别的样本数据集。然后,使用 `train_test_split` 函数将数据集划分为训练集和测试集。接下来,使用 `RandomForestClassifier` 类创建一个随机森林分类器,并使用训练集进行训练。最后,使用测试集进行预测,并计算模型的准确率。