网站方案建设书模板,手机兼职有哪些,淘客招商网站选品库建设,没有做icp备案的网站笔记和作业使用bayes_opt库的流程1.# 定义目标函数def knn_cv_score(n_neighbors, weights, metric):输入KNN参数#xff0c;返回交叉验证平均准确率参数说明#xff1a;- n_neighbors: 近邻数#xff08;整数#xff0c;贝叶斯优化会自动处理浮点转整数…笔记和作业使用bayes_opt库的流程1.# 定义目标函数def knn_cv_score(n_neighbors, weights, metric): 输入KNN参数返回交叉验证平均准确率 参数说明 - n_neighbors: 近邻数整数贝叶斯优化会自动处理浮点转整数 - weights: 权重方式0uniform1distance - metric: 距离度量0euclidean1manhattan2chebyshev # 将连续参数转换为整数(贝叶斯优化默认传浮点需转为KNN要求的类型) n_neighbors int(round(n_neighbors)) # 近邻数必须是整数 weights uniform if weights 0.5 else distance # 类别参数映射 metric_map {0: euclidean, 1: manhattan, 2: chebyshev} metric metric_map[int(round(metric))] # 创建模型 knn KNeighborsClassifier( n_neighborsn_neighbors, weightsweights, metricmetric, n_jobs-1 # 并行计算加速 ) # 5折交叉验证返回平均准确率 cv_scores cross_val_score(knn, X_train, y_train, cv5, scoringaccuracy) return cv_scores.mean()2.# 定义参数搜索空间# 注意贝叶斯优化仅支持连续型参数类别型需映射为数值区间 pbounds { n_neighbors: (3, 30), # 近邻数范围3~30 weights: (0, 1), # 0→uniform1→distance metric: (0, 2) # 0→euclidean1→manhattan2→chebyshev } 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}))3.# 创建贝叶斯优化器优化的过程已经被这个对象封装了# 初始化优化器verbose2打印迭代过程 optimizer BayesianOptimization( fknn_cv_score, pboundspbounds, random_state42, verbose2 ) start_time time.time() # 开始优化n_iter迭代次数init_points初始随机搜索点数 # init_points越多初始探索越充分n_iter越多优化越精细 optimizer.maximize(init_points5, n_iter20) end_time time.time() print(f优化完成总耗时: {end_time - start_time:.2f} 秒.center(80))4.# 提取所有迭代的结果terations [] scores [] for i, res in enumerate(optimizer.res): # res包含每次迭代的结果index从0开始 iterations.append(i 1) # 迭代次数从1开始 scores.append(res[target]) # 提取得分5.# 计算累计最优值best_scores [] current_best -np.inf # 初始化为负无穷大 for score in scores: if score current_best: # 检查当前得分是否打破历史记录 current_best score best_scores.append(current_best)6.# 绘制优化轨迹# 左图每次迭代的得分 ax1.plot(iterations, scores, o-, label每次迭代得分, alpha0.7, markersize6) ax1.plot(iterations, best_scores, r--, label累计最优得分, linewidth2) ax1.axhline(yoptimizer.max[target], colorgreen, linestyle:, labelf最终最优: {optimizer.max[target]:.4f}) # axhline绘制水平线 ax1.set_xlabel(迭代次数, fontsize12) ax1.set_ylabel(准确率, fontsize12) ax1.set_title(贝叶斯优化收敛曲线 (超大空间100次迭代), fontsize14, fontweightbold) ax1.legend() ax1.grid(True, alpha0.3) # 右图初始探索 vs 贝叶斯优化 init_points 20 # 更新为20 ax2.plot(iterations[:init_points], scores[:init_points], bo-, labelf随机探索 (前{init_points}次), markersize8, alpha0.7) ax2.plot(iterations[init_points:], scores[init_points:], go-, labelf贝叶斯优化 (后{len(iterations)-init_points}次), markersize8, alpha0.7) ax2.axvline(xinit_points, colorred, linestyle--, alpha0.5, label探索→利用) # axvline绘制垂直线 ax2.set_xlabel(迭代次数, fontsize12) ax2.set_ylabel(准确率, fontsize12) ax2.set_title(探索阶段 vs 利用阶段, fontsize14, fontweightbold) ax2.legend() ax2.grid(True, alpha0.3) plt.tight_layout() plt.show()