作者: 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}