为什么Keras Tuner的hp.Fixed固定超参数与直接使用静态值结果不同
问题原因
核心问题出在超参数的注册顺序逻辑上:
Python的函数参数会在函数调用前完成求值,你调用_param方法时直接把hp.Int('units', 1, 200, step=5)作为默认参数传入,无论config里是否存在对应的固定参数,hp.Int都会先执行,直接把units注册为可搜索的超参数。后续hp.Fixed因为和已注册的超参数同名产生冲突,被调优器直接忽略,最终你设置的固定参数完全不生效,调优器仍然会遍历所有参数取值。
修复方案
调整_param方法的逻辑,仅当没有配置固定值时,再构造可搜索的超参数,避免提前注册不需要的搜索空间:
class MyModel(kt.HyperModel): def __init__(self, **config): self.config = config self.seed = config.get('seed') self.name = "my_model" # 补充原代码缺失的name属性 def build_model(self): model = Sequential(name=self.name) model.add(LSTM(self.units, name='LSTM')) model.add(Dense(1, name='Output', kernel_initializer=GlorotUniform(seed=self.seed))) model.compile(loss='mean_squared_error', metrics='mean_squared_error', sample_weight_mode='temporal') return model def _param(self, hp, key, search_type=None, **search_kwargs): # 优先使用传入的固定值 value = self.config.get(key) if value is not None: return hp.Fixed(key, value) # 无固定值时才创建可搜索超参数 if search_type == "int": return hp.Int(key, **search_kwargs) elif search_type == "float": return hp.Float(key, **search_kwargs) elif search_type == "choice": return hp.Choice(key, **search_kwargs) else: raise ValueError(f"不支持的超参数搜索类型:{search_type}") def build(self, hp): self.units = self._param(hp, 'units', search_type='int', min_value=1, max_value=200, step=5) return self.build_model()
验证方法
修复完成后可以调用tuner.search_space_summary()查看搜索空间,确认需要固定的参数已经被标记为Fixed类型,没有对应的取值范围,此时调优结果就会和直接传入静态值完全一致。
内容的提问来源于stack exchange,提问作者SnakeWasTheNameTheyGaveMe
相关产品推荐
相关产品推荐

