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

如何通过for循环与函数实现网格搜索?并解决机器学习模型定义函数嵌入GridSearchCV的报错问题

解决网格搜索嵌入模型定义函数的问题

我来帮你排查这个问题,你的代码里有两个关键问题导致了报错和功能异常,咱们一步步解决:

1. 直接导致报错的核心问题

你在clr_svr分支里犯了两个变量相关的错误:

  • 最后一行return model是完全错误的:这个分支里你从来没有定义过model变量,你创建的网格搜索实例是clr_svr,所以应该返回这个变量,或者统一用model作为变量名保持一致性。
  • 关于UnboundLocalError: local variable 'parameters_svr' referenced before assignment:如果你的代码和你贴的完全一致,这个报错大概率是缩进问题——比如parameters_svr的定义没有被包含在elif model_type == 'clr_svr'的代码块里,导致进入分支时变量还没被定义。

2. 修正后的完整函数

我调整了你的代码,统一了变量命名,修复了缩进和返回逻辑,同时增加了未知模型类型的异常处理:

from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LinearRegression
from sklearn.neural_network import MLPRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.svm import SVR
import xgboost as xg

def define_model(model_type):
    if model_type == "linear":
        model = LinearRegression()
    elif model_type == "mlp":
        model = MLPRegressor(
            hidden_layer_sizes=(2), activation='identity', solver='lbfgs', max_iter=100000000000)
    elif model_type == 'KN':
        model = KNeighborsRegressor(
            n_neighbors=6, weights='distance', algorithm='ball_tree', leaf_size=60, p=2, metric='minkowski', metric_params=None, n_jobs=None)
    elif model_type == 'Dec_tree':
        model = DecisionTreeRegressor(
            criterion='squared_error', splitter='best', max_depth=33, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0,max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, ccp_alpha=0.0)
    elif model_type == 'SV':
        model = SVR(
            kernel='rbf', degree=5, gamma='scale', coef0=0.0, tol=0.001, C=10.0, epsilon=0.1, shrinking=True, cache_size=200, verbose=False, max_iter=- 1)
    elif model_type == 'XGBoost':
        model = xg.XGBRegressor(objective ='reg:linear', n_estimators = 600, seed = 123)
    elif model_type == 'clr_svr':
        # 定义基础SVR模型和参数网格
        svr_base = SVR()
        parameters_svr = {
            'kernel': ('linear', 'rbf','poly'),
            'C': [1.5, 10],
            'gamma': [1e-7, 1e-4],
            'epsilon': [0.1, 0.2, 0.5, 0.3]
        }
        # 创建网格搜索实例,赋值给统一的model变量
        model = GridSearchCV(svr_base, parameters_svr)
    else:
        # 处理未知模型类型,避免静默错误
        raise ValueError(f"不支持的模型类型:{model_type}")
    return model

3. 如何使用网格搜索模型

返回的GridSearchCV实例需要先调用fit()执行搜索,之后可以通过属性获取最优结果:

# 获取网格搜索模型
grid_model = define_model('clr_svr')
# 执行网格搜索(传入训练数据)
grid_model.fit(X_train, y_train)
# 获取最优参数的模型
best_svr = grid_model.best_estimator_
# 打印最优参数
print("SVR最优参数组合:", grid_model.best_params_)

4. 扩展到其他模型(比如MLP)

如果要给MLP也添加网格搜索,只需要新增一个分支即可,逻辑完全一致:

elif model_type == 'mlp_grid':
    mlp_base = MLPRegressor(max_iter=1000000)
    parameters_mlp = {
        'hidden_layer_sizes': [(2), (4,2), (8,4)],
        'activation': ['identity', 'relu'],
        'solver': ['lbfgs', 'adam']
    }
    model = GridSearchCV(mlp_base, parameters_mlp)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:32:37