python实现三维拟合的方法

yipeiwu_com5年前Python基础

如下所示:

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实现三维拟合的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python将字符串转换成数组的方法

python将字符串转换成数组的方法。分享给大家供大家参考。具体实现方法如下: #----------------------------------------- # N...

python多任务之协程的使用详解

1|0使用yield完成多任务 import time def test1(): while True: print("--1--") time.sleep(0.5)...

对python周期性定时器的示例详解

一、用thread实现定时器 py_timer.py文件 #!/usr/bin/python #coding:utf-8 import threading import os im...

打开电脑上的QQ的python代码

复制代码 代码如下:# _*_ coding:utf-8 _*_# name start_qq.pyimport osos.startfile("C:\Program Files\Ten...

Python检测QQ在线状态的方法

本文实例讲述了Python检测QQ在线状态的方法。分享给大家供大家参考。具体实现方法如下: import time,datetime import urllib2 def ch...