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()
类似于曲线拟合,平滑度越高,滑动窗口取值越宽,曲线越平滑,具体参数可参考文档:
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()