Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing multivariate function in R

Tags:

optimization

r

I have a multivariate function that I want to optimize over one parameter:

cost <- function(theta, X, y) {
  m <- nrow(X)
  X <- as.matrix(X)
  J <- sum(-y * log(sigmoid(X %*% theta)) - (1-y) * log(1 - sigmoid(X %*% theta)))/m;
  return(J)
}

To optimize it, i use optim function. First, I create a wrapper, then use optim function to optimize wrapper function:

# X and y initialized before
initial_theta <- rep(0,ncol(X))
wrapper <- function(theta) cost(theta, X=X, y=y)
o <- optim(initial_theta, wrapper) 

How to optimize a multivariate function with optim without creating additional functions?

like image 356
Nikita Barsukov Avatar asked Oct 16 '25 10:10

Nikita Barsukov


1 Answers

optim takes a ... parameter which passes any addition input to the function of interest. So you don't need to create a new function as long as the parameter you want to optimize over is the first parameter of the function of interest.

optim(initial_theta, cost, X = X, y = y)

should provide the same functionality as creating the extra function.

like image 181
Dason Avatar answered Oct 19 '25 00:10

Dason