二次编程设置约束

问题描述 投票:0回答:1

我正在尝试建立一个简单的OLS模型,对R中的系数进行约束。下面的代码正在工作。但是,这表明

y = c + a1x1 + a2x2 + a3x3,约束为a1 + a2 = 1

我想将此约束修改为:a1 * a2-a3 = 0

感谢您的帮助!

工作代码:

'''

    set.seed(1000) 
    n <- 20
    x1 <- seq(100,length.out=n)+rnorm(n,0,2)
    x2 <- seq(50,length.out=n)+rnorm(n,0,2)
    x3 <- seq(10,length.out=n)+rnorm(n,0,2)
    constant <- 100
    ymat <- constant + .5*x1 + .5*x2 + .75*x3 + rnorm(n,0,4)
    xmat <- cbind(x1,x2,x3)

    X <- cbind(rep(1,n),xmat) # explicitly include vector for constant
    bh <- solve(t(X)%*%X)%*%t(X)%*%ymat

    XX <- solve(t(X)%*%X)
    cmat <- matrix(1,1,1) 
    Q <- matrix(c(0,1,1,0),ncol(X),1) # a1+a2=1 for y = c + a1x1 + a2x2 + a3x3
    bc <- bh-XX%*%Q%*%solve(t(Q)%*%XX%*%Q)%*%(t(Q)%*%bh-cmat)

   library(quadprog)
   d <- t(ymat) %*% X
   Rinv = solve(chol(t(X)%*%X)) 
   qp <- solve.QP(Dmat=Rinv, dvec=d, Amat=Q, bvec=cmat, meq=1, factorized=TRUE)
   qp

   cbind(bh,qp$unconstrained.solution)
   cbind(bc,qp$solution)

'''

r constraints quadratic-programming
1个回答
0
投票

假设问题是最小化|| ymat-X b ||服从b [2] * b [3] == b [4]的^ 2我们可以用b [4]代替,给出如下所示的nls问题。下面的b是b的前3个元素,我们可以通过将下面b的后两个元素相乘得到b [4]。不使用任何软件包。

fm <- nls(ymat ~ X %*% c(b, b[2] * b[3]), start = list(b = 0:2))
fm

给予:

Nonlinear regression model
  model: ymat ~ X %*% c(b, b[2] * b[3])
   data: parent.frame()
     b1      b2      b3 
76.9718  0.6275  0.7598 
 residual sum-of-squares: 204

Number of iterations to convergence: 4 
Achieved convergence tolerance: 6.555e-06

计算b4

prod(coef(fm)[-1])
## [1] 0.476805
© www.soinside.com 2019 - 2024. All rights reserved.