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

如何用GridSearchCV确定MLP最佳层数与隐藏层大小?报错修复

修复GridSearchCV调MLP参数的TypeError问题

错误原因分析

你的代码有两个关键问题导致报错:

  1. 参数生成逻辑错误:list(range([list(range(10,200,10))])) 里,range() 要求传入整数参数,但你传了一个列表进去,直接触发 TypeError。
  2. 参数键名错误:因为你直接用 MLPClassifier 作为 GridSearchCV 的 estimator,不需要加 estimator__ 前缀,这个前缀仅适用于Pipeline等嵌套模型的参数指定。

修复方案

根据你要寻找最佳层数和隐藏层大小的需求,分两种场景给出修复代码:

场景1:仅测试单隐藏层的不同神经元数量

如果只需要测试1层隐藏层,神经元数从10到190,步长10:

import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.neural_network import MLPClassifier

df = pd.read_csv(r'C:\\Users\data.csv')
X = df.iloc[:,:20]
Y = df.iloc[:,20]

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)

# 生成单隐藏层的神经元数列表:[10,20,...,190]
params = {
    'hidden_layer_sizes': list(range(10, 200, 10))
}

clf = GridSearchCV(
    estimator=MLPClassifier(),
    param_grid=params,
    cv=5,
    n_jobs=5,
    verbose=1,
)

clf.fit(X_train, y_train)
print(clf.best_params_)

场景2:测试多层隐藏层(比如1-3层)的组合

如果要同时测试不同层数(比如1、2、3层)和对应神经元数的组合,需要生成包含元组的列表,每个元组代表一层或多层的神经元数:

import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.neural_network import MLPClassifier

df = pd.read_csv(r'C:\\Users\data.csv')
X = df.iloc[:,:20]
Y = df.iloc[:,20]

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)

# 生成不同层数的参数组合:单隐藏层、双隐藏层、三隐藏层
neuron_options = list(range(10, 200, 10))
hidden_layer_options = []
# 单隐藏层
for n in neuron_options:
    hidden_layer_options.append(n)
# 双隐藏层(两层神经元数相同)
for n in neuron_options:
    hidden_layer_options.append((n, n))
# 三隐藏层(三层神经元数相同)
for n in neuron_options:
    hidden_layer_options.append((n, n, n))

params = {
    'hidden_layer_sizes': hidden_layer_options
}

clf = GridSearchCV(
    estimator=MLPClassifier(),
    param_grid=params,
    cv=5,
    n_jobs=5,
    verbose=1,
)

clf.fit(X_train, y_train)
print(clf.best_params_)

说明

  • hidden_layer_sizes 的格式:可以是整数(单隐藏层),也可以是元组/列表(多层隐藏层,每个元素对应一层的神经元数)。
  • 如果你需要更灵活的多层组合(比如两层不同神经元数),可以扩展生成逻辑,比如遍历不同的神经元数组合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:44:57