Day12 贝叶斯优化可视化和随机森林的解读
2026/5/11 8:53:14 网站建设 项目流程

@浙大疏锦行

一.元组:

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()

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询