Optimization with Constraints

后端 未结 2 1512
南旧
南旧 2020-12-16 16:53

I am working with the output from a model in which there are parameter estimates that may not follow a-priori expectations. I would like to write a function that forces thes

2条回答
  •  执笔经年
    2020-12-16 17:36

    Alright, this is starting to take form, but still has some bugs. Based on the conversation in chat with @Joran, it seems I can include a conditional that will set the loss function to an arbitrarily large value if the values are not in order. This seems to work IF the discrepancy occurs between the first two coefficients, but not thereafter. I'm having a hard time parsing out why that would be the case.

    Function to minimize:

    f <- function(x, x0) {
      x1 <- x[1]
      x2 <- x[2]
      x3 <- x[3]
      x4 <- x[4]
      x5 <- x[5]
    
     loss <- (x1 - x0[1]) ^ 2 + 
             (x2 - x0[2]) ^ 2 + 
             (x3 - x0[3]) ^ 2 + 
             (x4 - x0[4]) ^ 2 +
             (x5 - x0[5]) ^ 2    
    
      #Make sure the coefficients are in order
      if any(diff(c(x1,x2,x3,x4,x5)) > 0) loss = 10000000
    
      return(loss)
    }
    

    Working example (sort of, it seems the loss would be minimized if b0 = 1.24?):

    > betas <- c(1.22, 1.24, 1.18, 1.12, 1.10)
    > optim(betas, f, x0 = betas)$par
    [1] 1.282 1.240 1.180 1.120 1.100
    

    Non-working example (note that the third element is still larger than the second:

    > betas <- c(1.20, 1.15, 1.18, 1.12, 1.10)
    > optim(betas, f, x0 = betas)$par
    [1] 1.20 1.15 1.18 1.12 1.10
    

提交回复
热议问题