从曲线数据点推断
我有点搞不清楚如何从一个数据集中推断出结果,特别是当这些点没有按照顺序排列时,比如说'x'的值是递减的,像这样:
http://www.pic-host.org/images/2014/07/21/0b5ad6a11266f549.png
我明白我需要分别为x和y的值创建一个图表。所以这段代码可以让我得到这个结果:(这些点是有序的)
x = bananax
y = bananay
t = np.arange(x.shape[0], dtype=float)
t /= t[-1]
nt = np.linspace(0, 1, 100)
x1 = scipy.interpolate.spline(t, x, nt)
y1 = scipy.interpolate.spline(t, y, nt)
plt.plot(nt, x1, label='data x')
plt.plot(nt, y1, label='data y')
现在我得到了插值样条。我想我需要分别对f(nt)=x1和f(nt)=y1进行外推。我知道如何通过简单的线性回归从数据中进行插值,但我不太清楚如何从中得到一个更复杂的样条进行外推。
我的目标是让外推的函数跟随数据点的曲线(至少在一端)。
谢谢!
2 个回答
我觉得你走在正确的道路上,因为你正在创建一个参数曲线(也就是生成 x(t) 和 y(t)),因为这些点是有顺序的。问题的一部分似乎在于 spline
函数返回的是离散值,而不是样条曲线的形式和参数。scipy.optimize
有一些很不错的工具,可以帮助你找到函数,而不是单纯计算点。
如果你对生成数据的底层过程有一些了解,我建议你利用这些信息来帮助选择一个合适的函数形式进行拟合。这些更自由的方式会给你一定的灵活性。
你可以拟合 x(t) 和 y(t),并保留得到的拟合函数。它们会根据从 t=0
到 t=1
的数据生成,但没有什么能阻止你在这个范围之外进行评估。
我可以推荐以下链接,帮助你了解曲线拟合的过程:
简短版: http://glowingpython.blogspot.com/2011/05/curve-fitting-using-fmin.html
详细版: http://nbviewer.ipython.org/gist/keflavich/4042018
*几乎没有什么
谢谢你,这让我找到了正确的方向。对我有效的是:
x = bananax
y = bananay
#------ fit a spline to the coordinates, x and y axis are interpolated towards t
t = np.arange(x.shape[0], dtype=float) #t is # of values
t /= t[-1] #t is now devided from 0 to 1
nt = np.linspace(0, 1, 100) #nt is array with values from 0 to 1 with 100 intermediate values
x1 = scipy.interpolate.spline(t, x, nt) #The x values where spline should estimate the y values
y1 = scipy.interpolate.spline(t, y, nt)
#------ create a new linear space for nnt in which an extrapolation from the interpolated spline will be made
nnt = np.linspace(-1, 1, 100) #values <0 are extrapolated (interpolation started at the tip(=0)
x1fit = np.polyfit(nt,x1,3) #fits a polynomial function of the nth order with the spline as input, output are the function parameters
y1fit = np.polyfit(nt,y1,3)
xpoly = np.poly1d(x1fit) #genereates the function based on the parameters obtained by polyfit
ypoly = np.poly1d(y1fit)