Pass tuple as input argument for scipy.optimize.curve_fit

后端 未结 4 1717
刺人心
刺人心 2021-02-14 20:21

I have the following code:

import numpy as np
from scipy.optimize import curve_fit


def func(x, p): return p[0] + p[1] + x


popt, pcov = curve_fit(func, np.ara         


        
4条回答
  •  梦谈多话
    2021-02-14 20:52

    scipy.optimize.curve_fit

    scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, **kw)

    Use non-linear least squares to fit a function, f, to data.
    
    Assumes ydata = f(xdata, *params) + eps
    

    Explaining the idea

    The function to be fitted should take only scalars (not: *p0). Remember that the result of the fit depends on the initialization parameters.

    Working example

    import numpy as np
    from scipy.optimize import curve_fit
    import matplotlib.pyplot as plt
    
    def func(x, a0, a1):
        return a0 + a1 * x
    
    x, y = np.arange(10), np.arange(10) + np.random.randn(10)/10
    popt, pcov = curve_fit(func, x, y, p0=(1, 1))
    
    # Plot the results
    plt.title('Fit parameters:\n a0=%.2e a1=%.2e' % (popt[0], popt[1]))
    # Data
    plt.plot(x, y, 'rx')
    # Fitted function
    x_fine = np.linspace(x[0], x[-1], 100)
    plt.plot(x_fine, func(x_fine, popt[0], popt[1]), 'b-')
    plt.savefig('Linear_fit.png')
    plt.show()
    

提交回复
热议问题