Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Manual least-squares (using optim) #2

Open
ashiklom opened this issue Apr 17, 2019 · 0 comments
Open

Manual least-squares (using optim) #2

ashiklom opened this issue Apr 17, 2019 · 0 comments

Comments

@ashiklom
Copy link
Collaborator

x <- c(60,100,330,15000) 
y <- c(0.429, 0.423, 0.4146, 0.127)
log_x <- log(x)
test_data <- data.frame(y, log_x)

head(test_data)
plot(y ~ log_x, data = test_data)

## ls_m <- nls(
##   y ~ r + (s-r)/ (1 + (alpha * log_x)^n) ^ (1 - 1/n) ,
##   nls.control(maxiter = 5000) ,
##   data = test_data,
##   start = list(r = 0.1, s = 0.5, n = 1.2, alpha = 0.015),
##   lower = list(r = 0, s = 0, n = 0, alpha = 0),
##   trace = TRUE,
##   algorithm = "port"
## )

f <- function(log_x, r, s, n, alpha) r + (s-r)/ (1 + (alpha * log_x)^n) ^ (1 - 1/n) 

likelihood <- function(params) {
  pred <- f(test_data$log_x, params[1], params[2], params[3], params[4])
  sum((pred - test_data$y) ^ 2)
}

opt <- optim(c(r = 0.1, s = 0.5, n = 1.2, alpha = 0.015),
             fn = likelihood,
             lower = c(r = 0, s = 0, n = 0, alpha = 0),
             method = "L-BFGS-B")

vals <- opt$par

plot(y ~ log_x, data = test_data)
lines(seq(3, 10, 0.1), f(seq(3, 10, 0.1), vals[1], vals[2], vals[3], vals[4]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant