2026/6/11 21:21:13
网站建设
项目流程
网站机房建设图,打开链接的网站,备案的网站程序上传,桂林北站官网浙大疏锦行
学习目标
三种主流调参方法#xff1a;
网格搜索#xff08;GridSearchCV#xff09;#xff1a;穷举式搜索 穷举所有参数组合、能找到最优解、计算量大#xff0c;维度灾难、 参数空间小#xff0c;计算资源充足
随机搜索#xff08;RandomizedSearchCV…浙大疏锦行学习目标三种主流调参方法网格搜索GridSearchCV穷举式搜索穷举所有参数组合、能找到最优解、计算量大维度灾难、 参数空间小计算资源充足随机搜索RandomizedSearchCV随机采样---只是一种思想随机采样参数组合、效率高于网格搜索 、可能错过最优解、参数空间大中等计算资源贝叶斯优化BayesSearchCV智能优化基于概率模型智能搜索、高效收敛快 、实现复杂 、 参数空间大计算资源有限实战随机森林调参1.基线模型# --- 1. 默认参数的随机森林 --- # 评估基准模型这里确实不需要验证集 print(--- 1. 默认参数随机森林 (训练集 - 测试集) ---) import time # 这里介绍一个新的库time库主要用于时间相关的操作因为调参需要很长时间记录下会帮助后人知道大概的时长 start_time time.time() # 记录开始时间 rf_model RandomForestClassifier(random_state42) rf_model.fit(X_train, y_train) # 在训练集上训练 rf_pred rf_model.predict(X_test) # 在测试集上预测 end_time time.time() # 记录结束时间 print(f训练与预测耗时: {end_time - start_time:.4f} 秒) print(\n默认随机森林 在测试集上的分类报告) print(classification_report(y_test, rf_pred)) print(默认随机森林 在测试集上的混淆矩阵) print(confusion_matrix(y_test, rf_pred))2.网格搜索优化# --- 2. 网格搜索优化随机森林 --- print(\n--- 2. 网格搜索优化随机森林 (训练集 - 测试集) ---) from sklearn.model_selection import GridSearchCV # 定义要搜索的参数网格 param_grid { n_estimators: [50, 100, 200], max_depth: [None, 10, 20, 30], min_samples_split: [2, 5, 10], min_samples_leaf: [1, 2, 4] } # 创建网格搜索对象 grid_search GridSearchCV(estimatorRandomForestClassifier(random_state42), # 随机森林分类器 param_gridparam_grid, # 参数网格 cv5, # 5折交叉验证 n_jobs-1, # 使用所有可用的CPU核心进行并行计算 scoringaccuracy) # 使用准确率作为评分标准 start_time time.time() # 在训练集上进行网格搜索 grid_search.fit(X_train, y_train) # 在训练集上训练模型实例化和训练的方法都被封装在这个网格搜索对象里了 end_time time.time() print(f网格搜索耗时: {end_time - start_time:.4f} 秒) print(最佳参数: , grid_search.best_params_) #best_params_属性返回最佳参数组合 # 使用最佳参数的模型进行预测 best_model grid_search.best_estimator_ # 获取最佳模型 best_pred best_model.predict(X_test) # 在测试集上进行预测 print(\n网格搜索优化后的随机森林 在测试集上的分类报告) print(classification_report(y_test, best_pred)) print(网格搜索优化后的随机森林 在测试集上的混淆矩阵) print(confusion_matrix(y_test, best_pred))3.随机搜索优化# --- 2. 随机搜索优化随机森林 --- print(\n--- 2. 随机搜索优化随机森林 (训练集 - 测试集) ---) from sklearn.model_selection import RandomizedSearchCV from scipy.stats import randint # 定义参数分布使用分布而非固定列表 param_distributions { n_estimators: randint(50, 200), # 从50-200之间随机整数 max_depth: [None, 10, 20, 30], # 也可以用固定列表 min_samples_split: randint(2, 11), # 从2-10之间随机整数 min_samples_leaf: randint(1, 5) # 从1-4之间随机整数 } # 创建随机搜索对象 random_search RandomizedSearchCV( estimatorRandomForestClassifier(random_state42), param_distributionsparam_distributions, n_iter50, # 随机采样50次可调整 cv5, # 5折交叉验证 n_jobs-1, # 使用所有CPU核心 scoringaccuracy, random_state42 # 保证结果可复现 ) start_time time.time() # 在训练集上进行随机搜索 random_search.fit(X_train, y_train) end_time time.time() print(f随机搜索耗时: {end_time - start_time:.4f} 秒) print(最佳参数: , random_search.best_params_) # 使用最佳参数的模型进行预测 best_model_random random_search.best_estimator_ best_pred_random best_model_random.predict(X_test) print(\n随机搜索优化后的随机森林 在测试集上的分类报告) print(classification_report(y_test, best_pred_random)) print(随机搜索优化后的随机森林 在测试集上的混淆矩阵) print(confusion_matrix(y_test, best_pred_random))4.贝叶斯优化# pip install scikit-optimize -i https://pypi.tuna.tsinghua.edu.cn/simple # --- 2. 贝叶斯优化随机森林 --- print(\n--- 2. 贝叶斯优化随机森林 (训练集 - 测试集) ---) from skopt import BayesSearchCV from skopt.space import Integer from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import classification_report, confusion_matrix import time # 定义要搜索的参数空间 search_space { n_estimators: Integer(50, 200), max_depth: Integer(10, 30), min_samples_split: Integer(2, 10), min_samples_leaf: Integer(1, 4) } # 创建贝叶斯优化搜索对象 bayes_search BayesSearchCV( estimatorRandomForestClassifier(random_state42), search_spacessearch_space, n_iter32, # 迭代次数可根据需要调整 cv5, # 5折交叉验证这个参数是必须的不能设置为1否则就是在训练集上做预测了 n_jobs-1, scoringaccuracy ) start_time time.time() # 在训练集上进行贝叶斯优化搜索 bayes_search.fit(X_train, y_train) end_time time.time() print(f贝叶斯优化耗时: {end_time - start_time:.4f} 秒) print(最佳参数: , bayes_search.best_params_) # 使用最佳参数的模型进行预测 best_model bayes_search.best_estimator_ best_pred best_model.predict(X_test) print(\n贝叶斯优化后的随机森林 在测试集上的分类报告) print(classification_report(y_test, best_pred)) print(贝叶斯优化后的随机森林 在测试集上的混淆矩阵) print(confusion_matrix(y_test, best_pred))5.贝叶斯优化进阶# pip install bayesian-optimization -i https://mirrors.aliyun.com/pypi/simple/ # --- 2. 贝叶斯优化随机森林 --- print(\n--- 2. 贝叶斯优化随机森林 (训练集 - 测试集) ---) from bayes_opt import BayesianOptimization from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score from sklearn.metrics import classification_report, confusion_matrix import time import numpy as np # 假设 X_train, y_train, X_test, y_test 已经定义好 # 定义目标函数这里使用交叉验证来评估模型性能 def rf_eval(n_estimators, max_depth, min_samples_split, min_samples_leaf): n_estimators int(n_estimators) max_depth int(max_depth) min_samples_split int(min_samples_split) min_samples_leaf int(min_samples_leaf) model RandomForestClassifier( n_estimatorsn_estimators, max_depthmax_depth, min_samples_splitmin_samples_split, min_samples_leafmin_samples_leaf, random_state42 ) scores cross_val_score(model, X_train, y_train, cv5, scoringaccuracy) return np.mean(scores) # 定义要搜索的参数空间 pbounds_rf { n_estimators: (50, 200), max_depth: (10, 30), min_samples_split: (2, 10), min_samples_leaf: (1, 4) } # 创建贝叶斯优化对象设置 verbose2 显示详细迭代信息 optimizer_rf BayesianOptimization( frf_eval, # 目标函数 pboundspbounds_rf, # 参数空间 random_state42, # 随机种子 verbose2 # 显示详细迭代信息 ) start_time time.time() # 开始贝叶斯优化 optimizer_rf.maximize( init_points5, # 初始随机采样点数 n_iter32 # 迭代次数 ) end_time time.time() print(f贝叶斯优化耗时: {end_time - start_time:.4f} 秒) print(最佳参数: , optimizer_rf.max[params]) # 使用最佳参数的模型进行预测 best_params optimizer_rf.max[params] best_model RandomForestClassifier( n_estimatorsint(best_params[n_estimators]), max_depthint(best_params[max_depth]), min_samples_splitint(best_params[min_samples_split]), min_samples_leafint(best_params[min_samples_leaf]), random_state42 ) best_model.fit(X_train, y_train) best_pred best_model.predict(X_test) print(\n贝叶斯优化后的随机森林 在测试集上的分类报告) print(classification_report(y_test, best_pred)) print(贝叶斯优化后的随机森林 在测试集上的混淆矩阵) print(confusion_matrix(y_test, best_pred))