【问题标题】:How to fit non-linear data's in python如何在python中拟合非线性数据
【发布时间】:2015-11-03 18:16:10
【问题描述】:

如何使用以下 3 种方法在 Python 中使用 scipy.optimize import curve_fit 拟合非线性数据:

  1. 高斯。
  2. 洛伦兹拟合。
  3. 朗缪尔适合。

我只能从我的数据文件中进行链接和绘图。

from matplotlib import pyplot as plt
from matplotlib import style
import numpy as np
import pylab
from scipy.optimize import curve_fit
style.use('ggplot')
data = np.genfromtxt('D:\csvtrail3.csv', delimiter=',', skiprows=1)
x=data[:,0]
y=data[:,1]
data.fit_lorentzians()
plt.plot(x, y)
plt.title('Epic chart')
plt.ylabel('Y Axis')
plt.xlabel('X Axis')
plt.show()

请建议我如何归档此数据的行。我不想要直装。我想要平滑的拟合。

【问题讨论】:

    标签: python matplotlib scipy curve-fitting


    【解决方案1】:

    一般来说,scipy.optimize.curve_fit 在我们知道最适合我们的数据集的方程后就会起作用。由于您想要拟合遵循高斯、洛伦兹等分布的数据集,您可以通过提供它们的特定方程来实现。

    只是一个小例子:

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.optimize import curve_fit
    import numpy as np
    
    xdata = np.array([-2,-1.64,-1.33,-0.7,0,0.45,1.2,1.64,2.32,2.9])
    ydata = np.array([0.69,0.70,0.69,1.0,1.9,2.4,1.9,0.9,-0.7,-1.4])
    
    def func(x, p1,p2):
      return p1*np.cos(p2*x) + p2*np.sin(p1*x)
    
    # Here you give the initial parameters for p0 which Python then iterates over
    # to find the best fit
    popt, pcov = curve_fit(func,xdata,ydata,p0=(1.0,0.3))
    
    print(popt) # This contains your two best fit parameters
    
    # Performing sum of squares
    p1 = popt[0]
    p2 = popt[1]
    residuals = ydata - func(xdata,p1,p2)
    fres = sum(residuals**2)
    
    print(fres)
    
    xaxis = np.linspace(-2,3,100) # we can plot with xdata, but fit will not look good 
    curve_y = func(xaxis,p1,p2)
    plt.plot(xdata,ydata,'*')
    plt.plot(xaxis,curve_y,'-')
    plt.show()
    

    以上是针对我的具体情况,我只使用了适合我的数据集的Harmonic addition formula。通过在func 定义中提供高斯方程或任何其他方程,您可以相应地进行更改。

    您的参数会相应变化。如果它是高斯分布,您将拥有sigma(标准差)和mean 作为未知参数。

    【讨论】:

      猜你喜欢
      • 2021-02-25
      • 2017-09-01
      • 1970-01-01
      • 2019-03-15
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      相关资源
      最近更新 更多