关于randomforest 的参数,挑选 3 个感兴趣的参数,用鸢尾花数据集为例,改变参数、观察 分类结果。
时间: 2024-02-22 12:58:06 浏览: 26
好的,感谢您的提问。关于 RandomForest 模型的参数,以下是三个我认为比较重要的参数:
1. n_estimators:决策树的数量。默认为100。增加这个参数可以增加模型的准确度,但会增加计算时间。
2. max_depth:树的最大深度。默认为None,表示树会一直生长直到叶节点中的每个样本都属于同一个类别或者该叶节点包含少于min_samples_split个样本。增加这个参数可以使模型更准确,但可能会导致过拟合。
3. min_samples_split:节点分裂所需的最小样本数。默认为2。增加这个参数可以使模型变得更加稳定,减少过拟合。
下面我们以鸢尾花数据集为例,来看看如何调整这些参数来观察分类结果。
首先,我们需要导入数据集并将其划分为训练集和测试集:
``` python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)
```
接下来,我们可以使用 RandomForestClassifier 来训练模型,并尝试调整参数:
``` python
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
# 基础模型
rfc = RandomForestClassifier(random_state=42)
rfc.fit(X_train, y_train)
y_pred = rfc.predict(X_test)
print('基础模型准确率:', accuracy_score(y_test, y_pred))
# 调整n_estimators
rfc1 = RandomForestClassifier(n_estimators=200, random_state=42)
rfc1.fit(X_train, y_train)
y_pred1 = rfc1.predict(X_test)
print('增加n_estimators后的准确率:', accuracy_score(y_test, y_pred1))
# 调整max_depth
rfc2 = RandomForestClassifier(max_depth=3, random_state=42)
rfc2.fit(X_train, y_train)
y_pred2 = rfc2.predict(X_test)
print('max_depth=3后的准确率:', accuracy_score(y_test, y_pred2))
# 调整min_samples_split
rfc3 = RandomForestClassifier(min_samples_split=5, random_state=42)
rfc3.fit(X_train, y_train)
y_pred3 = rfc3.predict(X_test)
print('min_samples_split=5后的准确率:', accuracy_score(y_test, y_pred3))
```
执行上述代码后,我们可以看到每个模型在测试集上的准确率。通过比较不同模型的准确率,我们可以选择最佳参数组合来训练模型。