Python实现Linear Regression及获取拟合参数Standard Deviation问题求解
问题原因
- 参数顺序错误:
sm.OLS()要求第一个输入为因变量(待拟合的目标数组),第二个输入为自变量矩阵,你写反了两个参数的位置 - 维度不匹配:你定义的自变量数组
a形状为(2, 3),要求自变量矩阵的行数必须和因变量的长度一致(3行,对应3个样本点),需要将自变量矩阵转置为(3, 2)格式,每行对应一组[A1取值, A2取值]
修正后代码
无截距项版本(匹配你的公式 B1 = a*A1 + b*A2)
import numpy as np import statsmodels.api as sm # 构造自变量矩阵,转置后每行对应一个样本的两个特征 exog = np.array([[1, 2, 3], [4, 5, 6]]).T # 因变量为目标曲线B1 endog = np.array([4, 5, 3]) # 构建OLS模型并拟合 model = sm.OLS(endog, exog) results = model.fit() # 输出完整拟合结果,包含参数值、标准差、p值等指标 print(results.summary()) # 单独提取拟合参数的标准差 params_standard_deviation = results.bse print("拟合参数标准差:", params_standard_deviation)
带截距项版本(若你需要拟合公式为 B1 = c + a*A1 + b*A2)
只需要给自变量矩阵添加常数项即可:
# 给自变量矩阵添加截距项列 exog_with_const = sm.add_constant(exog) model_with_const = sm.OLS(endog, exog_with_const) results_with_const = model_with_const.fit() print(results_with_const.summary()) print("带截距的参数标准差:", results_with_const.bse)
关键说明
拟合结果对象的bse属性返回的就是所有拟合参数的标准差,对应你需要的Standard Deviation。
内容的提问来源于stack exchange,提问作者smallbirds
相关产品推荐
相关产品推荐

