当前位置: 首页 > news >正文

Day12 贝叶斯优化可视化和随机森林的解读

@浙大疏锦行

一.元组:

1. 有序:可以通过索引取出来元素

2. 不可变,不可修改

3. 可迭代、可切片

创建元组:

# 创建元祖 # 原始元组:(姓名, 年龄, 成绩) old_tuple = ("张三", 25, 92.5) print(f"原始元组: {old_tuple}") print(f"原始类型: {type(old_tuple)}")

修改元组:

# 1. 转换为列表 (List) temp_list = list(old_tuple) print(f"\n转换为列表: {temp_list}") print(f"列表类型: {type(temp_list)}") # 2. 修改列表中的元素(列表是可变的) # 索引 1 是年龄 temp_list[1] = 26 print(f"修改后的列表: {temp_list}") # 3. 转换回元组 (Tuple) new_tuple = tuple(temp_list) print(f"\n转换回元组: {new_tuple}") print(f"最终类型: {type(new_tuple)}") print(f"原元组 (未变): {old_tuple}") # 原始元组并未被修改 # 验证修改结果 print(f"新元组的年龄: {new_tuple[1]}")

二、字典的items方法

my_dict_simple = {'A': 10, 'B': 20, 'C': 30} # 1. my_dict_simple.items() 返回 ('A', 10), ('B', 20) 等 (键, 值) 元组 # 2. enumerate 为这些元组添加索引 # 3. 循环中用 index, (key, value) 进行两次解包 for index, (key, value) in enumerate(my_dict_simple.items()): # 键和值通过解包直接获得,无需额外查表 print(f"索引: {index}, 键: {key}, 对应值: {value}")

三、贝叶斯优化可视化

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 # 定义目标函数 def rf_eval(n_estimators, max_depth, min_samples_split, min_samples_leaf, max_features): """ 目标函数:评估随机森林在给定参数下的性能 BayesianOptimization 会最大化这个函数的返回值 参数说明: - n_estimators: 树的数量(越多越好,但会增加计算时间) - max_depth: 树的最大深度(太浅欠拟合,太深过拟合) - min_samples_split: 分裂所需最小样本数(控制树的生长) - min_samples_leaf: 叶节点最小样本数(防止过拟合) - max_features: 特征采样比例(增加随机性,防止过拟合) """ # 将连续参数转换为整数 n_estimators = int(n_estimators) max_depth = int(max_depth) min_samples_split = int(min_samples_split) min_samples_leaf = int(min_samples_leaf) # max_features 保持浮点数 # 创建模型 model = RandomForestClassifier( n_estimators=n_estimators, max_depth=max_depth, min_samples_split=min_samples_split, min_samples_leaf=min_samples_leaf, max_features=max_features, random_state=42, n_jobs=-1 ) # 5折交叉验证 scores = cross_val_score(model, X_train, y_train, cv=5, scoring='accuracy') return np.mean(scores) # 定义参数搜索空间(扩大10倍!超大搜索空间) pbounds = { 'n_estimators': (10, 3000), # 从10到3000棵树 'max_depth': (3, 500), # 从3到500 'min_samples_split': (2, 200), # 从2到200 'min_samples_leaf': (1, 100), # 从1到100 'max_features': (0.1, 1.0) # 从10%到100% } for param, (low, high) in pbounds.items(): # items方法返回字典的键值对 range_size = high - low print(f" {param:20s}: [{low:7.1f}, {high:7.1f}] (范围: {range_size:7.1f})")
# 提取所有迭代的结果 iterations = [] scores = [] for i, res in enumerate(optimizer.res): # res包含每次迭代的结果,index从0开始 iterations.append(i + 1) # 迭代次数从1开始 scores.append(res['target']) # 提取得分 # 计算累计最优值 best_scores = [] current_best = -np.inf # 初始化为负无穷大 for score in scores: if score > current_best: # 检查当前得分是否打破历史记录 current_best = score best_scores.append(current_best) # 绘制优化轨迹 fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 5)) # 创建1行2列的子图 # 左图:每次迭代的得分 ax1.plot(iterations, scores, 'o-', label='每次迭代得分', alpha=0.7, markersize=6) ax1.plot(iterations, best_scores, 'r--', label='累计最优得分', linewidth=2) ax1.axhline(y=optimizer.max['target'], color='green', linestyle=':', label=f'最终最优: {optimizer.max["target"]:.4f}') # axhline绘制水平线 ax1.set_xlabel('迭代次数', fontsize=12) ax1.set_ylabel('准确率', fontsize=12) ax1.set_title('贝叶斯优化收敛曲线 (超大空间100次迭代)', fontsize=14, fontweight='bold') ax1.legend() ax1.grid(True, alpha=0.3) # 右图:初始探索 vs 贝叶斯优化 init_points = 20 # 更新为20 ax2.plot(iterations[:init_points], scores[:init_points], 'bo-', label=f'随机探索 (前{init_points}次)', markersize=8, alpha=0.7) ax2.plot(iterations[init_points:], scores[init_points:], 'go-', label=f'贝叶斯优化 (后{len(iterations)-init_points}次)', markersize=8, alpha=0.7) ax2.axvline(x=init_points, color='red', linestyle='--', alpha=0.5, label='探索→利用') # axvline绘制垂直线 ax2.set_xlabel('迭代次数', fontsize=12) ax2.set_ylabel('准确率', fontsize=12) ax2.set_title('探索阶段 vs 利用阶段', fontsize=14, fontweight='bold') ax2.legend() ax2.grid(True, alpha=0.3) plt.tight_layout() plt.show()
http://www.cnnetsun.cn/news/42734.html

相关文章:

  • 数据湖不是湖,是江湖:Delta Lake / Iceberg / Hudi 到底该选谁?
  • 告别开题报告模板拼凑!虎贲等考 AI 智能生成,让选题逻辑从模糊想法变身可执行研究计划
  • 【LeetCode刷题】跳跃游戏
  • 鸿蒙PC UI控件库 - PasswordInput 密码输入框详解
  • day37简单的神经网络@浙大疏锦行
  • 【水果识别】基于机器视觉苹果和香蕉的成熟度和大小检测附Matlab代码
  • JAVA的平凡之路——此峰乃是最高峰JVM-附加小菜-04
  • 【电力系统】电力系统优化与控制热液调度附Matlab代码和报告
  • 基于6种最新算法(小龙虾优化算法COA、MSA、RTH、NOA、BFO、SWO)求解机器人路径规划研究附Matlab代码
  • Golang实战:构建综合多头(逾期+反欺诈)风险查询的高性能客户端
  • 【TSP问题】基于蜣螂算法DBO和改进的蜣螂算法FADBO求解旅行商TSP问题(可根据自己的经纬度设置自己想要到达的地区)附Matlab代码
  • 【太阳能学报EI复现】基于粒子群优化算法的风-水电联合优化运行分析附Matlab代码
  • 数据结构:二叉排序树,平衡二叉树,红黑树的介绍
  • 软件复用的分类与实现
  • google服务
  • 进程PCB
  • 实战教程:1小时掌握逆向Unity游戏 (共13课时)
  • [从零构建操作系统]08 函数调用时栈的底层行为解析
  • 力扣hot100:搜索插入位置
  • Java冷启动全指南:从原理到实战优化
  • 测试 - 单元测试(JUnit)
  • C++中多态
  • c++经典练习题-多分支
  • qt为什么转向用cmake放弃qmake
  • 云屋音视频 SDK 凭何成为信创技术困局的 “破局者”?
  • 纯电动汽车动力经济性仿真:Cruise与Simulink联合仿真(2015版),包含BMS、再...
  • 【怎么理解maven中的镜像和仓库?】
  • comsol枝晶生长,沉积模型,包括:典型,形状成核,随机成核,均匀沉积,雪花晶形成过程。 适...
  • 终极指南:Qwen3-30B-A3B多GPU分布式推理完整解决方案
  • 腾讯混元语音驱动数字人技术:重塑动态视频生成新范式