python实现三维拟合的方法
程序员文章站
2022-07-06 11:56:39
如下所示:
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits...
如下所示:
from matplotlib import pyplot as plt import numpy as np from mpl_toolkits.mplot3d import axes3d fig = plt.figure() ax = axes3d(fig) #列出实验数据 point=[[2,3,48],[4,5,50],[5,7,51],[8,9,55],[9,12,56]] plt.xlabel("x1") plt.ylabel("x2") #表示矩阵中的值 isum = 0.0 x1sum = 0.0 x2sum = 0.0 x1_2sum = 0.0 x1x2sum = 0.0 x2_2sum = 0.0 ysum = 0.0 x1ysum = 0.0 x2ysum = 0.0 #在图中显示各点的位置 for i in range(0,len(point)): x1i=point[i][0] x2i=point[i][1] yi=point[i][2] ax.scatter(x1i, x2i, yi, color="red") show_point = "["+ str(x1i) +","+ str(x2i)+","+str(yi) + "]" ax.text(x1i,x2i,yi,show_point) isum = isum+1 x1sum = x1sum+x1i x2sum = x2sum+x2i x1_2sum = x1_2sum+x1i**2 x1x2sum = x1x2sum+x1i*x2i x2_2sum = x2_2sum+x2i**2 ysum = ysum+yi x1ysum = x1ysum+x1i*yi x2ysum = x2ysum+x2i*yi # 进行矩阵运算 # _mat1 设为 mat1 的逆矩阵 m1=[[isum,x1sum,x2sum],[x1sum,x1_2sum,x1x2sum],[x2sum,x1x2sum,x2_2sum]] mat1 = np.matrix(m1) m2=[[ysum],[x1ysum],[x2ysum]] mat2 = np.matrix(m2) _mat1 =mat1.geti() mat3 = _mat1*mat2 # 用list来提取矩阵数据 m3=mat3.tolist() a0 = m3[0][0] a1 = m3[1][0] a2 = m3[2][0] # 绘制回归线 x1 = np.linspace(0,9) x2 = np.linspace(0,12) y = a0+a1*x1+a2*x2 ax.plot(x1,x2,y) show_line = "y="+str(a0)+"+"+str(a1)+"x1"+"+"+str(a2)+"x2" plt.title(show_line) plt.show()
以上这篇python实现三维拟合的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。