欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python实现二维曲线拟合的方法

程序员文章站 2022-07-06 11:55:33
如下所示: from numpy import * import numpy as np import matplotlib.pyplot as plt...

如下所示:

from numpy import *
import numpy as np
import matplotlib.pyplot as plt

plt.close()
fig=plt.figure()
plt.grid(true)
plt.axis([0,10,0,8])

#列出数据
point=[[1,2],[2,3],[3,6],[4,7],[6,5],[7,3],[8,2]]
plt.xlabel("x")
plt.ylabel("y")

#用于求出矩阵中各点的值
xsum = 0.0
x2sum = 0.0
x3sum = 0.0
x4sum = 0.0
isum = 0.0
ysum = 0.0
xysum = 0.0
x2ysum = 0.0


#列出各点的位置
for i in range(0,len(point)):

 xi=point[i][0]
 yi=point[i][1]
 plt.scatter(xi,yi,color="red")
 show_point = "("+ str(xi) +","+ str(yi) + ")"
 plt.text(xi,yi,show_point)

 xsum = xsum+xi
 x2sum = x2sum+xi**2
 x3sum = x3sum + xi**3
 x4sum = x4sum + xi**4
 isum = isum+1
 ysum = ysum+yi
 xysum = xysum+xi*yi
 x2ysum = x2ysum + xi**2*yi

# 进行矩阵运算
# _mat1 设为 mat1 的逆矩阵
m1=[[isum,xsum, x2sum],[xsum, x2sum, x3sum],[x2sum, x3sum, x4sum]]
mat1 = np.matrix(m1)
m2=[[ysum], [xysum], [x2ysum]]
mat2 = np.matrix(m2)
_mat1 =mat1.geti()
mat3 = _mat1*mat2

# 用list来提取矩阵数据
m3=mat3.tolist()
a = m3[0][0]
b = m3[1][0]
c = m3[2][0]
# 绘制回归线
x = np.linspace(0,10)
y = a + b*x + c*x**2
plt.plot(x,y)
show_line = "y="+str(a)+"+("+str(b)+"x)"+"+("+str(c)+"x2)";
plt.title(show_line)
plt.show()

以上这篇python实现二维曲线拟合的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。