Py学习  »  Python

如何在python中向回归添加sum-to-1约束?

amaatouq • 5 年前 • 1897 次点击  

我使用statsmodels(对其他python选项开放)来运行一些线性回归。我的问题是,我需要回归没有截距和限制系数的范围(0,1),也总和为1。

我试过这样的方法(至少是1的总和):

from statsmodels.formula.api import glm
import pandas as pd

df = pd.DataFrame({'revised_guess':[0.6], "self":[0.55], "alter_1":[0.45], "alter_2":[0.2],"alter_3":[0.8]})
mod = glm("revised_guess ~ self + alter_1 + alter_2 + alter_3 - 1", data=df)
res = mod.fit_constrained(["self + alter_1 + alter_2 + alter_3  = 1"],
                          start_params=[0.25,0.25,0.25,0.25])
res.summary()

但仍在努力实施“非负”系数约束。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43876
 
1897 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Justice_Lords
Reply   •   1 楼
Justice_Lords    6 年前

你可以 nnls(非负最小二乘法) 这是在scipy下定义的。基于 福特朗 非负最小二乘解算器。不能向其添加约束。所以再加上一个等式 x1+x2+x3=1 输入方程式。

import numpy as np
from scipy.optimize import nnls 
##Define the input vectors
A = np.array([[1., 2., 5.], 
              [5., 6., 4.],
              [1.,  1.,   1. ]])

b = np.array([4., 7., 2.])

##Caluculate nnls
x, resdiual_norm = nnls(A,b)


##Find the difference
print(np.sum(A*x,1)-b)

现在对这个矩阵执行nnls,它将返回x值和残差。

Rubens_Zimbres
Reply   •   2 楼
Rubens_Zimbres    6 年前

简单地进行l1正则化回归:

import statsmodels.api as sm
from statsmodels.regression.linear_model import OLS
model = sm.OLS(Y,X)
model2=model.fit_regularized(method='elastic_net', alpha=0.0, L1_wt=1.0, start_params=None, profile_scale=False, refit=False)
model2.params

…调整超参数。