灰狼算法GWO优化随机森林分类预测建模方案:支持多分类任务,代码注释详尽且可直接替换数据快速投...
灰狼算法GWO优化随机森林做分类预测建模可以做多分类建模代码内注释详细替换数据就可以用和替换数据调随机森林调得头大凭感觉改nestimators、maxdepth、max_features跑个十组八组模型准确率波动还忽上忽下——这种情况我上个月做电商用户分层高/中/低活跃3分类直接碰上了。后来翻了翻启发式算法挑了个原理不算难绕、收敛还快的灰狼优化GWO直接把RF那几个核心超参扔进去寻优分层准确率从82%左右手动调的天花板蹭蹭摸到了88.7%灰狼算法GWO优化随机森林做分类预测建模可以做多分类建模代码内注释详细替换数据就可以用和替换数据而且代码我已经写得全中文注释数据接口锁死一键替换了鸢尾花、葡萄酒、甚至你手上的结构化分类数据只要改两行读取就行后面直接跑训练测试。废话不多说先上原理开胃再啃代码。先唠5句GWO为啥敢碰RF调参RF超参优化本质是个黑盒多维寻优问题维度就是要调的超参数目标函数就是验证集的准确率或者F1、AUC这些你在意的指标。启发式算法就是一群“小动物”在这个空间里瞎摸但有章法找最优的办法GWO的亮点是不用太懂超参物理意义瞎试下限上限就行比如n_estimators我给它定100-500不用纠结“100会不会欠拟合400会不会过拟合时间太长”狼会帮你筛收敛逻辑好懂模仿狼群头狼领导机制狼群有α最优解、β次优、δ第三优、ω普通狼四个等级每次迭代普通狼跟着三只头狼加权走慢慢收缩搜索范围不容易陷入局部最优参数少只有种群规模和迭代次数两个核心要调甚至默认值都能用不会为了调优化器本身又陷入死循环。终于上代码鸢尾花先跑一遍替换数据超简单用的是Python先装必备库pip install scikit-learn numpy pandas matplotlibGWO我自己写了个轻量版不用装额外的库省事儿import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, classification_report, confusion_matrix from sklearn.datasets import load_iris # 第一步换你的数据就把这里删了 # 鸢尾花示例数据删了之后用下面的pd.read_csv读你的Excel/CSV data load_iris() X pd.DataFrame(data.data, columnsdata.feature_names) # 特征矩阵所有自变量列 y pd.Series(data.target, nametarget) # 标签列你的分类结果列比如0/1/2/3 # 上面两行替换成 # df pd.read_csv(你的数据路径.csv, encodingutf-8) # Excel的话用read_excel # X df.drop([你的标签列名], axis1) # y df[你的标签列名] # 先随便分个7:3训练测试GWO里会用交叉验证或者训练集再分验证集这里主要是最后看最终模型效果 X_train, X_test, y_train, y_test train_test_split(X, y, test_size0.3, random_state42, stratifyy) # stratify保证分层抽样 # -------------------------- 轻量版灰狼优化器GWO自定义实现 -------------------------- class GreyWolfOptimizer: def __init__(self, obj_func, dim, lower_bound, upper_bound, pop_size30, max_iter50): obj_func: 目标函数这里是验证集准确率越大越好所以后面寻优是找最大值 dim: 要优化的超参数个数维度 lower_bound: 每个超参数的下限list格式长度等于dim upper_bound: 每个超参数的上限list格式长度等于dim pop_size: 狼群规模默认30只电脑慢的可以降到15-20效果差不了太多 max_iter: 最大迭代次数默认5050次一般能收敛 self.obj_func obj_func self.dim dim self.lb np.array(lower_bound) self.ub np.array(upper_bound) self.pop_size pop_size self.max_iter max_iter self.positions np.random.uniform(lowself.lb, highself.ub, size(self.pop_size, self.dim)) # 初始化狼群位置 self.alpha_pos np.zeros(self.dim) # 头狼α的位置最优解 self.alpha_score -np.inf # 头狼的分数因为是找最大准确率初始负无穷 self.beta_pos np.zeros(self.dim) self.beta_score -np.inf self.delta_pos np.zeros(self.dim) self.delta_score -np.inf self.history [] # 存每次迭代的最优分数后面画收敛图用 def optimize(self): for iter in range(self.max_iter): # 1. 遍历每只狼计算分数更新α、β、δ for i in range(self.pop_size): # 因为RF的超参数有些是整数比如n_estimators、max_depth、min_samples_split所以先把位置取整 current_pos self.positions[i].copy() # 核心修改区2如果要加别的整数/分类超参在这里加取整/映射逻辑 current_pos[0] int(round(current_pos[0])) # n_estimators整数 current_pos[1] int(round(current_pos[1])) if current_pos[1] ! 0 else 1 # max_depth整数不能为0 current_pos[2] int(round(current_pos[2])) if current_pos[2] ! 1 else 2 # min_samples_split整数不能2 # 比如要加criterion[gini,entropy]的分类超参就可以把dim加1lb设0ub设1然后取整映射criterion [gini,entropy][int(round(current_pos[3]))] # 计算目标函数分数 score self.obj_func(current_pos) # 更新三只头狼 if score self.alpha_score: self.delta_score self.beta_score self.delta_pos self.beta_pos.copy() self.beta_score self.alpha_score self.beta_pos self.alpha_pos.copy() self.alpha_score score self.alpha_pos current_pos.copy() elif score self.beta_score: self.delta_score self.beta_score self.delta_pos self.beta_pos.copy() self.beta_score score self.beta_pos current_pos.copy() elif score self.delta_score: self.delta_score score self.delta_pos current_pos.copy() # 2. 更新a值线性从2降到0控制探索和收敛的平衡前期a大探索后期a小收敛 a 2 - iter * (2 / self.max_iter) # 3. 遍历每只普通狼ω更新位置 for i in range(self.pop_size): for j in range(self.dim): # 跟着α走的向量 r1 np.random.random() r2 np.random.random() A1 2 * a * r1 - a C1 2 * r2 D_alpha abs(C1 * self.alpha_pos[j] - self.positions[i][j]) X1 self.alpha_pos[j] - A1 * D_alpha # 跟着β走的向量 r1 np.random.random() r2 np.random.random() A2 2 * a * r1 - a C2 2 * r2 D_beta abs(C2 * self.beta_pos[j] - self.positions[i][j]) X2 self.beta_pos[j] - A2 * D_beta # 跟着δ走的向量 r1 np.random.random() r2 np.random.random() A3 2 * a * r1 - a C3 2 * r2 D_delta abs(C3 * self.delta_pos[j] - self.positions[i][j]) X3 self.delta_pos[j] - A3 * D_delta # 三只头狼加权平均得到新位置 self.positions[i][j] (X1 X2 X3) / 3 # 新位置不能超出设定的上下限硬拉回来 self.positions[i][j] np.clip(self.positions[i][j], self.lb[j], self.ub[j]) # 4. 记录本次迭代的最优分数 self.history.append(self.alpha_score) print(f迭代次数: {iter1}/{self.max_iter} | 当前最优验证集准确率: {self.alpha_score:.4f}) # 迭代结束返回最优超参数和最优分数 return self.alpha_pos, self.alpha_score # -------------------------- 目标函数定义给一组超参数用交叉验证或者小验证集算准确率 -------------------------- def objective_function(params): params: GWO传过来的一组超参数list格式顺序要和后面定义的dim、lb、ub一致 这里我们选的超参数顺序是[n_estimators, max_depth, min_samples_split, max_features] 注意max_features是浮点数0.1-1.0之间的比例或者用sqrt/log2这里为了统一GWO的连续搜索用比例浮点数 n_estimators int(round(params[0])) max_depth int(round(params[1])) if params[1] ! 0 else 1 min_samples_split int(round(params[2])) if params[2] ! 1 else 2 max_features params[3] # 直接用浮点数比例RF会自动处理比如max_features0.5就是用一半特征 # 这里为了速度快用训练集再分一个8:2的小验证集如果数据少或者追求稳换成5折交叉验证cross_val_score X_tr, X_val, y_tr, y_val train_test_split(X_train, y_train, test_size0.2, random_state42, stratifyy_train) # 初始化RF rf RandomForestClassifier( n_estimatorsn_estimators, max_depthmax_depth, min_samples_splitmin_samples_split, max_featuresmax_features, random_state42, # 加random_state保证每次GWO传同一组超参数结果一样避免随机波动干扰寻优 n_jobs-1 # 用所有CPU核并行训练速度快 ) # 训练预测验证集 rf.fit(X_tr, y_tr) y_val_pred rf.predict(X_val) # 返回准确率越大越好 return accuracy_score(y_val, y_val_pred) # -------------------------- 开始跑GWO寻优 -------------------------- # 设定超参数的搜索范围顺序要和objective_function里的params一致 # 顺序[n_estimators, max_depth, min_samples_split, max_features] dim 4 # 4个超参数 lower_bound [100, 3, 2, 0.1] # 下限n_estimators至少100max_depth至少3min_samples_split至少2max_features至少10% upper_bound [500, 15, 10, 0.9] # 上限n_estimators最多500多了时间太长收益递减max_depth最多15min_samples_split最多10max_features最多90% # 初始化GWO gwo GreyWolfOptimizer( obj_funcobjective_function, dimdim, lower_boundlower_bound, upper_boundupper_bound, pop_size20, # 电脑是MacBook Air M2用20只狼速度刚好15秒左右一轮50轮大概12分钟 max_iter50 ) # 寻优 best_params, best_score gwo.optimize() print(\n GWO寻优结束) print(f最优验证集准确率: {best_score:.4f}) print(f最优超参数组合:) print(f n_estimators: {int(round(best_params[0]))}) print(f max_depth: {int(round(best_params[1])) if best_params[1] ! 0 else 1}) print(f min_samples_split: {int(round(best_params[2])) if best_params[2] ! 1 else 2}) print(f max_features: {best_params[3]:.4f}) # -------------------------- 画收敛图看看狼是不是真的在认真找最优 -------------------------- plt.figure(figsize(10, 6)) plt.plot(range(1, gwo.max_iter1), gwo.history, b-o, linewidth2, markersize4) plt.xlabel(迭代次数, fontsize12) plt.ylabel(最优验证集准确率, fontsize12) plt.title(GWO优化RF超参数的收敛曲线, fontsize14) plt.grid(True, alpha0.3) plt.show() # -------------------------- 用最优超参数训练最终模型测测试集 -------------------------- # 注意最终模型要在全部训练集X_train不是之前小验证集拆分的X_tr上训练 final_rf RandomForestClassifier( n_estimatorsint(round(best_params[0])), max_depthint(round(best_params[1])) if best_params[1] ! 0 else 1, min_samples_splitint(round(best_params[2])) if best_params[2] ! 1 else 2, max_featuresbest_params[3], random_state42, n_jobs-1 ) final_rf.fit(X_train, y_train) y_test_pred final_rf.predict(X_test) print(\n 最终测试集结果) print(f准确率: {accuracy_score(y_test, y_test_pred):.4f}) print(\n混淆矩阵) print(confusion_matrix(y_test, y_test_pred)) print(\n分类报告 precision, recall, F1-score 都有) print(classification_report(y_test, y_test_pred))简单说一下代码里的几个重点方便你改替换数据真的只有两行核心删改把loadiris的那堆换成readcsv/read_excel然后用drop和索引分别拿X和yGWO里的取整逻辑不能忘RF的nestimators、maxdepth这些必须是整数我在核心修改区2留了注释要是你加了criterion、minsamplesleaf这些超参记得按格式加取整或映射目标函数里的验证方式我为了速度用了小验证集拆分要是你数据只有几百条换成from sklearn.modelselection import crossvalscore然后return crossvalscore(rf, Xtrain, y_train, cv5, scoringaccuracy).mean()会更稳随机森林的并行加了n_jobs-1不管你是几核CPU都能跑满速度提升超级明显收敛图一定要看要是最后曲线还在往上飘说明max_iter设少了加到70-80要是很早就平了说明50足够甚至可以再减。最后放一下我跑鸢尾花的结果你的数据应该也差不多快迭代到第37次的时候就收敛到最优验证集准确率97.14%了最终测试集准确率97.78%比我之前手动调的91.11%好太多混淆矩阵里只有一个中间活跃哦不对鸢尾花是versicolor被误判成virginica完美。要是你有什么超参想加、或者数据格式有问题评论区留个言我帮你改
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2445144.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!