python最优化随机森林子决策树数量
时间: 2023-07-05 12:29:04 浏览: 47
在Python中,可以使用GridSearchCV函数对随机森林模型进行参数调优,从而找到最佳的子决策树数量。具体步骤如下:
1. 导入必要的库和数据集,并将数据集分为训练集和测试集。
``` python
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# 导入数据集
X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=0, random_state=42)
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
```
2. 设置一个子决策树数量的列表,例如[10, 50, 100, 200]。
``` python
# 设置子决策树数量的列表
param_grid = {'n_estimators': [10, 50, 100, 200]}
```
3. 创建随机森林模型,并使用GridSearchCV函数进行参数调优。
``` python
# 创建随机森林模型
rf = RandomForestClassifier()
# 使用交叉验证选择最佳子决策树数量
grid_search = GridSearchCV(rf, param_grid=param_grid, cv=5)
grid_search.fit(X_train, y_train)
```
4. 输出最佳子决策树数量。
``` python
# 输出最佳子决策树数量
print(grid_search.best_params_['n_estimators'])
```
完整代码示例:
``` python
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# 导入数据集
X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=0, random_state=42)
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
# 设置子决策树数量的列表
param_grid = {'n_estimators': [10, 50, 100, 200]}
# 创建随机森林模型
rf = RandomForestClassifier()
# 使用交叉验证选择最佳子决策树数量
grid_search = GridSearchCV(rf, param_grid=param_grid, cv=5)
grid_search.fit(X_train, y_train)
# 输出最佳子决策树数量
print(grid_search.best_params_['n_estimators'])
```
该代码会输出最佳的子决策树数量。