You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Keras-Tuner的RandomSearch Tuner时search_space_summary()无法显示全部Dense层信息

问题描述

尝试使用keras-tuner进行超参数调优,代码如下:

!pip install keras-tuner --upgrade
import keras_tuner as kt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.optimizers import Adam

def build_model(hp):
    model = Sequential([
        Flatten(input_shape=(28, 28)),
        Dense(units= hp.Int('units', min_value = 16, max_value = 64, step = 16), activation='relu'),
        Dense(units = hp.Int('units', min_value = 8, max_value = 20, step = 2), activation='softmax')
    ])

    model.compile(
        optimizer=Adam(learning_rate=hp.Float('learning_rate', min_value=1e-4, max_value=1e-2, sampling='LOG')),
        loss='sparse_categorical_crossentropy',
        metrics=['accuracy']
    )
    return model

# Create a RandomSearch Tuner
tuner = kt.RandomSearch(
    build_model, 
    objective='val_accuracy',
    max_trials=10,
    executions_per_trial=2
)

# Display a summary of the search space
tuner.search_space_summary()

运行后输出:

Search space summary
Default search space size: 2
units (Int)
{'default': None, 'conditions': [], 'min_value': 16, 'max_value': 64, 'step': 16, 'sampling': 'linear'}
learning_rate (Float)
{'default': 0.0001, 'conditions': [], 'min_value': 0.0001, 'max_value': 0.01, 'step': None, 'sampling': 'log'}

仅显示第一个Dense层的units超参数信息,第二个Dense层的units配置未被展示,询问是否配置有误及原因。

原因分析与解决方案

这是配置错误导致的:你给两个Dense层的超参数都用了同一个名称units。Keras Tuner会将同名的超参数视为同一个变量,后定义的超参数配置会被前面的覆盖,因此搜索空间中只保留第一个units的设置。

解决方法很简单,给两个超参数设置不同的名称,比如分别命名为dense_1_units和dense_2_units,修改后的代码如下:

def build_model(hp):
    model = Sequential([
        Flatten(input_shape=(28, 28)),
        # 第一个Dense层超参数命名为dense_1_units
        Dense(units= hp.Int('dense_1_units', min_value = 16, max_value = 64, step = 16), activation='relu'),
        # 第二个Dense层超参数命名为dense_2_units
        Dense(units = hp.Int('dense_2_units', min_value = 8, max_value = 20, step = 2), activation='softmax')
    ])

    model.compile(
        optimizer=Adam(learning_rate=hp.Float('learning_rate', min_value=1e-4, max_value=1e-2, sampling='LOG')),
        loss='sparse_categorical_crossentropy',
        metrics=['accuracy']
    )
    return model

再次运行tuner.search_space_summary(),就会看到搜索空间包含三个独立的超参数:dense_1_units、dense_2_units和learning_rate。

内容的提问来源于stack exchange,提问作者ThomasIsCoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 09:22:03