Python data processing 1: using curve_fit to achieve curve fitting

In the following example, we used a variety of curves to simply fit the given data. We mainly learn how to use curve_fit to achieve curve fitting. As for the specific function to fit, we should choose according to the actual data given. ! ! !

The functions that can be fitted are more than the following. It can be seen that as long as you write the expression of the function you want to use, you can get the parameters of the function! ! !

from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import numpy as np

#线性
def func_linear(x, a, b):
    return a * x+ b
#二次
def func_poly_2(x, a, b, c):
    return a*x*x + b*x + c
#三次
def func_poly_3(x, a, b, c , d):
    return a*x*x*x + b*x*x + c*x + d
#幂函数
def func_power(x, a, b):
    return x**a + b
#指数函数
def func_exp(x, a, b):
    return a**x + b

# 待拟合点
xdata = [1, 2, 3, 4, 5]
ydata = [1, 3, 8, 18, 36]

x = list(np.arange(0, 6, 0.01))

# 绘制散点
plt.scatter(xdata[:], ydata[:], 25, "red")

# popt数组中,存放的就是待求的参数a,b,c,......
popt, pcov = curve_fit(func_linear, xdata, ydata)
y1 = [func_linear(i, popt[0], popt[1]) for i in x]
plt.plot(x, y1, 'r')


popt, pcov = curve_fit(func_poly_2, xdata, ydata)
y2 = [func_poly_2(i, popt[0], popt[1], popt[2] ) for i in x]
plt.plot(x, y2, 'g')

popt, pcov = curve_fit(func_poly_3, xdata, ydata)
y3 = [func_poly_3(i, popt[0], popt[1], popt[2] ,popt[3]) for i in x]
plt.plot(x, y3, 'b')

popt, pcov = curve_fit(func_power, xdata, ydata)
y4 = [func_power(i, popt[0], popt[1]) for i in x]
plt.plot(x, y4, 'y')

popt, pcov = curve_fit(func_exp, xdata, ydata)
y5 = [func_exp(i, popt[0], popt[1]) for i in x]
plt.plot(x, y5, 'c')

plt.show()

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_39507748/article/details/110679328