HyperModel
基底類別使搜尋空間能被更好地封裝,以利共享和重複使用。一個 HyperModel
子類別只需要實作一個 build(self, hp)
方法,該方法會使用 hp
引數來定義超參數並建立一個 keras.Model
,然後回傳模型實例。一個簡單的程式碼範例如下所示。
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
實例作為搜尋空間傳遞給 Tuner
。
tuner = kt.RandomSearch(
MyHyperModel(),
objective='val_loss',
max_trials=5)
還有一些內建的 HyperModel
子類別(例如 HyperResNet
、HyperXception
)供使用者直接使用,如此一來,使用者就不需要編寫自己的搜尋空間。
tuner = kt.RandomSearch(
HyperResNet(input_shape=(28, 28, 1), classes=10),
objective='val_loss',
max_trials=5)