用多项函数拟合多项式

时间:2018-12-04 20:28:40

标签: python regression

假设我有一个名为Y的数组和另一个名为X的数组。我知道如何使用numpy.polyfit()来拟合多项式,作为输出,我将得到一个带有系数的数组。但是,如果我想添加一些函数f(x)作为多项式的附加回归函数,该如何在python中实现呢?

例如Y = [1,2,3,4,5,6]X = [101,102,103,104,105,106]。我知道如何估算y = a_0+a_1x+a_2x^2+a_3x^3的系数(3阶多项式),我可以使用z = numpy.polyfit(Y, X, 3)进行估算。现在,我想估计y = a_0+a_1x+a_2x^2+a_3x^3 + a_4f(x),其中f(x)是一些函数。我是Python新手,在Google上找不到答案

2 个答案:

答案 0 :(得分:1)

scipy.optimize.curve_fit是您要寻找的。它可以采用任意函数,因此可以在该函数中定义多项式项和附加函数项。

def f(x, a0, a1, a2, a3, a4):
  func_term = np.exp(-abs(x))  # can be anything you need
  return a0 + a1 * x + a2 * x**2 + a3 * x**3 + a4 * func_term

然后拟合曲线:

popt, _ = curve_fit(f, xdata, ydata)

答案 1 :(得分:1)

这里是使用Gerges Dib的答案中提供的示例函数的图形拟合器代码。请注意,scipy的curve_fit()是一个非线性求解器,需要初始参数估计作为起点,并且如果您不提供任何参数,则默认情况下所有这些参数的值均为1.0。在这里,您可以看到拟合的结果在外观上看起来不错,但如果不是这种情况,则可能是由于初始参数估计值引起的-有时会发生这种情况。 Scipy具有遗传算法可帮助确定初始参数估计值,在此示例中,这不是必需的。

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

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(x, a0, a1, a2, a3, a4): # Gerges Dib gave this example function
    func_term = numpy.exp(-abs(x))  # can be anything you need
    return a0 + a1 * x + a2 * x**2 + a3 * x**3 + a4 * func_term


fittedParameters, pcov = curve_fit(func, xData, yData)
print('Fitted parameters:', 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

    axes.set_title('Gerges Dib example function')

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

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

example