如何为MLPClassifier依次测试多种隐藏层架构配置?
问题原因
你直接把包含多个隐藏层配置的列表传给了hidden_layer_sizes参数,但这个参数要求的是单个元组(对应一个MLP模型的隐藏层结构)。当sklearn内部验证参数时,会把你传入的列表转成数组,数组里的每个元素是元组,和整数0比较时就触发了类型错误。
解决方法
方法1:手动循环逐个测试配置
遍历所有隐藏层配置,为每个配置单独创建并训练MLP模型:
hl_parameters = {'hidden_layer_sizes': [(10,), (50,), (10,10,), (50,50,)]} # 遍历每个隐藏层配置 for size in hl_parameters['hidden_layer_sizes']: print(f"训练配置: {size}") mlp = MLPClassifier( hidden_layer_sizes=size, max_iter=300, alpha=1e-4, solver='sgd', tol=1e-4, learning_rate_init=.1, verbose=True, random_state=ID ) mlp.fit(X_train, y_train) # 可添加模型评估逻辑,比如测试集准确率计算 # accuracy = mlp.score(X_test, y_test) # print(f"配置{size}的测试准确率: {accuracy}")
方法2:用GridSearchCV自动调参(推荐)
如果需要系统测试参数并做交叉验证,使用sklearn的GridSearchCV,它会自动遍历所有指定参数组合并返回最优模型:
from sklearn.model_selection import GridSearchCV # 定义参数网格 param_grid = {'hidden_layer_sizes': [(10,), (50,), (10,10,), (50,50,)]} # 初始化MLP基础模型 mlp_base = MLPClassifier( max_iter=300, alpha=1e-4, solver='sgd', tol=1e-4, learning_rate_init=.1, verbose=True, random_state=ID ) # 初始化网格搜索(5折交叉验证) grid_search = GridSearchCV(estimator=mlp_base, param_grid=param_grid, cv=5, verbose=2) grid_search.fit(X_train, y_train) # 查看最优结果 print(f"最优隐藏层配置: {grid_search.best_params_}") print(f"最优交叉验证得分: {grid_search.best_score_}") # 使用最优模型进行后续预测 best_mlp = grid_search.best_estimator_
内容的提问来源于stack exchange,提问作者cipos
相关产品推荐
相关产品推荐

