R optim function - 为各个参数设置约束
R optim function - Setting constraints for individual parameters
我希望使用 optim
最小化一个函数,如下所示:
yield <- function(data, par) {
with(data, par[1] + (par[2] + par[3]/par[4])*(1-exp(-par[4]*maturity))/(par[4]*maturity) - (par[3]*exp(-par[4]*maturity)/par[4]))
}
min.RSS <- function(data, par) {
sum((data$price - 100*exp(-data$maturity*yield(data, par)))^2)
}
result <- optim(par = theta, min.RSS, data = data))
参数par[1]
和par[4]
必须是非负数,而另外两个是无约束的。是否可以将这些约束包含在 optim
函数中?
谢谢
只是为了让@BondedDust 的建议非常清楚:
yield <- function(data, par) {
with(data, par[1] + (par[2] + par[3]/par[4])*(1-exp(-par[4]*maturity))/(par[4]*maturity) - (par[3]*exp(-par[4]*maturity)/par[4]))
}
# the function being optimized
min.RSS <- function(data, par) {
# EXPONENETIATE PARAMTERS 1 AND 4 TO MAKE THEM POSITIVE.
par[1] <- exp(par[1])
par[4] <- exp(par[4])
sum((data$price - 100*exp(-data$maturity*yield(data, par)))^2)
}
PAR <- theta
# LOG TRANSFRORM THE INITIAL VALUES FOR PARAMTERS 1 AND 4
PAR[1] <- log(PAR[1])
PAR[4] <- log(PAR[4])
# CALL optim()
result <- optim(par = PAR,
min.RSS,
data = data))
# THE BEST SET OF PARAMETERS
par <- result$par
# again, exponenetiate paramters 1 and 4 to make them positive.
par[1] <- log(par[1])
par[4] <- log(par[4])
我希望使用 optim
最小化一个函数,如下所示:
yield <- function(data, par) {
with(data, par[1] + (par[2] + par[3]/par[4])*(1-exp(-par[4]*maturity))/(par[4]*maturity) - (par[3]*exp(-par[4]*maturity)/par[4]))
}
min.RSS <- function(data, par) {
sum((data$price - 100*exp(-data$maturity*yield(data, par)))^2)
}
result <- optim(par = theta, min.RSS, data = data))
参数par[1]
和par[4]
必须是非负数,而另外两个是无约束的。是否可以将这些约束包含在 optim
函数中?
谢谢
只是为了让@BondedDust 的建议非常清楚:
yield <- function(data, par) {
with(data, par[1] + (par[2] + par[3]/par[4])*(1-exp(-par[4]*maturity))/(par[4]*maturity) - (par[3]*exp(-par[4]*maturity)/par[4]))
}
# the function being optimized
min.RSS <- function(data, par) {
# EXPONENETIATE PARAMTERS 1 AND 4 TO MAKE THEM POSITIVE.
par[1] <- exp(par[1])
par[4] <- exp(par[4])
sum((data$price - 100*exp(-data$maturity*yield(data, par)))^2)
}
PAR <- theta
# LOG TRANSFRORM THE INITIAL VALUES FOR PARAMTERS 1 AND 4
PAR[1] <- log(PAR[1])
PAR[4] <- log(PAR[4])
# CALL optim()
result <- optim(par = PAR,
min.RSS,
data = data))
# THE BEST SET OF PARAMETERS
par <- result$par
# again, exponenetiate paramters 1 and 4 to make them positive.
par[1] <- log(par[1])
par[4] <- log(par[4])