随机森林算法的超参数调优

RandomSearch方法

from sklearn.model_selection import RandomizedSearchCV
 
# 参数配置
# 随机森林中树的个数
n_estimators = [int(x) for x in np.linspace(start = 1, stop = 1000, num = 100)]
# 每一节点考虑切分的节点数
max_features = ['auto', 'sqrt']
# 最大深度
max_depth = [int(x) for x in np.linspace(10, 200, num = 20)]
max_depth.append(None)
# 切分一个节点最小数量
min_samples_split = [2, 5, 10]
# 每一叶子节点最小数量
min_samples_leaf = [1, 2, 4]
# Method of selecting samples for training each tree
bootstrap = [True, False]

#随机种子
random_state=[int(x) for x in np.linspace(10, 200, num = 15)]
random_state.append(None)

# Create the random grid
random_grid = {'random_state':random_state,
               'n_estimators': n_estimators,
               'max_features': max_features,
               'max_depth': max_depth,
               'min_samples_split': min_samples_split,
               'min_samples_leaf': min_samples_leaf,
               'bootstrap': bootstrap}
 
# 模型构建
model_RandomForestRegressor = ensemble.RandomForestRegressor()
# Random search of parameters, using 3 fold cross validation, 
# search across 100 different combinations, and use all available cores
rf_random = RandomizedSearchCV(estimator=model_RandomForestRegressor, param_distributions=random_grid,
                              n_iter = 100, scoring='neg_mean_absolute_error', 
                              cv = 3, verbose=2, random_state=2, n_jobs=-1)
 
# 训练
rf_random.fit(x_train , y_train)

# 给出最佳参数
rf_random.best_params_

GridSearchCV调参

from sklearn.model_selection import GridSearchCV, KFold

# 参数配置
#随机种子
random_state=[int(x) for x in np.linspace(0, 10, num = 1)]
random_state.append(None)

parameters = {'hidden_layer_sizes': [(4,4),(5,5),(6,6),(7,7),(8,8),(10,),(100,),(1000,)],
              'random_state':random_state,
              'activation':['logistic'],
              'solver':['lbfgs'],
              'alpha':[0.05],
              'max_iter':[20000],
              'learning_rate_init':[0.0001]
              }

kfold = KFold(n_splits=10)

ann = MLPRegressor()
# 训练集上进行网格搜索
grid = GridSearchCV(ann, parameters, scoring='r2', cv=kfold)

grid = grid.fit(x_train, y_train)

# 查看最优参数
reg = grid.best_estimator_
print('best score: %f'%grid.best_score_)
print('best parameters:')
for key in parameters.keys():
    print('%s: %d'%(key, reg.get_params()[key]))

print('test score: %f'%reg.score(x_test, y_test))

# 将最优参数传入estimator,获取最优模型
#ann = MLPRegressor(hidden_layer_sizes=reg.get_params()['hidden_layer_sizes'], random_state=reg.get_params()['random_state'])
  • 4
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在MATLAB中进行随机森林超参数调优可以通过使用交叉验证来选择最佳的超参数组合。下面是一个基本的步骤: 1. 准备数据集:将数据集划分为训练集和测试集。 2. 创建随机森林模型:使用fitensemble函数创建一个随机森林分类器或回归器。 3. 定义超参数搜索空间:确定需要调优超参数范围。 4. 设置交叉验证:使用cvpartition函数创建一个交叉验证对象,指定交叉验证的折数。 5. 定义评估指标:选择一个适当的评估指标,例如分类问题可以使用分类准确率或F1分数,回归问题可以使用均方误差或R平方。 6. 超参数调优:使用hyperparameters函数创建一个超参数优化器对象,指定要优化的超参数和搜索范围。 7. 执行超参数搜索:使用tuning函数执行超参数搜索,传入随机森林模型、交叉验证对象、评估指标和超参数优化器对象。 8. 获取最佳超参数组合:使用bestPoint函数获取最佳超参数组合。 9. 重新训练模型:使用最佳超参数组合重新训练随机森林模型。 10. 评估模型性能:使用测试集评估模型的性能。 下面是一个示例代码,演示如何在MATLAB中进行随机森林超参数调优: ```matlab % 准备数据集 load fisheriris X = meas; Y = species; % 创建随机森林模型 model = fitensemble(X, Y, 'Bag', 100, 'Tree', 'Type', 'Classification'); % 定义超参数搜索空间 paramGrid = struct('NumLearningCycles', [50, 100, 200], 'MinLeafSize', [1, 5, 10]); % 设置交叉验证 cv = cvpartition(Y, 'KFold', 5); % 定义评估指标 evalMetric = 'accuracy'; % 超参数调优 opt = hyperparameters('fitensemble'); opt.MaxObjectiveEvaluations = 10; opt.HyperparameterOptimizationOptions.RandomSearchFactor = 3; opt.HyperparameterOptimizationOptions.UseParallel = true; opt.HyperparameterOptimizationOptions.ShowPlots = true; opt.HyperparameterOptimizationOptions.Verbose = 1; % 执行超参数搜索 tunedModel = tuning(model, X, Y, cv, evalMetric, paramGrid, opt); % 获取最佳超参数组合 bestParams = bestPoint(tunedModel); % 重新训练模型 bestModel = fitensemble(X, Y, 'Bag', bestParams.NumLearningCycles, 'Tree', 'Type', 'Classification', 'MinLeafSize', bestParams.MinLeafSize); % 评估模型性能 predY = predict(bestModel, X); accuracy = sum(strcmp(predY, Y)) / numel(Y); disp(['Accuracy: ', num2str(accuracy)]); ``` 这是一个基本的随机森林超参数调优的示例,你可以根据自己的需求进行修改和扩展。同时,你也可以根据具体问题的特点来选择合适的超参数和评估指标。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值