scipy.interpolate: 插值和平滑处理

scipy有很多插值函数(方法),按维度可分为一维、二维和多维的插值方法,按方法包括拉格朗日和泰勒插值方法等,具体插值函数可参阅如下介绍:

https://docs.scipy.org/doc/scipy/reference/interpolate.html?highlight=scipy%20interpolate#module-scipy.interpolate

一维插值

这里简单介绍下一维插值方法interpolate.interp1d

import numpy as np
from scipy.interpolate import interp1d 
# 创建待插值的数据 
x = np.linspace(0, 10 * np.pi, 20) 
y = np.cos(x) 
# 分别用linear和quadratic插值 
fl = interp1d(x, y, kind='linear') 
fq = interp1d(x, y, kind='quadratic') 

xint = np.linspace(x.min(), x.max(), 1000) # 将x设置为1000个点
yintl = fl(xint) # 线性插值  
yintq = fq(xint) # 二次项插值

结果如图:

import matplotlib.pyplot as plt
fig,ax = plt.subplots(2,2,figsize=(10,8))
plt.subplot(221)
plt.plot(x,y,label='raw-data',marker='o')
plt.legend()

plt.subplot(223)
plt.scatter(xint,yintl,label='linear_interpl',marker='o')
plt.legend()
plt.subplot(224)
plt.scatter(xint,yintq,label='quadratic_interpl',marker='o')
plt.legend()

scipy.interpolate: 插值和平滑处理_第1张图片

平滑度

类似于曲线拟合,平滑度越高,滑动窗口取值越宽,曲线越平滑,具体参数可参考文档:

https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.UnivariateSpline.html#scipy.interpolate.UnivariateSpline

from scipy.interpolate import UnivariateSpline
x = np.linspace(-5,5,200)
y = np.exp(-x**2)+np.random.randn(200)/10

# 平滑曲线处理,平滑参数s=1
s = UnivariateSpline(x,y,s=1)
xs = np.linspace(-5,5,1000)
ys = s(xs)
plt.plot(x,y,'.-')
plt.plot(xs,ys,label='s=1')
plt.legend()
plt.show()


# 平滑曲线处理,平滑参数s=2
s = UnivariateSpline(x,y,s=2)
xs = np.linspace(-5,5,1000)
ys = s(xs)
plt.plot(x,y,'.-')
plt.plot(xs,ys,label='s=2')
plt.legend()
plt.show()

scipy.interpolate: 插值和平滑处理_第2张图片

scipy.interpolate: 插值和平滑处理_第3张图片

 

你可能感兴趣的:(数据分析,Python,插值,interpolate,scipy,平滑)