Python Least squares leastsq function implementation

Source: Internet
Author: User

Code modified from http://www.cnblogs.com/NanShan2016/p/5493429.html

Baidu on the Internet a bit, mainly two examples, a use of polynomial functions, one is this. Some of the details are not understood, mainly to ignore the P is an array of parameters instead of a number (python basic problem), tangled up with notes to make a note

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


From Wiznote

Python Least squares leastsq function implementation

Related Article

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.