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.
The fitting of linear/quadratic equations of one variable has been shared before. If you are interested, you can check out: Fitting of Univariate Equations in Python . Today I will share with you how to use Python to fit multivariate equations.
1 Python code
The same functions used here are curve_fit, so I won’t introduce them in detail. The binary implementation is implemented using a two-dimensional array. See the code for details. In addition, code for three-dimensional visualization has been added.
# -*- coding: utf-8 -*-
"""
@Time : 2023/12/25 9:21
@Auth : RS迷途小书童
@File :Regressive Analysis.py
@IDE :PyCharm
@Purpose:线性回归
@Web:博客地址:https://blog.csdn.net/m0_56729804
"""
import numpy as np
import pylab as mpl
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def binary_linear_equation():
# 需要自己定义方程
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文
plt.rcParams['axes.unicode_minus'] = False # 解决负数坐标显示问题
x = np.array([[1, 4], [2, 1], [3, 1], [4, 2], [5, 1], [9, 3]])
y = np.array([33, 4, 5, 12, 7, 27])
def func(x1, a, b, c):
return a * b * x1.T[0] + c * x1.T[1] ** 2
p_opt, p_cov = curve_fit(func, x, y)
print("方程参数最佳值为:", p_opt.astype(np.int64)) # 参数最佳值,np.round(p_opt, 4)
print("拟合方程协方差矩阵:\n", p_cov)
y_fit = func(x, *p_opt) # 使用拟合参数计算对应的y值
# ------------------可视化------------------
mpl.rcParams['legend.fontsize'] = 12 # 将图例的字体大小设置为12
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x.T[0], x.T[1], y, marker='x', lw=2, label='原始数据')
ax.plot(x.T[0], x.T[1], y_fit, c='r', label='拟合曲线')
plt.legend() # 显示label
plt.tight_layout() # 自动调整子图参数,使其内部组件(例如轴、标题、标签等)之间以及与子图边缘之间没有重叠。
plt.show()
if __name__ == "__main__":
# linear_equation_with_one_unknown()
# Uni_quadratic_equation()
binary_linear_equation()
2 Summary
The blog post on fitting equations will not be updated from now on, because I have no need for this yet. Logarithmic, exponential, idempotent equations can also be implemented with the above code, so I won’t be verbose anymore. Other aspects of code and theory will be updated later. If you are interested, you can follow me!