如何在 statsmodels OLS 中指定约束?

问题描述 投票:0回答:1

我正在使用 statsmodels OLS 对我的数据运行一些线性回归。我的问题是我希望系数加起来为 1(我计划不使用常量参数)。

是否可以在 statsmodels OLS 中对系数指定至少 1 个约束?我看不出这样做的选择。

python statsmodels
1个回答
0
投票

要在

statsmodels
OLS 中指定约束,例如将系数加起来达到特定值,您可以使用
fit_constrained
方法。该方法允许将线性等式约束应用于回归模型。

以下是使用

statsmodels
在 OLS 模型中应用此约束的分步指南:

首先,拟合 OLS 模型。如果您打算不使用常量参数,请在模型公式中包含 - 1 以排除截距。

import pandas as pd
import statsmodels.formula.api as smf

# Assuming df is your DataFrame
df = pd.read_csv('your_data.csv')  # Replace with the path to your dataset

# Fit the OLS model without a constant
model = smf.ols('dependent_variable ~ IV1 + IV2 + IV3 - 1', data=df).fit()

使用

fit_constrained
方法应用约束。例如,如果您希望三个变量 (
IV
IV2
IV3
) 的系数之和等于 1,则约束表达式将为
IV1 + IV2 + IV3 = 1

# Constraint expression
constraint_expr = 'IV1 + IV2 + IV3 = 1'

# Apply the constraint
model_constrained = model.fit_constrained(constraint_expr)

# Print the summary of the model with constraints
print(model_constrained.summary())

在此设置中,

constraint_expr
是一个字符串,表示您正在应用的线性等式约束。表达式
IV1 + IV2 + IV3 = 1
确保自变量的系数总和等于 1。

© www.soinside.com 2019 - 2024. All rights reserved.