在Python中将曲线拟合到数据集时 [英] On fitting a curved line to a dataset in Python

查看:74
本文介绍了在Python中将曲线拟合到数据集时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两个数据集的图,它会产生轻微的梯度,其中最佳拟合曲线可能会被过度绘制.

I have a plot with two data sets which produces a slight gradient, where a curved line of best fit may be overplotted.

目前我只能找到一条最适合的直线.我知道 scipy.optimize.curve_fit 应该能够帮助我,但这需要我知道我想要过度绘制的函数(我认为).

At the moment I have only managed to get a straight line of best fit. I understand scipy.optimize.curve_fit should be able to help me, but this requires me to know the function I want to overplot (I think).

以下是我的代码和绘图.如何为这些数据集创建曲线图?

Below are my code and plots. How would one go about creating a curved plot for these data sets?

plt.figure(figsize=(15,6.6))
pl.subplot(1,2,1) 
plt.plot(gg,AA, 'kx')
plt.xlabel('x')
plt.ylabel('y')
plt.gca().invert_yaxis()
y=AA
x=gg
fit=pl.polyfit(x,y,1)
#slope, fit_fn=pl.poly1d(fit)
fit_fn=pl.poly1d(fit)
scat=pl.plot(x,y, 'kx', x,fit_fn(x), '-b' )


pl.subplot(1,2,2) 
pl.plot(LL,pp, 'kx')#shows points with no removal or bestfit
plt.gca().invert_yaxis()

plt.savefig('1.jpg')
plt.show()

应该指出的是,可能没有曲线,但我想知道是否有一条曲线可以拟合.

It should be noted that there is possibly no curve but I want to discover if there is one which would fit.

推荐答案

如果我很好理解,您的问题将是一个概念性问题,而不是实用性问题.

If I understand well, your question is much rather a conceptual than a practical one.

如果要显示一条稍微代表您的数据集的线,可以从三件事开始:移动平均,插值和多项式拟合.

If you want to show a line that somewhat represents your dataset, you could start with three things: moving average, interpolation and polynomial fit.

移动平均可以很好地平滑您的数据集.我不知道它的内置功能,但是您可以自己编写它,因为它已经在这里.

Moving average smoothes your dataset nicely. I'm not aware of a built-in function for it, but you can code it yourself, as it was discussed here.

插值(样条线(例如)适合您的数据集上的某些函数,可以在许多点对其进行评估然后进行绘制.

Interpolation (spline, for example) fits some function on your dataset which can be evaluated at many points and then plotted.

使用上述两种方法,您不必指定函数.但是,您可以自己拟合多项式函数.如何确定多项式的次数?您可以获取所有数据点的对数,将线性线拟合到对数数据中,如果拟合良好,则可以将线性部分的系数视为多项式对原始数据集的次数.但是,不要使用过多的多项式-您可以轻松地为此过度拟合方法.

With the two mentioned methods, you don't have to specify a function. However, you can fit a polynomial function yourself. How to determine the degree of the polynomial? You can take the log of all your data points, fit a linear line to the log data, and IF IT FITS WELL, the coefficient of the linear part can be considered as the degree of the polynomial to the original dataset. However, don't use too large degree of polynomials - you can easily run into overfitting with this method.

这篇关于在Python中将曲线拟合到数据集时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆