2017-10-11 58 views
-2

我想找到一個最大經濟壓力情景,該情景受此場景的馬氏距離限制。爲此,我必須考慮優化中的兩個功能。通過R中的兩個函數實現最大化

爲了方便起見,我們可以使用一個簡化的問題:我們有一個簡單的線性模型:y=a+bx。爲此,我想盡量減少:sum(a+bx-y)^2。但是,我也有例如限制:(ab*5)/2<30

用Excel解算器計算這個問題不是問題。但是,我如何得到這個?

+1

你嘗試過這麼遠嗎? SO不是「請爲我寫代碼」網站。你應該看看做一個好的[MRE](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – tbradley

+0

也許發佈的Excel解算器的步驟和什麼你有*到目前爲止嘗試*然後只有當人們可能開始提供 – amonk

+2

StackOverflow不是一個家庭作業網站請閱讀https://stackoverflow.com/help/how-to-ask – F0XS

回答

0

您可以嘗試納入約束爲目標函數,這樣

# example data whose exact solution lies outside the constraint 
x <- runif(100, 1, 10) 
y <- 3 + 5*x + rnorm(100, mean=0, sd=.5) 

# big but not too big 
bigConst <- sum(y^2) * 100 

# if the variables lie outside the feasible region, add bigConst 
f <- function(par, x, y) 
    sum((par["a"]+par["b"]*x-y)^2) + 
    if(par["a"]*par["b"]>12) bigConst else 0 

# simulated annealing can deal with non-continous objective functions 
sol <- optim(par=c(a=1, b=1), fn=f, method="SANN", x=x, y=y) 

# this is how it looks like 
plot(x,y) 
abline(a=sol$par["a"], b=sol$par["b"])