【问题标题】:Interpolate without having negative values in python在python中没有负值的插值
【发布时间】:2017-02-25 14:42:30
【问题描述】:

我一直在尝试根据这些值创建一条平滑线,但我的结果中不能有负值。到目前为止,我尝试的所有方法都给出了负值。希望得到一些帮助。

import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
import numpy as np
y = np.asarray([0,5,80,10,1,10,40,30,80,5,0])
x = np.arange(len(y))

plt.plot(x, y, 'r', ms=5)
spl = UnivariateSpline(x, y)
xs = np.linspace(0,len(y)-1, 1000)
spl.set_smoothing_factor(2)

plt.plot(xs, spl(xs), 'g', lw=3)
plt.show()

【问题讨论】:

    标签: python numpy matplotlib scipy interpolation


    【解决方案1】:

    已知样条拟合会过冲。您似乎正在寻找所谓的 monotonic 插值器之一。例如,

    In [10]: from scipy.interpolate import pchip
    
    In [11]: pch = pchip(x, y)
    

    生产

    In [12]: xx = np.linspace(x[0], x[-1], 101)
    
    In [13]: plt.plot(x, y, 'ro', label='points')
    Out[13]: [<matplotlib.lines.Line2D at 0x7fce0a7fe390>]
    
    In [14]: plt.plot(xx, pch(xx), 'g-', label='pchip')
    Out[14]: [<matplotlib.lines.Line2D at 0x7fce0a834b10>]
    

    【讨论】:

    • 太棒了!正是我需要的
    【解决方案2】:

    这样做,尽管在某些部分比其他部分更好。

    import matplotlib.pyplot as plt
    from scipy.interpolate import UnivariateSpline
    import numpy as np
    
    y = np.asarray([0,5,80,10,1,10,40,30,80,5,0])
    x = np.arange(len(y))
    
    plt.plot(x, y, 'r', ms=5)
    spl = UnivariateSpline(x, y)
    xs = np.linspace(0,len(y)-1, 1000)
    spl.set_smoothing_factor(2)
    
    #new code
    ny = spl(xs).clip(0,max(spl(x)))
    spl2 = UnivariateSpline(xs, ny)
    
    plt.plot(xs, spl(xs) , 'g', lw=2,label="original")
    plt.plot(xs, spl2(xs), 'b', lw=2,label="stack mod")
    
    plt.legend()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2012-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 2020-08-12
      • 2018-03-29
      • 1970-01-01
      相关资源
      最近更新 更多