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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With