This is just a description of how the least squares method is used to solve the linear regression problem of a function in the R language.
The code is as follows: (data above a blog) (not very simple????)
> x<-c (6.19,2.51,7.29,7.01,5.7,2.66,3.98,2.5,9.1,4.2) > Y<-c ( 5.25,2.83,6.41,6.71,5.1,4.23,5.05,1.98,10.5,6.3) > Lsfit (x, y)
The results are as follows:
$coefficientsIntercept X 0.8310557 0.9004584
Description: Intercept: Intercept
x: Coefficient of variable X
That is, for the one-dimensional function intercept equation: y=0.9x+0.83
Results of the previous blog's Calculations (python):
Output: k= 0.900458420439 b= 0.831055638877 cost:1 The fitting line is: y=0.9x+0.83
If you do not pursue the beauty of the drawing, it is possible to simply draw a scatter chart directly with R (it is also possible to adjust the point of view by setting parameters).
> Plot (x, y) # # #x, y is the data that has been assigned above
Results
650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/1119747/201703/ 1119747-20170308104218938-2119793121.png "style=" border:0px; "/>
We then adjust the target function and the sample data:
Objective function: Y=ax2+bx+c
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" border:0px; "/>
> x<-c (1,2,3,4,5,6) > Y<-c (9,18,31,48,69,94) > Lsfit (x, y) $coefficientsIntercept X-14.66667 17.00000
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" border:0px; "/>
It can be seen from the results that the solution is still a function of the Y=kx+b form.
Instead, adjust the code in Python (see the following connection for the full code):
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" border:0px; "/>
def func (p,x): a,b,c=p return a*x*x+b*x+cp0=[10,10,10] #读取结果a, B,c=para[0]print ("a=", A, "b=", B, "c=", c) print ("Cost:" + STR (para[1])) print ("Fit Line for Solution:") Print ("y=" +str (Round (a,2)) + "x*x+" +str (Round (b,2)) + "x+" +str (c))
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" border:0px; "/>
A= 2.0 b= 3.0 c= 4.0cost:2 the fitted line for the solution is: y=2.0x*x+3.0x+4.0
The comparison shows that the LEASTSQ function in Python scipy library is still relatively high in generality.
How to use least squares in R language