[Mathematical Model] Python fitting of one-variable/quadratic equations (linear regression)

        A variety of libraries can be used in Python to fit equations, the most commonly used of which are NumPy and SciPy. NumPy is a library for processing arrays and matrices, while SciPy provides a large number of scientific computing functions, including fitting algorithms.

1 Fitting of a linear equation of one variable

        It should be noted that our equation here needs to be defined by ourselves, and then we can use curve_fit to find the parameters (coefficients) and covariance matrix in the equation.

def linear_equation_with_one_unknown():
    # 需要自己定义方程
    mpl.rcParams['font.sans-serif'] = ['SimHei']  # 显示中文
    plt.rcParams['axes.unicode_minus'] = False  # 解决负数坐标显示问题
    x = np.array([1, 2, 3, 4, 5])
    y = np.array([4, 6, 7, 9, 13])

    def func(x1, a, b):  # 定义拟合方程
        return a*x1 + b

    p_opt, p_cov = curve_fit(func, x, y)  # p0 = 1是因为只有a一参数
    print("方程参数最佳值为:", p_opt.astype(np.int64))  # 参数最佳值,np.round(popt, 4)
    print("拟合方程协方差矩阵:\n", p_cov)  # 协方差矩阵,popt[0],popt[1],popt[2]分别代表参数a b c
    y_predict = func(x, p_opt[0], p_opt[1])
    plt.scatter(x, y, marker='x', lw=1, label='原始数据')
    plt.plot(x, y_predict, c='r', label='拟合曲线')
    plt.legend()  # 显示label
    plt.show()

2 Fitting of quadratic equation of one variable

        The code here is no different from the above. It just needs to change the defined function into a function of a quadratic equation. If it is other functions, such as exponential function and logarithmic function, you can modify it here.

def Uni_quadratic_equation():
    # 需要自己定义方程
    mpl.rcParams['font.sans-serif'] = ['SimHei']  # 显示中文
    plt.rcParams['axes.unicode_minus'] = False  # 解决负数坐标显示问题
    # x = np.a range(0, 20)
    # y = 2 * x ** 2 + np.random.randint(0, 100, 20)
    x = np.array([1, 2, 3, 4, 5])
    y = np.array([1, 4, 9, 16, 25])

    def func(x1, a, b, c):  # 定义拟合方程
        return a*x1**2 + b*x1 + c
    p_opt, p_cov = curve_fit(func, x, y)  # p0 = 1是因为只有a一参数
    print("方程参数最佳值为:", p_opt.astype(np.int64))  # 参数最佳值,np.round(popt, 4)
    print("拟合方程协方差矩阵:\n", p_cov)  # 协方差矩阵,popt[0],popt[1],popt[2]分别代表参数a b c
    y_predict = func(x, p_opt[0], p_opt[1], p_opt[2])
    plt.scatter(x, y, marker='x', lw=1, label='原始数据')
    plt.plot(x, y_predict, c='r', label='拟合曲线')
    plt.legend()  # 显示label
    plt.show()

3 Summary

        Today I only share the fitting of linear and quadratic equations of one variable. There is no difference in the code. It is just a matter of changing the initially defined equation. Theoretically, this code can be used directly as long as x and y are single. If there are multiple independent variables (multivariate), you cannot use this code directly. At present, I have not studied the problem of multiple regression. I will write it down and share it with you later.

Guess you like

Origin blog.csdn.net/m0_56729804/article/details/135197514