news 2026/8/16 3:28:51

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
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()
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/8/13 22:29:22

LeetCode 17. 电话号码的字母组合 | 深度解析 + 高效回溯实现

一、题目介绍1.1 题目描述给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。数字到字母的映射与电话按键一致(1 不对应任何字母):2: abc3: def4: ghi5: jkl6: mno7: pqrs8: tuv9: wxyz1.2…

作者头像 李华
网站建设 2026/8/16 7:40:40

自动迁移旧 TabView 新 Tab API:从痛点到实战可复用代码模版

网罗开发(小红书、快手、视频号同名)大家好,我是 展菲,目前在上市企业从事人工智能项目研发管理工作,平时热衷于分享各种编程领域的软硬技能知识以及前沿技术,包括iOS、前端、Harmony OS、Java、Python等方…

作者头像 李华
网站建设 2026/8/16 3:21:38

写论文软件哪家强?别再只盯 “生成速度”!我们用一份被导师退回 3 次的初稿,实测哪款工具真能帮你改到位

“选题空洞、逻辑混乱、引用不规范、论证无力”—— 这是经管类本科生小周的论文《数字经济赋能乡村振兴》收到的 3 次退稿核心意见。这份初稿和多数学生的作品一样:框架松散,章节衔接生硬;文献堆砌无分析,30% 引用无法检索&#…

作者头像 李华
网站建设 2026/8/15 20:34:16

AI论文工具怎么选?6款详细对比+2025年推荐清单

毕业季近在眼前,论文查重和AI痕迹检测的压力让你头疼不已?别慌!作为亲身测试过多款AI论文工具的博主,我明白那种选择恐惧症——工具太多,功能眼花缭乱,选不对就白费功夫。今天,我就带大家走进20…

作者头像 李华
网站建设 2026/8/16 3:34:15

高性能音频处理:深入解析无锁环形缓冲区 (Lock-Free Ring Buffer)

高性能音频处理:深入解析无锁环形缓冲区 (Lock-Free Ring Buffer) 在实时音频处理领域,性能和低延迟是至关重要的。传统的互斥锁(Mutex)虽然能保证线程安全,但在高并发或实时性要求极高的场景下,锁竞争导致…

作者头像 李华