HyperModel 类keras_tuner.HyperModel(name=None, tunable=True)
定义模型的搜索空间。
搜索空间是模型集合。build 函数将使用给定的 HyperParameters 对象从空间中构建其中一个模型。
用户应继承 HyperModel 类,通过重写 build() 来定义其搜索空间,build() 会创建并返回 Keras 模型。可选地,您也可以重写 fit() 来自定义模型的训练过程。
示例
在 build() 中,您可以使用超参数创建模型。
class MyHyperModel(kt.HyperModel):
def build(self, hp):
model = keras.Sequential()
model.add(keras.layers.Dense(
hp.Choice('units', [8, 16, 32]),
activation='relu'))
model.add(keras.layers.Dense(1, activation='relu'))
model.compile(loss='mse')
return model
重写 HyperModel.fit() 时,如果您使用 model.fit() 来训练模型,该函数会返回训练历史,您可以直接返回它。您可以使用 hp 来指定任何要调优的超参数。
class MyHyperModel(kt.HyperModel):
def build(self, hp):
...
def fit(self, hp, model, *args, **kwargs):
return model.fit(
*args,
epochs=hp.Int("epochs", 5, 20),
**kwargs)
如果您有自定义的训练过程,您可以返回目标值(浮点数)。
如果您想跟踪更多指标,您可以返回一个要跟踪的指标字典。
class MyHyperModel(kt.HyperModel):
def build(self, hp):
...
def fit(self, hp, model, *args, **kwargs):
...
return {
"loss": loss,
"val_loss": val_loss,
"val_accuracy": val_accuracy
}
参数
False,则必须提前定义这些参数的搜索空间,或者将使用默认值。默认为 True。build 方法HyperModel.build(hp)
构建模型。
参数
HyperParameters 实例。返回
一个模型实例。