Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using optim() or optimize() functions in R

Tags:

r

I have been trying to use optim() or optimize() function to minimize the sum of absolute forecast errors.

I have 2 vectors, each of length 28, 1 containing forecast data and the other containing the actual data for the last 28 days.

The fcst and act vectors are here :-

fcst <- c(3434.23, 3434.23, 3232.4, 1894.63, 1989.23, 3827.71, 3827.71, 3827.71, 3434.23, 1984.42, 1894.63, 1989.23, 3827.71, 3827.71, 3827.71, 3827.71, 3625.88, 2288.11, 1989.23, 3434.23, 3434.23, 3434.23, 3434.23, 3232.4, 2288.11, 2382.71, 3827.71, 3827.71)

act <- c(3194.62, 3109.93, 2991.44, 1741.49, 1935.07, 3100.84, 3169.39, 3170.24, 2613.81, 1947.35, 1820.63, 1765.62, 3397.48, 3501.14, 3444.14, 3589.24, 3263.55, 2153.49, 2159.85, 3237.94, 3345.7, 3246.66, 3195.58, 3001.53, 2073.76, 2419.29, 3530.62, 3455.71)

I have created an objective function like so :-

fn <- function(fcst, act, par) {
sum(abs(act - (fcst * par)))}

Using the optimize() function like so :-

xmin1 <- optimize(fn, c(0.5, 1.5), fcst = fcst, act = act)

I get the correct value for 'par' - no problems.

> xmin1
$minimum
[1] 0.92235

$objective
[1] 3630.399

However, when I use the optim() function like so :-

xmin <- optim(par = c(0.1, 1.9), fn, fcst = fcst, act = act)

I get 2 values for par like this :-

> xmin
$par
[1] 0.9223822 0.9191707

$value
[1] 3623.823

$counts
function gradient 
      95       NA 

$convergence
[1] 0

$message
NULL

The question is why do I get 2 values for the single parameter 'par' using optim() function. Shouldn't I be getting only one (1) value as I do for the optimize() function?

Also, in either case, I get marginally different values for the parameter values depending upon the initial values of the parameter - should this be dependent upon the initial values when this objective function is essentially unimodal?

Best regards

Deepak Agarwal

like image 342
Deepak Agarwal Avatar asked Feb 21 '18 00:02

Deepak Agarwal


1 Answers

The problem is that you are initializing the par object with 2 parameters and the default optimizer in optim so it thinks, for some strange reason, that it has to solve for 2 parameters (this has happen to me but i don't know why) just use 1 value en the par entry in the function and you will get the result you want.

xmin <- optim(par = 0.1, fn, fcst = fcst, act = act)
like image 169
Alejandro Andrade Avatar answered Nov 10 '22 18:11

Alejandro Andrade