且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python中的二阶导数-scipy/numpy/pandas

更新时间:2022-03-09 16:24:05

您可以使用scipy的一维

You can interpolate your data using scipy's 1-D Splines functions. The computed spline has a convenient derivative method for computing derivatives.

对于您的示例数据,使用UnivariateSpline可以得到以下拟合结果

For the data of your example, using UnivariateSpline gives the following fit

import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline

y_spl = UnivariateSpline(x,y,s=0,k=4)

plt.semilogy(x,y,'ro',label = 'data')
x_range = np.linspace(x[0],x[-1],1000)
plt.semilogy(x_range,y_spl(x_range))

看起来合适,至少在视觉上是合适的.您可能要尝试使用UnivariateSpline使用的参数.

The fit seems reasonably good, at least visually. You might want to experiment with the parameters used by UnivariateSpline.

样条拟合的二阶导数可以简单地获得为

The second derivate of the spline fit can be simply obtained as

y_spl_2d = y_spl.derivative(n=2)

plt.plot(x_range,y_spl_2d(x_range))

结果看起来有些不自然(以防您的数据与某个物理过程相对应).您可能想要更改样条曲线拟合参数,改善数据(例如,提供更多样本,执行较少的噪声测量),或者决定使用分析函数对数据建模并进行曲线拟合(例如,使用sicpy的 curve_fit )

The outcome appears somewhat unnatural (in case your data corresponds to some physical process). You may either want to change the spline fit parameters, improve your data (e.g., provide more samples, perform less noisy measurements), or decide on an analytic function to model your data and perform a curve fit (e.g., using sicpy's curve_fit)