Python实现⼆维曲线拟合的⽅法
如下所⽰:
from numpy import *
import numpy as np
import matplotlib.pyplot as plt
plt.close()
正则化的最小二乘法曲线拟合pythonfig=plt.figure()
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) + ")"
<(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 =I()
mat3 = _mat1*mat2
# ⽤list来提取矩阵数据
list()
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实现⼆维曲线拟合的⽅法就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论