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

卡方检验代码报错:'numpy.ndarray' object is not callable 求解

卡方检验特征筛选报错:'numpy.ndarray' object is not callable 解决方法

问题背景

执行卡方检验判断特征与目标变量独立性,筛选符合p值要求的特征时,触发如下错误:

TypeError: 'numpy.ndarray' object is not callable

原代码:

y = dtf_train["y"]
X_names = vectorizer.get_feature_names()
p_value_limit = 0.95
dtf_features = pd.DataFrame()
for cat in np.unique(y):
    chi2, p = feature_selection.chi2(X_train, y==cat)
    dtf_features = dtf_features.append(pd.DataFrame(
                   {"feature":X_names, "score":1-p, "y":cat}))
    dtf_features = dtf_features.sort_values(["y","score"], 
                    ascending=[True,False])
    dtf_features = dtf_features[dtf_features["score"]>p_value_limit]

X_names = dtf_features["feature"].unique().tolist()

错误栈:

TypeError                                 Traceback (most recent call last)
<ipython-input-103-1028dac02fc2> in <module>
      4 dtf_features = pd.DataFrame()
      5 for cat in np.unique(y):
----> 6     chi2, p = chi2(X_train, y==cat)
      7     dtf_features = dtf_features.append(pd.DataFrame(
      8                    {"feature":X_names, "score":1-p, "y":cat}))

TypeError: 'numpy.ndarray' object is not callable

错误原因

核心问题是变量名冲突:
第一次循环时,你用chi2接收feature_selection.chi2函数返回的第一个结果(卡方值数组),此时chi2从原本指向函数的引用,变成了numpy数组。第二次循环执行chi2(X_train, y==cat)时,实际是在调用一个数组,自然触发"不可调用"的错误。

另外最后一行代码存在语法问题:tolist是列表生成方法,需要加括号调用,否则会得到方法对象而非目标列表。

修正后的代码

y = dtf_train["y"]
X_names = vectorizer.get_feature_names()
p_value_limit = 0.95
dtf_features = pd.DataFrame()
for cat in np.unique(y):
    # 重命名变量避免与函数名冲突
    chi2_score, p = feature_selection.chi2(X_train, y==cat)
    dtf_features = dtf_features.append(pd.DataFrame(
                   {"feature":X_names, "score":1-p, "y":cat}))
    dtf_features = dtf_features.sort_values(["y","score"], 
                    ascending=[True,False])
    dtf_features = dtf_features[dtf_features["score"]>p_value_limit]

# 修正tolist()的调用方式
X_names = dtf_features["feature"].unique().tolist()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 06:25:24