繁体   English   中英

带约束截距的线性回归

[英]Linear regression with constrained intercept

我确实想使用截距值进行约束线性回归,如下所示:lowerbound<=intercept<=upperbound。

我知道我可以使用一些 python 库来限制系数,但找不到可以限制截距的库。

我想要的是在截距在我定义的范围内的约束下,以最小的可能错误获得适合我的数据点的最佳解决方案。

如何在 python 中做到这一点?

这是一个使用带有参数边界的curve_fit的示例。 在这个例子中,参数“a”是无界的,参数“b”是有界的,拟合值在这些范围内,参数“c”是有界的,拟合值是有界的。

import numpy
import matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

xData = numpy.array([5.0, 6.1, 7.2, 8.3, 9.4])
yData = numpy.array([ 10.0,  18.4,  20.8,  23.2,  35.0])


def standardFunc(data, a, b, c):
    return a * data + b * data**2 + c


# some initial parameter values - must be within bounds
initialParameters = numpy.array([1.0, 1.0, 1.0])

# bounds on parameters - initial parameters must be within these
lowerBounds = (-numpy.Inf, -100.0, -5.0)
upperBounds = (numpy.Inf, 100.0, 5.0)
parameterBounds = [lowerBounds, upperBounds]

fittedParameters, pcov = curve_fit(standardFunc, xData, yData, initialParameters, bounds = parameterBounds)

# values for display of fitted function
a, b, c = fittedParameters

# for plotting the fitting results
xPlotData = numpy.linspace(min(xData), max(xData), 50)
y_plot = standardFunc(xPlotData, a, b, c)

plt.plot(xData, yData, 'D') # plot the raw data as a scatterplot
plt.plot(xPlotData, y_plot) # plot the equation using the fitted parameters
plt.show()

print('fitted parameters:', fittedParameters)

更新:根据评论,这是一个多元拟合示例:

import numpy
from scipy.optimize import curve_fit

X1 = (-1.0, -2.2, -3.3, -4.4, -5.5, -6.7)
X2 = (21.0, 22.2, 23.3, 24.4, 25.5, 26.7)
X3 = (51.0, 52.2, 53.3, 54.4, 55.5, 56.7)
all_X_data = numpy.array([X1, X2, X3])

Y = (11.1, 12.1, 13.1, 14.1, 15.1, 16.1)


# function to be fitted
def modelFunction(data, a, b, c, offset):
    f = (data[0] * a) + (data[1] * b) + (data[2] * c) + offset
    return f


# some initial parameter values
# these might be estimated from scatterplots
initialParameters = (1.0, 1.0, 1.0, 1.0)

# perform the fit
fittedParameters, pcov = curve_fit(modelFunction, all_X_data, Y, initialParameters)

print('a, b, c, offset:', fittedParameters)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM