Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question on nloptr package in for optimisation

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.

like image 766
Brian Smith Avatar asked May 30 '26 05:05

Brian Smith


1 Answers

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.

Construct a Closure to Ensure Once Only Evaluation

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.

like image 67
Gwang-Jin Kim Avatar answered Jun 01 '26 21:06

Gwang-Jin Kim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!