首页 > 解决方案 > 如何使用点数组执行曲线拟合并触摸该数组中的特定点

问题描述

我需要曲线拟合一组给定点的帮助。这些点形成抛物线,我应该找到结果的峰值点。问题是当我进行曲线拟合时,即使输入数组中给出了实际点,它有时也不会触及最大 y 坐标。以下是代码片段。这里 1.88 是实际峰值 y 坐标 (13.05,1.88)。但是由于曲线拟合,代码生成的图形并没有触及该点。那么有没有办法拟合曲线以确保它触及输入数组中给出的最大点?

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit, minimize_scalar
fig = plt.gcf()
#fig.set_size_inches(18.5, 10.5)

x = [4.59,9.02,13.05,18.47,20.3]
y = [1.7,1.84,1.88,1.7,1.64]

def f(x, p1, p2, p3):
    return p3*(p1/((x-p2)**2 + (p1/2)**2))   

plt.plot(x,y,"ro")
popt, pcov = curve_fit(f, x, y)

# find the peak
fm = lambda x: -f(x, *popt)
r = minimize_scalar(fm, bounds=(1, 5))
print( "maximum:", r["x"], f(r["x"], *popt) )  #maximum: 2.99846874275 18.3928199902
plt.text(1,1.9,'maximum '+str(round(r["x"],2))+'( @'+str(round(f(r["x"], *popt),2)) + ' )') 
x_curve = np.linspace(min(x), max(x), 50)
plt.plot(x_curve, f(x_curve, *popt))
plt.plot(r['x'], f(r['x'], *popt), 'ko')
plt.show()

标签: curve-fitting

解决方案


这是一个使用带有加权拟合的方程的图形代码示例,我将最大点设置得更大,以便更容易地看到加权的效果。在非加权曲线拟合中,所有权重都隐含为 1.0,因为所有数据点的权重相同。Scipy 的 curve_fit 例程使用不确定性形式的权重,因此给一个点一个非常小的不确定性(我已经做过)就像给这个点一个非常大的权重。该技术可用于通过任何可以执行加权拟合的软件任意接近任何单个数据点的拟合传递。

阴谋

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

x = [4.59,9.02,13.05,18.47,20.3]
y = [1.7,1.84,2.0,1.7,1.64]


# note the single very small uncertainty - try making this value 1.0
uncertainties = numpy.array([1.0, 1.0, 1.0E-6, 1.0, 1.0])


# rename data to use previous example
xData = numpy.array(x)
yData = numpy.array(y)


def func(x, p1, p2, p3):
    return p3*(p1/((x-p2)**2 + (p1/2)**2))   


# these are the same as the scipy defaults
initialParameters = numpy.array([1.0, 1.0, 1.0])

# curve fit the test data, first without uncertainties to
# get us closer to initial starting parameters
ssqParameters, pcov = curve_fit(func, xData, yData, p0 = initialParameters)

# now that we have better starting parameters, use uncertainties
fittedParameters, pcov = curve_fit(func, xData, yData, p0 = ssqParameters, sigma=uncertainties, absolute_sigma=True)

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('Parameters:', fittedParameters)
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)

推荐阅读