【问题标题】:Least-square spline interpolation forcing interpolant to pass through specific points最小二乘样条插值强制插值通过特定点
【发布时间】:2019-06-07 06:50:34
【问题描述】:

我在实现一些不太常见的插值问题时遇到了问题。我有一些(x,y)数据点散布在我不知道的先验曲线上,我想尽我所能重建这条曲线,用最小平方误差对我的点进行插值。我曾想过为此目的使用scipy.interpolate.splrep(但也许您会建议使用更好的选项)。在我的情况下,另一个困难是我想约束样条曲线通过我的原始数据的一些特定点。我认为玩结和权重可能会成功,但我不知道该怎么做(除了基本的拟合程序外,我还在拖延避免样条插值理论)。此外,由于一些未公开的原因,当我尝试在我的splrep 中设置结时,我得到了与this post 相同的错误,这使事情变得复杂。以下是我的示例代码:

from __future__ import division
import numpy as np
import scipy.interpolate as spi
import matplotlib.pylab as plt

# Some surrogate sample data
f = lambda x : x**2 - x/2.
x = np.arange(0.,20.,0.1)
y = f(4*(x + np.random.normal(size=np.size(x))))

# I want to use spline interpolation with least-square fitting criterion, making sure though that the spline starts
# from the origin (or in general passes through a precise point of my dataset). 
# In my case for example I would like the spline to originate from the point in x=0. So I attempted to include as first knot x=0... 
# but it won't work, nor I am sure this is the right procedure...

fy = spi.splrep(x,y)
fy = spi.splrep(x,y,t=fy[0])
yy = spi.splev(x,fy)

plt.plot(x,y,'-',x,yy,'--')
plt.show()

尽管我什至传递了从第一次调用 splrep 计算的结,但它会给我:

  File "/usr/lib64/python2.7/site-packages/scipy/interpolate/fitpack.py", line 289, in splrep
    res = _impl.splrep(x, y, w, xb, xe, k, task, s, t, full_output, per, quiet)
  File "/usr/lib64/python2.7/site-packages/scipy/interpolate/_fitpack_impl.py", line 515, in splrep
    raise _iermess[ier][1](_iermess[ier][0])
ValueError: Error on input data

【问题讨论】:

    标签: python scipy constraints interpolation spline


    【解决方案1】:

    您使用splrep 的权重参数:可以给这些点您需要固定的非常大的权重。这肯定是一种解决方法,因此请注意合身质量和稳定性。

    【讨论】:

    • 好的,它可以工作。然而,理想的情况是在极值点也有样条插值匹配导数。例如,MATLAB 在spline(x,y,xq) 函数中有这样一个选项,它只提供len(x)+2y,其中y[0]y[-1](分别是y(1)y(end) 在MATLAB 表示法中)是这些点的导数.我也可以在 python 中轻松实现这一点吗?
    • 谢谢。我知道BSPline.from_derivativessplprep,但正如您所指出的,与spline 结合使用的配件目前在scipy 中不可用。所以我需要找出一个替代解决方案。如果我在原来的问题中设置了结怎么办?如何将结与重量结合起来?它是直截了当的吗?
    【解决方案2】:

    按照@ev-br 的建议,为特定点设置高权重确实是一种可行的解决方案。此外,由于没有直接的方法来匹配曲线极值处的导数,因此在这种情况下也可以应用相同的原理。假设您希望 y[0]y[-1] 中的导数与您的数据点的导数相匹配,那么您还为 y[1]y[-2] 添加较大的权重,即

    weights = np.ones(len(x))
    weights[[0,-1]] = 100  # Promote spline interpolant through first and last point
    weights[[1,-2]] = 50   # Make spline interpolant derivative tend to derivatives at first/last point
    fy = spi.splrep(x,y,w=weights,s=0.1)
    yy = spi.splev(x,fy)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-24
      • 2021-10-18
      • 2020-08-25
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 2021-03-09
      相关资源
      最近更新 更多