作者:Luca Invernizzi, James Long, Francois Chollet, Tom O'Malley, Haifeng Jin
创建日期 2019/05/31
最后修改日期 2021/10/27
描述: 在不更改超模型的情况下,调整超参数的子集。
!pip install keras-tuner -q
在本指南中,我们将展示如何在不直接更改 HyperModel
代码的情况下定制搜索空间。例如,您可以只调整部分超参数并保持其余参数固定,或者您可以覆盖编译参数,如 optimizer
、loss
和 metrics
。
在定制搜索空间之前,了解每个超参数都有一个默认值非常重要。当我们定制搜索空间时,如果不调整某个超参数,则会使用此默认值作为该超参数的值。
每当您注册一个超参数时,您可以使用 default
参数来指定一个默认值。
hp.Int("units", min_value=32, max_value=128, step=32, default=64)
如果您不指定,超参数始终具有默认的默认值(对于 Int
,它等于 min_value
)。
在以下模型构建函数中,我们将 units
超参数的默认值指定为 64。
import keras
from keras import layers
import keras_tuner
import numpy as np
def build_model(hp):
model = keras.Sequential()
model.add(layers.Flatten())
model.add(
layers.Dense(
units=hp.Int("units", min_value=32, max_value=128, step=32, default=64)
)
)
if hp.Boolean("dropout"):
model.add(layers.Dropout(rate=0.25))
model.add(layers.Dense(units=10, activation="softmax"))
model.compile(
optimizer=keras.optimizers.Adam(
learning_rate=hp.Choice("learning_rate", values=[1e-2, 1e-3, 1e-4])
),
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
)
return model
在本教程的其余部分,我们将通过覆盖超参数来重用此搜索空间,而无需定义新的搜索空间。
如果您有一个现有的超模型,并且只想搜索少数几个超参数,并保持其余参数固定,则无需更改模型构建函数或 HyperModel
中的代码。您可以将一个 HyperParameters
传递给调谐器构造函数的 hyperparameters
参数,其中包含您要调整的所有超参数。指定 tune_new_entries=False
以防止它调整其他超参数,否则将使用其默认值。
在以下示例中,我们仅调整 learning_rate
超参数,并更改其类型和值范围。
hp = keras_tuner.HyperParameters()
# This will override the `learning_rate` parameter with your
# own selection of choices
hp.Float("learning_rate", min_value=1e-4, max_value=1e-2, sampling="log")
tuner = keras_tuner.RandomSearch(
hypermodel=build_model,
hyperparameters=hp,
# Prevents unlisted parameters from being tuned
tune_new_entries=False,
objective="val_accuracy",
max_trials=3,
overwrite=True,
directory="my_dir",
project_name="search_a_few",
)
# Generate random data
x_train = np.random.rand(100, 28, 28, 1)
y_train = np.random.randint(0, 10, (100, 1))
x_val = np.random.rand(20, 28, 28, 1)
y_val = np.random.randint(0, 10, (20, 1))
# Run the search
tuner.search(x_train, y_train, epochs=1, validation_data=(x_val, y_val))
Trial 3 Complete [00h 00m 01s]
val_accuracy: 0.20000000298023224
Best val_accuracy So Far: 0.25
Total elapsed time: 00h 00m 03s
如果您总结搜索空间,您将只看到一个超参数。
tuner.search_space_summary()
Search space summary
Default search space size: 1
learning_rate (Float)
{'default': 0.0001, 'conditions': [], 'min_value': 0.0001, 'max_value': 0.01, 'step': None, 'sampling': 'log'}
在上面的示例中,我们展示了如何仅调整少数几个超参数并保持其余参数固定。您也可以反过来:只固定少数几个超参数并调整其余所有参数。
在以下示例中,我们固定了 learning_rate
超参数的值。传递一个带有 Fixed
条目(或任意数量的 Fixed
条目)的 hyperparameters
参数。另外,请记住指定 tune_new_entries=True
,这允许我们调整其余的超参数。
hp = keras_tuner.HyperParameters()
hp.Fixed("learning_rate", value=1e-4)
tuner = keras_tuner.RandomSearch(
build_model,
hyperparameters=hp,
tune_new_entries=True,
objective="val_accuracy",
max_trials=3,
overwrite=True,
directory="my_dir",
project_name="fix_a_few",
)
tuner.search(x_train, y_train, epochs=1, validation_data=(x_val, y_val))
Trial 3 Complete [00h 00m 01s]
val_accuracy: 0.15000000596046448
Best val_accuracy So Far: 0.15000000596046448
Total elapsed time: 00h 00m 03s
如果您总结搜索空间,您将看到 learning_rate
被标记为固定,而其余的超参数正在被调整。
tuner.search_space_summary()
Search space summary
Default search space size: 3
learning_rate (Fixed)
{'conditions': [], 'value': 0.0001}
units (Int)
{'default': 64, 'conditions': [], 'min_value': 32, 'max_value': 128, 'step': 32, 'sampling': 'linear'}
dropout (Boolean)
{'default': False, 'conditions': []}
如果您的超模型需要更改现有的优化器、损失或指标,您可以通过将这些参数传递给调谐器构造函数来实现。
tuner = keras_tuner.RandomSearch(
build_model,
optimizer=keras.optimizers.Adam(1e-3),
loss="mse",
metrics=[
"sparse_categorical_crossentropy",
],
objective="val_loss",
max_trials=3,
overwrite=True,
directory="my_dir",
project_name="override_compile",
)
tuner.search(x_train, y_train, epochs=1, validation_data=(x_val, y_val))
Trial 3 Complete [00h 00m 01s]
val_loss: 29.39796257019043
Best val_loss So Far: 29.39630699157715
Total elapsed time: 00h 00m 04s
如果您获得最佳模型,您可以看到损失函数已更改为 MSE。
tuner.get_best_models()[0].loss
/usr/local/python/3.10.13/lib/python3.10/site-packages/keras/src/saving/saving_lib.py:388: UserWarning: Skipping variable loading for optimizer 'adam', because it has 2 variables whereas the saved optimizer has 10 variables.
trackable.load_own_variables(weights_store.get(inner_path))
'mse'
您也可以将这些技术与 KerasTuner 中预构建的模型一起使用,如 HyperResNet
或 HyperXception
。但是,要查看这些预构建的 HyperModel
中包含哪些超参数,您需要阅读源代码。
在以下示例中,我们仅调整 HyperXception
的 learning_rate
,并固定了所有其余的超参数。由于 HyperXception
的默认损失为 categorical_crossentropy
,它期望标签为独热编码,这与我们的原始整数标签数据不匹配,因此我们需要通过在编译参数中覆盖 loss
为 sparse_categorical_crossentropy
来更改它。
hypermodel = keras_tuner.applications.HyperXception(input_shape=(28, 28, 1), classes=10)
hp = keras_tuner.HyperParameters()
# This will override the `learning_rate` parameter with your
# own selection of choices
hp.Choice("learning_rate", values=[1e-2, 1e-3, 1e-4])
tuner = keras_tuner.RandomSearch(
hypermodel,
hyperparameters=hp,
# Prevents unlisted parameters from being tuned
tune_new_entries=False,
# Override the loss.
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
objective="val_accuracy",
max_trials=3,
overwrite=True,
directory="my_dir",
project_name="helloworld",
)
# Run the search
tuner.search(x_train, y_train, epochs=1, validation_data=(x_val, y_val))
tuner.search_space_summary()
Trial 3 Complete [00h 00m 19s]
val_accuracy: 0.15000000596046448
Best val_accuracy So Far: 0.20000000298023224
Total elapsed time: 00h 00m 58s
Search space summary
Default search space size: 1
learning_rate (Choice)
{'default': 0.01, 'conditions': [], 'values': [0.01, 0.001, 0.0001], 'ordered': True}