带约束的简单线性回归

3
我已经开发了一个算法,可以循环处理15个变量并为每个变量生成简单的OLS。然后该算法再循环11次,以产生相同的15个OLS回归,但X变量的滞后期每次增加1。我选择具有最高r^2的自变量,并使用3、4或5个变量的最佳滞后期。
Y_t+1 - Y_t = B ( X_t+k - X_t) + e

我的数据集看起来像这样:

Regression = pd.DataFrame(np.random.randint(low=0, high=10, size=(100, 6)), 
                columns=['Y', 'X1', 'X2', 'X3', 'X4','X5'])

我已经拟合的OLS回归使用以下代码:

到目前为止,我拟合的OLS回归使用以下代码:

Y = Regression['Y']
X = Regression[['X1','X2','X3']]

Model = sm.OLS(Y,X).fit()
predictions = Model.predict(X)

Model.summary()

问题在于使用OLS时,可能会得到负系数(我就是这样)。我希望能够通过以下方法约束模型:
sum(B_i) = 1

B_i >= 0

你是否愿意使用非线性方法,例如scipy.optimize.curve_fit(),并且可能从scipy.optimize.differential_evolution()中获取初始参数估计?这将允许一个简单的“砖墙”类型的约束,其中对于超出约束的参数值返回硬编码的大值 - 因此返回大误差。实际上,当优化离开约束区域时,它会遇到无法克服的“砖墙”。虽然简单粗暴,但这种技术可以是一种有效的约束参数值的方法,并且易于编写和测试。 - James Phillips
我会尝试一下。 - 78282219
如果需要的话,我可以提供一个示例。 - James Phillips
我会很感激的,我整天都在阅读关于QP、套索和其他可能的方法,现在我的大脑已经疲惫不堪了。 - 78282219
如果你想走得更远,可以使用结构方程模型来进行参数约束。不确定是否有一种好的方法可以使用OLS回归来实现。 - Simon
3个回答

5

这个很好用,

from scipy.optimize import minimize

# Define the Model
model = lambda b, X: b[0] * X[:,0] + b[1] * X[:,1] + b[2] * X[:,2]

# The objective Function to minimize (least-squares regression)
obj = lambda b, Y, X: np.sum(np.abs(Y-model(b, X))**2)

# Bounds: b[0], b[1], b[2] >= 0
bnds = [(0, None), (0, None), (0, None)]

# Constraint: b[0] + b[1] + b[2] - 1 = 0
cons = [{"type": "eq", "fun": lambda b: b[0]+b[1]+b[2] - 1}]

# Initial guess for b[1], b[2], b[3]:
xinit = np.array([0, 0, 1])

res = minimize(obj, args=(Y, X), x0=xinit, bounds=bnds, constraints=cons)

print(f"b1={res.x[0]}, b2={res.x[1]}, b3={res.x[2]}")

#Save the coefficients for further analysis on goodness of fit

beta1 = res.x[0]

beta2 = res.x[1]

beta3 = res.x[2]

3

根据评论,这里是使用scipy的differential_evolution模块确定有界参数估计的示例。该模块内部使用拉丁超立方算法来确保对参数空间进行彻底搜索,并需要在其中搜索的边界,虽然这些边界可以很宽松。默认情况下,differential_evolution模块将在使用边界后内部以curve_fit()的调用结束-这可以禁用-并确保最终拟合的参数没有被限制,此示例通过稍后调用curve_fit而不传递边界来实现。从打印结果中可以看出,对differential_evolution的调用显示第一个参数受到-0.185的限制,而这不适用于稍后对curve_fit()的调用。在您的情况下,您可以使下限为零,以便参数不为负数,但如果代码导致参数达到或非常接近边界,则这不是最佳选择,如此示例所示。

import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.optimize import differential_evolution
import warnings

xData = numpy.array([19.1647, 18.0189, 16.9550, 15.7683, 14.7044, 13.6269, 12.6040, 11.4309, 10.2987, 9.23465, 8.18440, 7.89789, 7.62498, 7.36571, 7.01106, 6.71094, 6.46548, 6.27436, 6.16543, 6.05569, 5.91904, 5.78247, 5.53661, 4.85425, 4.29468, 3.74888, 3.16206, 2.58882, 1.93371, 1.52426, 1.14211, 0.719035, 0.377708, 0.0226971, -0.223181, -0.537231, -0.878491, -1.27484, -1.45266, -1.57583, -1.61717])
yData = numpy.array([0.644557, 0.641059, 0.637555, 0.634059, 0.634135, 0.631825, 0.631899, 0.627209, 0.622516, 0.617818, 0.616103, 0.613736, 0.610175, 0.606613, 0.605445, 0.603676, 0.604887, 0.600127, 0.604909, 0.588207, 0.581056, 0.576292, 0.566761, 0.555472, 0.545367, 0.538842, 0.529336, 0.518635, 0.506747, 0.499018, 0.491885, 0.484754, 0.475230, 0.464514, 0.454387, 0.444861, 0.437128, 0.415076, 0.401363, 0.390034, 0.378698])


def func(t, n_0, L, offset): #exponential curve fitting function
    return n_0*numpy.exp(-L*t) + offset


# function for genetic algorithm to minimize (sum of squared error)
def sumOfSquaredError(parameterTuple):
    warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm
    val = func(xData, *parameterTuple)
    return numpy.sum((yData - val) ** 2.0)


def generate_Initial_Parameters():
    # min and max used for bounds
    maxX = max(xData)
    minX = min(xData)
    maxY = max(yData)
    minY = min(yData)

    parameterBounds = []
    parameterBounds.append([-0.185, maxX]) # seach bounds for n_0
    parameterBounds.append([minX, maxX]) # seach bounds for L
    parameterBounds.append([0.0, maxY]) # seach bounds for Offset

    # "seed" the numpy random number generator for repeatable results
    result = differential_evolution(sumOfSquaredError, parameterBounds, seed=3)
    return result.x

# by default, differential_evolution completes by calling
# curve_fit() using parameter bounds
geneticParameters = generate_Initial_Parameters()
print('fit with parameter bounds (note the -0.185)')
print(geneticParameters)
print()

# second call to curve_fit made with no bounds for comparison
fittedParameters, pcov = curve_fit(func, xData, yData, geneticParameters)

print('re-fit with no parameter bounds')
print(fittedParameters)
print()

modelPredictions = func(xData, *fittedParameters) 

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))

print()
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()


##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = func(xModel, *fittedParameters)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)

0

我不知道你是否能轻松地限制系数,我有两个解决方案备选:

1-使用时间序列的倒数(1/x),以消除产生负系数的关系。这将要求您首先进行普通回归,然后再反转那些具有负相关性的系数。获取权重并执行wi/sum(wi)。

2-看起来你在处理时间序列,使用对数差(np.log(ts).diff().dropna())作为输入并获取权重。如有必要,将其除以权重总和,并通过np.exp(predicted_ts.cumsum())还原您的估计。


我也打算尝试对数差分。然而,它不会严格满足我的第二个约束条件:sum(beta)=1。 - 78282219

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接