Keras Tuner触发模型构建函数返回无效Keras实例的RuntimeError问题咨询
Keras Tuner 模型构建函数报错修复指南
报错核心根因
本次报错与导入路径无关,直接触发原因是:自定义的create_autoencoder构建函数最终返回了包含两个模型的元组,而Keras Tuner要求模型构建函数必须且仅能返回单个合法的Keras Model实例。
报错信息中明确提示返回值是两个Functional类型对象组成的元组,完全匹配当前代码中return autoencoder, encoder的返回逻辑,属于接口使用方式不符合框架约定,不属于常见的版本导入冲突类问题。
代码中连带存在的其他运行隐患
- 自定义Tuner类的
run_trial方法内直接引用了全局作用域下不存在的hp对象定义batch_size、epochs超参数,运行到fit阶段会触发变量未定义报错,需要改用方法入参trial携带的超参实例完成定义。 - 多输出模型的损失配置不匹配:当前构建的autoencoder存在两个独立输出(特征重建分支、标签分类分支),但compile阶段仅传入了单个损失函数,没有为两个输出分别配置对应损失规则,会触发维度匹配报错。
- 超参数定义重复:两个相邻的Dense层共用同一个
output_x超参数定义,会导致两层神经元数量被强制绑定为完全相同的值,和常规网络设计的灵活性要求不匹配。
具体修复方案
- 修改模型构建函数的返回逻辑:仅返回用于训练的autoencoder单模型,不要把后续独立使用的encoder辅助结构作为返回值传递给Tuner。如果需要获取encoder,可在超参搜索完成、拿到最优超参后,基于网络结构重新单独初始化encoder实例,不需要耦合在超参搜索的构建流程里。
- 补全多输出模型的损失配置,为每个输出分支匹配对应任务的损失函数,示例修复后的构建函数代码:
def create_autoencoder(hp, input_dim, output_dim): # 保留原有网络层定义,仅调整返回值和损失配置 i = Input(input_dim) encoded = BatchNormalization()(i) encoded = GaussianNoise(hp.Float('gaussian_noise', 1e-2, 1, sampling='log', default=5e-2))(encoded) encoded = Dense(hp.Int('encoder_dense', 100, 300, step=50, default=64), activation='relu')(encoded) decoded = Dropout(hp.Float('decoder_dropout_1', 1e-1, 1, sampling='log', default=0.2))(encoded) decoded = Dense(input_dim, name='decoded')(decoded) x = Dense(hp.Int('dense_1', 32, 100, step=10, default=32), activation='relu')(decoded) x = BatchNormalization()(x) x = Dropout(hp.Float('x_dropout_1', 1e-1, 1, sampling='log', default=0.2))(x) x = Dense(hp.Int('dense_2', 32, 100, step=10, default=32), activation='relu')(x) x = BatchNormalization()(x) x = Dropout(hp.Float('x_dropout_2', 1e-1, 1, sampling='log', default=0.2))(x) x = Dense(output_dim, activation='sigmoid', name='label_output')(x) autoencoder = Model(inputs=i, outputs=[decoded, x]) autoencoder.compile( optimizer=Adam(hp.Float('lr', 0.00001, 0.1, default=0.001)), loss={ 'decoded': 'mse', 'label_output': 'binary_crossentropy' }, metrics=['accuracy'] ) # 仅返回单模型,删除原有的encoder返回逻辑 return autoencoder - 修正自定义Tuner方法内的超参引用问题,把全局
hp对象的引用替换为trial.hyperparameters实例的方法调用,示例修复片段:def run_trial(self, trial, x, y): cv = PurgedGroupTimeSeriesSplit(n_splits=5, group_gap = 20) val_losses = [] # 从trial对象获取超参实例 hp = trial.hyperparameters for train_indices, test_indices in cv.split(x, groups=x[0]): x_train, y_train = x[train_indices, 1:], y[train_indices] x_test, y_test = x[test_indices, 1:], y[test_indices] x_train = apply_transformation(x_train) x_test = apply_transformation(x_test) model = self.hypermodel.build(hp) # 基于hp实例定义batch size和epochs,不再引用不存在的全局hp batch_size = hp.Int('batch_size', 500, 5000, step=500, default=4000) epochs = hp.Int('epochs', 100, 1000, step=200, default=500) model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs) val_losses.append(model.evaluate(x_test, y_test)) self.oracle.update_trial(trial.trial_id, {'val_loss': np.mean(val_losses)}) self.save_model(trial.trial_id, model)
内容的提问来源于stack exchange,提问作者Krishnang K Dalal
相关产品推荐
相关产品推荐

