Python中如何修改现有单变量网格搜索函数以支持8个超参数寻优
多变量网格搜索适配实现
先修正现有代码的计算错误
你定义的cost_function_1存在运算逻辑错误:Python中^是按位异或运算符,并非幂运算,求平方需要使用**,修正后的成本函数为:
cost_function_1 = lambda x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8: ( 675 + (x_1-15)**2 + x_1**2 * np.cos(x_1*np.pi) ) + x_2**2 + x_3**2 + x_4**2 + x_5**2 + x_6**2 + x_7**2 + x_8**2
函数改动核心逻辑
原单变量网格搜索逻辑无法适配8变量场景的核心原因有两个:
- 候选集生成逻辑不匹配:单变量场景下只需要1维采样数组,多变量场景下需要生成所有维度的取值笛卡尔积,每个组合为1个长度为8的候选解
- 成本计算逻辑不匹配:原逻辑直接将候选数组整体传入成本函数,既没有将每个候选解拆成对应维度的参数,也没有逐候选计算独立成本
修改后的完整函数实现
def get_best_value(f, candidates): """ Return the candidate that yielded the lowest cost in the function f. :param f: cost function :param candidates: array of shape (n_candidates, n_dims), each row is a set of hyperparameters :return: the best candidate (1D array matching the dimension of candidates) """ # 逐候选计算成本,将每行的8个值解包为独立参数传入成本函数 costs = np.array([f(*cand) for cand in candidates]) # 找到成本最小的候选索引 idx_min = np.argmin(costs) return candidates[idx_min] def run_grid_search_experiment(f, n_trials, X_MIN, X_MAX, n_dims=8): """ Run the experiment for grid search. :param f: cost function that takes n_dims positional arguments :param n_trials: number of grid points sampled per dimension :param X_MIN: lower bound of the search range for each dimension :param X_MAX: upper bound of the search range for each dimension :param n_dims: number of hyperparameter dimensions :return: the best candidate """ # 为每个维度生成等距采样的候选值 per_dim_candidates = [np.linspace(X_MIN, X_MAX, n_trials) for _ in range(n_dims)] # 生成所有维度的笛卡尔积,整理为每行一个候选解的格式 grids = np.meshgrid(*per_dim_candidates, indexing='ij') candidates = np.stack(grids, axis=-1).reshape(-1, n_dims) # 计算并返回最优候选 selected_value = get_best_value(f, candidates) return selected_value
调用方式
和原单变量调用逻辑几乎一致,返回值为长度8的数组,依次对应x1到x8的最优取值:
gs_selected_value = run_grid_search_experiment( cost_function_1, n_trials=10, X_MIN=-10, X_MAX=30, n_dims=8 ) # 拆分出每个变量的最优值 x1_best, x2_best, x3_best, x4_best, x5_best, x6_best, x7_best, x8_best = gs_selected_value
注意事项
- 计算量提示:每个维度采样10个点、共8个维度的总组合数为
10^8 = 100,000,000,Python层逐行循环的计算耗时会比较高,后续可通过向量化改写成本函数提升运行速度 - 扩展兼容性:当前实现默认所有维度的搜索范围、采样密度一致,如需适配不同维度的独立范围/采样数,只需修改
per_dim_candidates为每个维度单独生成的采样数组即可,无需改动核心计算逻辑
内容的提问来源于stack exchange,提问作者vverdic
相关产品推荐
相关产品推荐

