0
votes

I want to optimize a custom function in R with several parameters. I am fairly sure the custom function correctly gives the sum of squares error, but when I try to optimize the parameters "k" and "lambda" there is no success. In the end, I would like the optim function to test many different "lambda" and "k" values and ultimately give me the combination that reduces the sum of squares error. Any advice will be greatly appreciated. I am new at optimizations so any pointers will be welcome.

# Actual data
x = seq(0,3.277,0.005)[1:500]
actual.ani = rnorm(1:500)

# Exponential function - returns sum of squares error
exp.f <- function(lambda, k) { 
  pred.ani = (k + exp((-lambda*x) + log10(100-k)))
  sse.tot = sum((actual.ani-pred.ani)^2)
  return(sse.tot)
}

# Run optimization
params = c(lambda=1, k=1)
optim(par=params, exp.f)

Error in fn(par, ...) : argument "k" is missing, with no default

Thanks!

1
Do you think the answer given below is not helpful?Suren
@Suren, your answer was very helpful. ThanksConnor Murray

1 Answers

1
votes

If you define your function as below (where the argument is a vector), optim provide a solution.

exp.f <- function(y) { 
  lambda <- y[1]
    k <- y[2]

  pred.ani = (k + exp((-lambda*x) + log10(100-k)))
  sse.tot = sum((actual.ani-pred.ani)^2)
  return(sse.tot)
}
optim(par=params, exp.f)
$par
[1] 564.75987560  -0.02335728
$value
[1] 499.9616
$counts
function gradient
     117       NA
$convergence
[1] 0
$message
NULL