Python least squares leastsq function for normal solution and x-axis vertical problem

Source: Internet
Author: User

lines perpendicular to the x-axis cannot be calculated when y=kx+b is used. Therefore, the normal ysin (theta) +xcos (theta) = dist is used. It seems that the use of a bit complicated, direct use of ax+by=1 do not know can calculate, not tested.

  
 
  1. # 修改自 http://www.cnblogs.com/NanShan2016/p/5493429.html
  2. ### 最小二乘法 python leastsq###
  3. import numpy as np
  4. import math
  5. from scipy.optimize import leastsq
  6. ###采样点(Xi,Yi)###
  7. Xi=np.array([-1,-1])
  8. Yi=np.array([0,10])
  9. # p是个数组,表示所有参数!!!
  10. ### 定义误差函数,拟合y=kx+b,p[0]表示k,p[1]表示b
  11. ### 法线式 y*sin(theta)+x*cos(theta) = dist
  12. def error ( p x y
  13. return y*math.sin(p[0])+x*math.cos(p[0])-p[1] #x、y都是列表,故返回值也是个列表
  14. ###主函数从此开始###
  15. # 可能是使用梯度下降法而非矩阵运算,因此需要给定初始参数p0
  16. p0=[0,1]
  17. Para=leastsq(error,p0,args=(Xi,Yi)) #把error函数中除了p以外的参数打包到args中
  18. theta = Para[0][0]
  19. dist = Para[0][1]
  20. print("theta=",theta,‘\n‘,"dist=",dist)
  21. ###绘图,看拟合效果###
  22. import matplotlib.pyplot as plt
  23. plt.axis([-10,10,-10,10])
  24. plt.scatter(Xi,Yi,color="red",label="Sample Point",linewidth=3) #画样本点
  25. if theta != 0:
  26. x=np.linspace(-10,10,10)
  27. y=dist/math.sin(theta)-x/math.tan(theta)
  28. else:
  29. x = dist
  30. y = np.linspace(-10,10,10)
  31. plt.plot(x,y,color="orange",label="Fitting Line",linewidth=2) #画拟合直线
  32. plt.legend()
  33. plt.show()


From Wiznote

Python least squares leastsq function for normal solution and x-axis vertical problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.