如何从HyperoptEstimator中获取隐藏层尺寸参数?
解决hyperopt-sklearn中MLP最优隐藏层配置获取问题
一、修正搜索空间定义(核心问题)
你之前的hp.choice实现错误:返回的是自定义字典结构,但mlp_classifier需要直接对应sklearn MLPClassifier的参数(比如hidden_layer_sizes),而非自定义格式。正确的做法是让hp.choice直接返回hidden_layer_sizes所需的结构:1层传单个整数,多层传元组/列表。
修正后的代码:
import numpy as np from hyperopt import hp, tpe from hpsklearn import HyperoptEstimator, mlp_classifier, scope clf = mlp_classifier( # 直接对hidden_layer_sizes参数做选择,匹配MLPClassifier的要求 hidden_layer_sizes=hp.choice('number_of_layers', [ # 1层隐藏层:单个神经元数量 scope.int(hp.qloguniform("1layer", np.log(1), np.log(1000), 1)), # 2层隐藏层:(第一层神经元数, 第二层神经元数) ( scope.int(hp.qloguniform("2layer_1", np.log(1), np.log(1000), 1)), scope.int(hp.qloguniform("2layer_2", np.log(1), np.log(1000), 1)) ), # 3层隐藏层:(第一层, 第二层, 第三层) ( scope.int(hp.qloguniform("3layer_1", np.log(1), np.log(1000), 1)), scope.int(hp.qloguniform("3layer_2", np.log(1), np.log(1000), 1)), scope.int(hp.qloguniform("3layer_3", np.log(1), np.log(1000), 1)) ) ]), # 可选:添加其他需要优化的MLP参数 activation=hp.choice('activation', ['tanh', 'relu', 'logistic']), alpha=hp.loguniform('alpha', np.log(1e-5), np.log(1e-1)) ) mlp_clf = HyperoptEstimator( classifier=clf, algo=tpe.suggest, max_evals=20, trial_timeout=200, seed=42, # 原代码中np.random.seed(42)返回None,会导致seed无效,直接传整数即可 n_jobs=-1, verbose=True ) mlp_clf.fit(X_train, y_train)
二、获取最优隐藏层配置
修正后,可通过两种方式获取最优的隐藏层参数:
- 从最佳模型实例中直接提取
best_learner = mlp_clf.best_model()['learner'] print("最优隐藏层配置:", best_learner.hidden_layer_sizes) # 同时可查看其他最优参数 print("激活函数:", best_learner.activation) print("L2正则化系数:", best_learner.alpha)
- 从最佳trial中查看搜索空间的选择结果
best_trial = mlp_clf.best_trial() # 层数索引对应:0=1层,1=2层,2=3层 print("选中的层数索引:", best_trial['misc']['vals']['number_of_layers'][0]) # 示例:若选中2层,查看对应神经元数量 if best_trial['misc']['vals']['number_of_layers'][0] == 1: print("第一层神经元数:", best_trial['misc']['vals']['2layer_1'][0]) print("第二层神经元数:", best_trial['misc']['vals']['2layer_2'][0])
三、原代码问题解释
你之前用hp.choice返回字典(如{"1layer": ...}),但mlp_classifier没有对应的参数接收该结构,导致Hyperopt无法将值映射到MLPClassifier的hidden_layer_sizes参数上,最终训练出的模型自然不会包含这部分配置信息。必须让搜索空间的参数直接对应到sklearn模型的参数名,才能正确传递和优化。
内容的提问来源于stack exchange,提问作者Francisco Santoro
相关产品推荐
相关产品推荐

