欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

线性插值的 Python 实现详解

最编程 2024-06-22 16:25:09
...

在算法分析过程中,我们经常会遇到数据需要处理插值的过程,为了方便理解,我们这里给出相关概念和源程序,希望能帮助到您!

案例一:

已知坐标 (x0, y0) 与 (x1, y1),要求得区间 [x0, x1] 内某一点位置 x 在直线上的y值。两点间直线方程,我们有
y=y_{0}+\left(x-x_{0}\right) \frac{y_{1}-y_{0}}{x_{1}-x_{0}}=y_{0}+\frac{\left(x-x_{0}\right) y_{1}-\left(x-x_{0}\right) y_{0}}{x_{1}-x_{0}}

那么,如何实现它呢?
依据数值分析,我们可以发现存在递归情况

import matplotlib.pyplot as plt

"""
详细描述;
1)计算n阶差商 f[x0, x1, x2 ... xn]
2) xi 所有插值节点的横坐标集合                                                        o
3) fi 所有插值节点的纵坐标集合                                                      /   \
4) 返回xi的i阶差商(i为xi长度减1)                                                     o     o
5) a. 必须确保xi与fi长度相等                                                        / \   / \
    b. 由于用到了递归,所以留意不要爆栈了.                                           o   o o   o
    c. 递归减递归(每层递归包含两个递归函数), 每层递归次数呈二次幂增长,总次数是一个满二叉树的所有节点数量(所以极易栈溢出)                                                                                    
"""
def get_order_diff_quot(xi = [], fi = []):
    if len(xi) > 2 and len(fi) > 2:
        return (get_order_diff_quot(xi[:len(xi) - 1], fi[:len(fi) - 1]) - get_order_diff_quot(xi[1:len(xi)], fi[1:len(fi)])) / float(xi[0] - xi[-1])
    return (fi[0] - fi[1]) / float(xi[0] - xi[1])

"""
6) 获得Wi(x)函数;
 Wi的含义举例 W1 = (x - x0); W2 = (x - x0)(x - x1); W3 = (x - x0)(x - x1)(x - x2)
7) i  i阶(i次多项式)
8) xi  所有插值节点的横坐标集合
9) 返回Wi(x)函数
"""
def get_Wi(i = 0, xi = []):
    def Wi(x):
        result = 1.0
        for each in range(i):
            result *= (x - xi[each])
        return result
    return Wi




"""
 获得牛顿插值函数
"""
def get_Newton_inter(xi = [], fi = []):
    def Newton_inter(x):
        result = fi[0]
        for i in range(2, len(xi)):
            result += (get_order_diff_quot(xi[:i], fi[:i]) * get_Wi(i-1, xi)(x))
        return result
    return Newton_inter



"""
demo:
"""
if __name__ == '__main__':

    ''' 插值节点, 这里用二次函数生成插值节点,每两个节点x轴距离位10 '''
    sr_x = [i for i in range(-50, 51, 10)]
    sr_fx = [i**2 for i in sr_x]

    Nx = get_Newton_inter(sr_x, sr_fx)            # 获得插值函数

    tmp_x = [i for i in range(-50, 51)]          # 测试用例
    tmp_y = [Nx(i) for i in tmp_x]               # 根据插值函数获得测试用例的纵坐标

    ''' 画图 '''
    plt.figure("I love china")
    ax1 = plt.subplot(111)
    plt.sca(ax1)
    plt.plot(sr_x, sr_fx, linestyle = '', marker='o', color='b')
    plt.plot(tmp_x, tmp_y, linestyle = '--', color='r')
    plt.show()

执行结果;


image.png

此外,我们也可以对一维线性插值使用指定得库:numpy.interp

numpy.interp(x,xp,fp,left = None,right = None,period = None )

将一维分段线性插值返回给具有给定离散数据点(xp,fp)的函数,该函数在x处求值

参数说明:   
x : 类似数组
评估插值的x坐标

xp : 一维浮点数序列
如果未指定参数周期,则数据点的x坐标必须增加 . 否则,在用归一化周期边界之后对xp进行内部排序,xp = xp % period.

fp : 一维浮点数或复数序列
数据点的y坐标,与xp的长度相同。

left : 对应于fp的可选float或complex
x <xp [0]的返回值,默认值为fp [0]。

right : 对应于fp的可选float或complex
x> xp [-1]的返回值,默认值为fp [-1]。

period : 无或浮动,可选
X坐标的句点,此参数允许对x坐标进行适当的插值。 如果指定了period,则忽略参数left和right。


Returns:    
y : 浮点型或复数(对应于fp)或ndarray
内插值,形状与x相同。

Raises: 
ValueError
If xp and fp have different length If xp or fp are not 1-D sequences If period == 0

检查: 如果xp没有增加,则结果是无意义的。

案例二:

另一方面:线性插值是一种使用线性多项式进行曲线拟合的方法,可以在一组离散的已知数据点范围内构造新的数据点。

实际上,这可能意味着您可以推断已知位置点之间的新的估计位置点,以创建更高频率的数据或填写缺失值。

以最简单的形式,可视化以下图像:

image.png

在此,已知数据点在位置(1,1)和(3,3)处为红色。使用线性迭代,我们可以在它们之间添加一个点,该点可以显示为蓝色。

这是一个非常简单的问题,如果我们拥有更多已知的数据点,并且想要特定频率的插值点又该怎么办呢?

这可以使用numpy包中的两个函数在Python中非常简单地实现:

#Let's create ten x and y values that follow a sine curve

import numpy as np 
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 10)
 y = np.sin(x)
plt.plot(x, y, 'o') 
plt.show()

image

我们有十个已知点,但是假设我们要一个50个序列。

我们可以使用np.linspace做到这一点;序列的起点,序列的终点以及我们想要的数据点总数

起点和终点将与您的初始x值的起点和终点相同,因此在此我们指定0和2 * pi。我们还指定了对序列中50个数据点的请求

xvals = np.linspace(0,2 * np.pi,50)

现在,进行线性插值!使用np.interp,我们传递所需数据点的列表(我们在上面创建的50个),然后传递原始的x和y值

yinterp = np.interp(xvals,x,y)

现在,让我们绘制原始值,然后覆盖新的内插值!

plt.plot(x,y,'o')

plt.plot(xvals,yinterp,'-x')

plt.show()
image.png

案例三:

您还可以将此逻辑应用于时间序列中的x和y坐标。在这里,您将根据时间对x值进行插值,然后针对时间对y值进行插值。如果您想在时间序列中使用更频繁的数据点(例如,您想在视频帧上叠加一些数据),或者缺少数据点或时间戳不一致,这将特别有用。

让我们为一个场景创建一些数据,在该场景中,在60秒的比赛时间里,一辆赛车仅发出十个位置(x&y)输出(在整个60秒的时间内,时间也不一致):

import numpy as np

import matplotlib.pyplot as plt

timestamp = (0,5,10,15,30,35,40,50,55,60)

x_coords = (0,10,12,13,19,13,12,19,21,25)

y_coords = (0,5,10,7,2,8,15,19,14,15)

#Now, let's create the start time for the race, the end time, and the duration - we'll need these values for the linear interpolation

start_timestamp = min(timestamp)

end_timestamp = max(timestamp)

duration_seconds = (end_timestamp - start_timestamp)

#Apply the spacing, and the the interpolation independently for the x values and the y values

new_intervals = np.linspace(start_timestamp, end_timestamp, duration_seconds)

new_x_coords = np.interp(new_intervals, timestamp, x_coords)

new_y_coords = np.interp(new_intervals, timestamp, y_coords)

 

#Let's have a look at the interpolated positional values that we now have:

 

plt.plot(x_coords, y_coords, 'o')

plt.plot(new_x_coords, new_y_coords, '-x')

plt.show()
image.png

参考文献