python 最小二乘 leastsq 函数实现 法线式 解决与x轴垂直问题
生活随笔
收集整理的這篇文章主要介紹了
python 最小二乘 leastsq 函数实现 法线式 解决与x轴垂直问题
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
當(dāng)使用y=kx+b時,與x軸垂直的直線無法計算。因此使用法線式y(tǒng)sin(theta)+xcos(theta) = dist。貌似這么用有點復(fù)雜了,直接使用ax+by=1不知道能不能計算,未測試。
# 修改自 http://www.cnblogs.com/NanShan2016/p/5493429.html### 最小二乘法 python leastsq###import numpy as npimport mathfrom scipy.optimize import leastsq###采樣點(Xi,Yi)###Xi=np.array([-1,-1])Yi=np.array([0,10])# p是個數(shù)組,表示所有參數(shù)!!!### 定義誤差函數(shù),擬合y=kx+b,p[0]表示k,p[1]表示b### 法線式 y*sin(theta)+x*cos(theta) = distdef error(p,x,y):return y*math.sin(p[0])+x*math.cos(p[0])-p[1] #x、y都是列表,故返回值也是個列表###主函數(shù)從此開始#### 可能是使用梯度下降法而非矩陣運算,因此需要給定初始參數(shù)p0p0=[0,1]Para=leastsq(error,p0,args=(Xi,Yi)) #把error函數(shù)中除了p以外的參數(shù)打包到args中theta = Para[0][0]dist = Para[0][1]print("theta=",theta,'\n',"dist=",dist)###繪圖,看擬合效果###import matplotlib.pyplot as pltplt.axis([-10,10,-10,10])plt.scatter(Xi,Yi,color="red",label="Sample Point",linewidth=3) #畫樣本點if theta != 0:x=np.linspace(-10,10,10)y=dist/math.sin(theta)-x/math.tan(theta)else:x = disty = np.linspace(-10,10,10)plt.plot(x,y,color="orange",label="Fitting Line",linewidth=2) #畫擬合直線plt.legend()plt.show()
總結(jié)
以上是生活随笔為你收集整理的python 最小二乘 leastsq 函数实现 法线式 解决与x轴垂直问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring boot技术干货
- 下一篇: MyBatis和Hibernate相比较