仅将曲线拟合到几个数据点

2024-10-02 10:25:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个只有5个数据点的散点图,我想拟合一条曲线。我尝试过polyfit和下面的代码,但是都不能用这么少的数据点生成曲线

def func(x, a, b, c):
 return a * np.exp(-b * x) + c
plt.plot(xdata, ydata, ".", label="Data");
optimizedParameters, pcov = opt.curve_fit(func, xdata, ydata);
plt.plot(xdata, func(xdata, *optimizedParameters), label="fit");

附件是一个情节的例子,以及一个我试图产生的曲线的例子(为糟糕的绘图道歉)。谢谢!在

enter image description here


Tags: 数据代码returnplotdefplt曲线label
3条回答

你必须选择你想要的适合曲线运动员之后。从你的绘画的外观看,你似乎在试图把它塑造成某种对数。

这是对数回归的图片:

enter image description here

对数回归的形式为y=A+B ln(x)。 这基本上是线性回归拟合,而不是拟合y与x 我们正在尝试适合y和ln(x)。

所以,您可以只需要获取数据集中点的x值的自然日志,并在它上执行线性回归算法。屈服系数为y=A+B ln(x)的A和B。

图片学分: http://mathworld.wolfram.com/LeastSquaresFittingLogarithmic.html

编辑:正如詹姆斯·菲利普斯在回答中指出的,也可以用y=Ax^(-B)+C的形式对曲线进行建模,因为对于如此少的点,如果图形具有水平渐近线或总是增长但减速,则无法确定。很多曲线都可能(例如y=A*B^(-x)+C可能是另一条曲线),但您需要选择之后的数据模型。

下面是一个使用注释中的数据的Python fitter示例,它适合于一个多形类型的等式。在这个例子中,不需要记录数据。这里X轴是按十年对数标度绘制的。请注意,示例代码中的数据是浮点数形式。在

plot

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

xData = numpy.array([7e-09, 9e-09, 1e-08, 2e-8, 1e-6])
yData = numpy.array([790.0, 870.0, 2400.0, 2450.0, 3100.0])


def func(x, a, b, offset): # polytrope equation from zunzun.com
    return  a / numpy.power(x, b) + offset


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

# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)

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), 1000)
    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.xscale('log') # comment this out for default linear scaling


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

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

指数函数不适合你的数据。考虑另一个建模函数。在

给定

 import numpy as np
 import scipy.optimize as opt
 import matplotlib.pyplot as plt


%matplotlib inline


x_samp = np.array([7e-09, 9e-09, 1e-08, 2e-8, 1e-6])
y_samp = np.array([790, 870, 2400, 2450, 3100])


def func(x, a, b):
    """Return a exponential result."""
    return a + b*np.log(x)


def func2(x, a, b, c):
    """Return a 'power law' result."""
    return a/np.power(x, b) + c

编码

根据@Allan Lago的对数模型:

^{pr2}$

Estimated Parameters [8339.61062739  367.6992259 ]

enter image description here

使用@James Phillips的“多向性”模型:

# REGRESSION                                  
p0 = [1, 1, 1]
w, _ = opt.curve_fit(func2, x_samp, y_samp, p0=p0)     
print("Estimated Parameters", w)  

# Model
y_model = func2(x_lin, *w)


# PLOT                                     
# Visualize data and fitted curves
plt.plot(x_samp, y_samp, "ko", label="Data")
plt.plot(x_lin, y_model, "k ", label="Fit")
plt.xticks(np.arange(0, x_samp.max(), x_samp.max()/2))
plt.title("Least squares regression")
plt.legend()

Estimated Parameters [-3.49305043e-10  1.57259788e+00  3.05801283e+03]

enter image description here

相关问题 更多 >

    热门问题