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

如何生成OLS回归摘要并解决UFuncTypeError错误?

问题原因与解决方案

错误根源

你当前代码里的independent_variables被定义成了列名的字符串嵌套列表,但sm.add_constant()和sm.OLS()需要的是数值型数据集(DataFrame或数组),不是列名文本。numpy尝试对字符串执行数值计算(比如求最大值),因此抛出了类型不匹配的错误。

修正后的代码

import pandas as pd
import statsmodels.api as sm

df = pd.read_csv('wine.csv')

# 直接从DataFrame中提取指定列的数值数据,而非仅存储列名字符串
independent_variables = df[['fixed acidity', 'volatile acidity', 'citric acid', 'residual sugar', 
                            'chlorides', 'free sulfur dioxide', 'total sulfur dioxide', 'density', 
                            'pH', 'sulphates', 'alcohol']]
# 给自变量添加常数项(用于拟合截距)
independent_variables = sm.add_constant(independent_variables)
dependent_variable = df['quality']
# 拟合OLS回归模型
regression_model = sm.OLS(dependent_variable, independent_variables).fit()

# 输出标准回归结果摘要
print(regression_model.summary())

关键修正说明

  • 将纯列名字符串列表替换为df[['列名1', '列名2', ...]],这样获取的是包含数值数据的DataFrame,满足statsmodels的输入要求。
  • sm.add_constant()会自动在自变量数据集前添加全1的常数项,用于模型截距的拟合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 13:55:12