Линейная регрессия с ограниченным перехватом - PullRequest
0 голосов
/ 02 ноября 2019

Я хочу сделать ограниченную линейную регрессию со значением перехвата, подобным: lowerbound <= intercept <= upperbound. </p>

Я знаю, что могу ограничить коэффициенты некоторыми библиотеками python, но не смог найти тот, где я могу ограничить перехват.

Я хочу получить лучшее решение, подходящее для моеготочки данных с минимально возможной ошибкой в ​​ограничении, где точка пересечения находится в определенном мною диапазоне.

Как я могу это сделать в python?

1 Ответ

1 голос
/ 02 ноября 2019

Вот пример использования 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)
...