news 2026/6/23 14:07:55

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/6/23 21:29:35

数据湖不是湖,是江湖:Delta Lake / Iceberg / Hudi 到底该选谁?

数据湖不是湖,是江湖:Delta Lake / Iceberg / Hudi 到底该选谁?很多同学一上来就问我一句话灵魂拷问:Echo,Delta、Iceberg、Hudi,我到底该用哪个? 现在不用是不是就“落后”了?说实话…

作者头像 李华
网站建设 2026/6/23 18:51:11

【LeetCode刷题】跳跃游戏

给你一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。判断你是否能够到达最后一个下标,如果可以,返回 true ;否则,返回 false 。示例 1:输入&am…

作者头像 李华
网站建设 2026/6/22 21:24:26

鸿蒙PC UI控件库 - PasswordInput 密码输入框详解

视频地址: https://www.bilibili.com/video/BV1jomdBBE4H/ 📋 目录 概述特性快速开始API 参考使用示例主题配置最佳实践常见问题总结 概述 PasswordInput 是控件库中专用于密码输入的组件,基于 TextInput 扩展而来,支持显示/…

作者头像 李华
网站建设 2026/6/23 18:51:11

day37简单的神经网络@浙大疏锦行

day37简单的神经网络浙大疏锦行 使用 sklearn 的 load_digits 数据集 (8x8 像素的手写数字) 进行 MLP 训练。 import torch import torch.nn as nn import torch.optim as optim from sklearn.datasets import load_digits from sklearn.model_selection import train_test_s…

作者头像 李华