I am trying to optimize an function using nloptr package in R like below
Some_Dataframe_Fixed = data.frame(x = 1:2, y = 4:5)
eval_f <- function(x) {
Some_Arg_Fixed_Mat = as.matrix(Some_Dataframe_Fixed)
100 * (x[2] - x[1] * x[1]) ^ 2 + (1 - x[1]) ^ 2
}
In above function, I am converting an external data frame Some_Dataframe_Fixed to matrix inside the function.
I would like to know from expert here, if such implementation is efficient? Will that dataframe Some_Dataframe_Fixed be converted fresh every time nloptr call that function during optimization? Or should I always convert that data frame outside of the function since that conversion does not depend on x?
Thanks for your pointer.
Such an implementation is NOT efficient, since as.matrix(Some_Dataframe_Fixed) would evaluate Some_Dataframe_Fixed everytime the function eval_f is called.
How to make it more efficient?
Evaluate only once while function is defined:
Some_Dataframe_Fixed = data.frame(x = 1:2, y = 4:5)
eval_f <- function(x, some_arg_fixed_mat=as.matrix(Some_Datframe_Fixed)) {
100 * (x[2] - x[1] * x[1]) ^ 2 + (1 - x[1]) ^ 2
}
This lets the evaluation happen only once at function definition time.
Another, more general way is to use a closure - and define a function
which can create for every specific Some_Dataframe_Fixed a new updated eval_f function:
# `Some_Dataframe_Fixed` here as `df`
make_eval_f <- function(df) {
mat <- as.matrix(df) # the as.matrix(df) call as a closure
function(x) {
# Use `mat` inside the function
100 * (x[2] - x[1]^2)^2 + (1 - x[1])^2
} # this eval_f function gets returned
}
eval_f <- make_eval_f(Some_Dataframe_Fixed)
And then you can use the eval_f function like above.
When Some_Dataframe_Fixed changes, you can redefine eval_f by calling make_eval_f() with the updated dataframe.
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