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

如何在Pipeline中调优FunctionTransformer的num_corr_threshold参数?

如何在Pipeline中调优自定义函数的num_corr_threshold参数?

问题背景

我有一个需要调优num_corr_threshold参数的自定义函数:

import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix

def categorical_anticorr(X_cat_in, num_corr_threshold=0.5):
    if type(X_cat_in) == np.ndarray:
        X_cat_in = pd.DataFrame(X_cat_in)
    elif type(X_cat_in) == type(csr_matrix(0)):
        X_cat_in = pd.DataFrame(X_cat_in.toarray())
    corr_num = X_cat_in.corr(method='spearman')
    upper = corr_num.where(np.triu(np.ones(corr_num.shape), k=1).astype(bool)).abs()
    col_to_drop = [column for column in upper.columns if any(upper[column] > num_corr_threshold)]
    return X_cat_in.drop(columns=col_to_drop)

已将该函数加入名为preproc的复杂Pipeline中,通过preproc.get_params()查到参数路径为columntransformer__pipeline-2__functiontransformer__func: <function main.categorical_anticorr(X_cat_in, num_corr_threshold=0.5)>。

尝试编写网格搜索的参数网格时:

param_grid =  {'columntransformer__pipeline2__functiontransformer__func': <function main.categorical_anticorr(X_cat_in, num_corr_threshold=0.5)>}

出现SyntaxError: invalid syntax错误,需要正确编写语法来调优categorical_anticorr函数的num_corr_threshold参数。

解决方案

核心思路

不能直接将函数对象传入param_grid,而是要借助FunctionTransformer的kw_args参数,传递自定义函数的关键字参数实现调优,同时注意参数路径的正确性。

具体步骤

  1. 修正参数路径:原路径中是pipeline-2(带连字符),你之前写成pipeline2是错误的,需保持路径完全一致。
  2. 使用kw_args传递参数:FunctionTransformer的kw_args参数用于给绑定的自定义函数传递关键字参数,网格搜索时只需遍历该参数的不同取值字典即可。

正确的param_grid示例

param_grid = {
    'columntransformer__pipeline-2__functiontransformer__kw_args': [
        {'num_corr_threshold': 0.3},
        {'num_corr_threshold': 0.5},
        {'num_corr_threshold': 0.7},
        {'num_corr_threshold': 0.9}
    ]
}

补充说明

如果你的FunctionTransformer是如下方式初始化的,上述方法完全适用:

from sklearn.preprocessing import FunctionTransformer

# 绑定自定义函数
func_transformer = FunctionTransformer(func=categorical_anticorr)

kw_args默认是空字典,网格搜索会将每个候选的字典传递给categorical_anticorr函数,实现num_corr_threshold参数的调优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:35:26