R – NonLinear Least Square
Non-Linear Least Square
Mathematical Formula:
where,
r is residual or error value between 2 points.
resid()
Syntax:
nls(formula, start)
where,
formula indicates the model formula i.e., non-linear function start is a list of starting estimates
Note: To know about more optional parameters of nls(), use below command in R console –help("nls")
Example 1 :
# defining x and y coordinates x < - seq( 0 , 10 , 0.1 ) y < - rnorm( 101 , 5 , 1 ) # output to be present as PNG file png( file = "nls.png" ) # Taking the model to get fitted m < - nls(y~a * x ^ 3 + b * x + c, start = list (a = 1 , b = 2 , c = 1 )) # plot the graph plot(x, y, col.lab = "darkgreen" , col.axis = "darkgreen" ) # plot the graph with new fitting line # or regression line lines(x, predict(m)) # saving the file dev.off() # print minimum residual or error value print ( sum (resid(m)^ 2 )) |
Output :
[1] 106.4507
Example 2 :
cor()
# creating sequence of 101 values from 0 to 100 x < - seq( 0 , 100 , 1 ) y< - ((runif( 1 , 10 , 20 ) * x) / (runif( 1 , 0 , 10 ) + x)) + rnorm( 101 , 0 , 1 ) # output to be present as PNG file png( file = "nls2.png" ) # using starting values in nls() function # to not get a warning m< - nls(y~a * x / (b + x), start = list (a = 1 , b = 2 )) # goodness of fit cor(y, predict(m)) # minimized residual value sum (resid(m)^ 2 ) # plotting points on graph plot(x, y) # finding regression line lines(x, predict(m)) # saving the file dev.off() |
Output :
[1] 0.9622681 [1] 108.1481