R中的约束优化比手动更差

时间:2015-08-04 14:57:46

标签: r optimization

我在R. Code中运行约束优化并且没有错误。但优化的解决方案比我手动看到的更糟糕!优化终止,没有错误和0终止代码。然而,我的解决方案成本更低。即使手动解决方案作为初始解决方案提供,程序运行并且不会抱怨第一个解决方案不可行(在不同的情况下它会做到这一点),然后又回到更高成本的最佳解决方案。

你能帮助发生什么事吗?下面的代码运行,可直接在R中进行测试。

num.prod <- 4
cd.penalty <- 0.001
in.data <- data.frame(V1=c(70.22, 249.92, 241.55, 70.75), V2=c(185.04, 287.43, 240.07, 277.88))

# initial solution
temp <- max(in.data$V1, in.data$V2)
init.flow <- rep(round(temp,-floor(log10(temp))), (num.prod+1)^2)

# cost matrix
cost.mat <- matrix(0, nrow=num.prod+1, ncol=num.prod+1)
for (i in (num.prod/2+1):num.prod) {
    cost.mat[i, 1:num.prod/2] <- cd.penalty
    cost.mat[i, setdiff((num.prod/2+1):num.prod, i)] <- cd.penalty
    cost.mat[i, num.prod+1] <- cd.penalty
}


# constraint matrix
n <- num.prod + 1
cons.mat <- matrix(0, nrow=2*n+n*n, ncol=n*n)
for (i in 1:n) { # outflow
    cons.mat[i, ((i-1)*n+1):(i*n)] <- 1
}
for (i in 1:n) { # inflow
    cons.mat[i+n, seq(i, n*n, n)] <- 1
}
for (i in 1:(n*n)) { # var level
    cons.mat[i+2*n, i] <- 1
}

# constraints constants
balance <- c(c(round(in.data$V1,2), 0), c(round(in.data$V2,2), 0), rep(0, (num.prod+1)^2))

# objective function
flow.cost <- function(flow) {
    flow1 <- matrix(flow, nrow=num.prod+1, byrow=T)
    cost <- sum(flow1 * cost.mat) + sum(flow1 > 0.01)
    return(cost)
}

# optimized solution
result12 <- constrOptim(theta=init.flow, f=flow.cost, ui=cons.mat, ci=balance,
                        method="Nelder-Mead", outer.iterations=500, control=list(maxit=1000))

matrix(result12$par, nrow=num.prod+1, byrow=T) # optimize solution
result12$value # 17

# manual solution
mysol <- matrix(c(70.22291, rep(0,5), 249.92384, rep(0,5), 240.0733, 0, 1.47988, rep(0,3), 70.75244, 0, 114.81899, 37.50806, 0, 207.13116, 0), nrow=num.prod+1, byrow=T)
flow.cost(t(mysol)) # 8.00148

0 个答案:

没有答案