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

设置Overwrite=True后Kerastuner超参搜索仍未重启问题

问题分析与解决方案

核心原因

你遇到的问题大概率是以下几个因素导致的:

  • HyperModel实例复用:循环中没有每次创建新的MyHyperModel实例,或者模型类内部保留了静态状态,导致复用了第一次的超参数配置。
  • 目录清理不及时/不彻底:删除目录的操作可能在tuner实例化之后执行,或者系统进程占用导致目录未真正删除,Kerastuner仍能读取旧缓存。
  • Kerastuner全局缓存残留:除了指定的directory,Kerastuner可能在全局路径(如~/.keras/tuner)保留了缓存数据,导致复用旧结果。
  • 输入数据未同步更新:可能每次循环的训练数据还是第一次的500特征版本,导致模型表现看起来像是沿用了旧超参数。

具体解决方案

1. 每次循环重新实例化HyperModel并传入当前特征数

确保MyHyperModel能接收当前特征数参数,且每次循环都创建全新实例:

import os
import shutil
import kerastuner as kt

for cpg_num in [100,500,1000,5000,10000,20000,40000]:
    # 实例化tuner前先清理结果目录
    project_path = os.path.join(results_dir, "tune_hypermodel")
    if os.path.exists(project_path):
        shutil.rmtree(project_path, ignore_errors=True)
    
    # 传入当前特征数,创建全新HyperModel实例
    hypermodel = MyHyperModel(cpg_num=cpg_num)
    
    # 实例化tuner时禁用缓存
    tuner = kt.RandomSearch(
        hypermodel,
        objective="mae",
        max_trials=30,
        overwrite=True,
        directory=results_dir,
        project_name="tune_hypermodel",
        cache=False
    )
    
    # 加载对应当前特征数的训练数据
    x_train, y_train = load_data_with_cpg(cpg_num)  # 替换成你的数据加载逻辑
    tuner.search(x_train, y_train, epochs=10, validation_split=0.2)

2. 检查HyperModel的build方法

确认build方法根据传入的特征数动态构建输入层,而非硬编码固定值:

class MyHyperModel(kt.HyperModel):
    def __init__(self, cpg_num):
        self.cpg_num = cpg_num  # 保存当前特征数
    
    def build(self, hp):
        model = keras.Sequential()
        # 动态设置输入形状
        model.add(keras.layers.Dense(
            units=hp.Int('units', min_value=32, max_value=512, step=32),
            activation='relu', 
            input_shape=(self.cpg_num,)
        ))
        # 后续层逻辑...
        model.compile(optimizer='adam', loss='mae', metrics=['mae'])
        return model

3. 清理Kerastuner全局缓存

如果上述方法无效,可手动清理全局缓存目录:

# Linux/macOS
rm -rf ~/.keras/tuner
# Windows
rd /s /q %USERPROFILE%\.keras\tuner

注意:此操作会清理所有Kerastuner项目的缓存,执行前请确认无其他正在运行的调优任务。

4. 强制重置搜索状态

部分Kerastuner版本支持在search方法中添加reset=True参数,强制跳过旧结果加载:

tuner.search(x_train, y_train, epochs=10, validation_split=0.2, reset=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:16:12