簡體   English   中英

帶約束的簡單線性回歸

[英]Simple linear regression with constraint

我開發了一種算法來循環遍歷 15 個變量並為每個變量生成一個簡單的 OLS。 然后算法再循環 11 次以產生相同的 15 個 OLS 回歸,但 X 變量的滯后每次增加 1。 我選擇具有最高 r^2 的自變量並使用 3,4 或 5 個變量的最佳滯后

IE

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 回歸使用以下代碼:

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

這很好用,

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]

根據評論,這里是使用 scipy 的差分進化模塊來確定有界參數估計的示例。 該模塊在內部使用拉丁超立方體算法來確保對參數空間進行徹底搜索,並且需要在其中進行搜索的邊界,盡管這些邊界可能很大。 默認情況下,different_evolution 模塊將在內部以使用邊界調用 curve_fit() 結束 - 這可以禁用 - 並確保最終擬合參數不受限制,此示例稍后調用 curve_fit 而不通過邊界。 您可以從打印的結果中看到,對different_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)

我不知道你可以很容易地限制系數,我有兩種解決方案,

1- 使用導致負系數的時間序列的逆 (1/x)。 這將要求您首先進行正常回歸,然后將具有負面關系的回歸。 獲取權重並計算 wi/sum(wi)。

2-似乎您正在處理時間序列,使用對數差異(np.log(ts).diff().dropna()) 作為輸入並獲得權重。 如有必要,將其除以權重總和,並通過 np.exp(predicted_ts.cumsum()) 恢復您的估計。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM