假设我有一个简单的回归方程
lm(y~., newdata=df)
我知道如果我想把截距减少到0,我会写
lm(y+0., newdata=df)
然而,有没有一种方法可以产生逐步回归,同时将每个系数限制在一个特定的范围内?例如:
step(lm(y~.>1000, newdata=df)
上面的方法不起作用,但有没有一种方法可以说产生一个回归,基本上产生最佳拟合,并迫使每个系数大于1,000?或者,小于指定的范围。
#as per Gautam
minfunc <- function(coefs){
out <- sum(sapply(3:314, function(z) return(coefs[z]*test2[, z])))
return(out)
}
par = c(1, 1, 30) # initial value
lb = c(-1, -1, -300000) # lower bound for coefs
ub = c(30, 30, 30000) # upper bound
result <- hjkb(par = par, fn = minfunc, lower = lb, upper = ub)
谢谢,
发布于 2018-06-09 04:22:15
这里有一个应该可以工作的代码。您将需要调整边界等,以获得您想要的。
library(data.table)
library(dfoptim)
minfunc <- function(coefs){
# using mtcars as the sample data - you would read in your data here
df <- as.data.table(mtcars)
out <- (sum(coefs[1]*df$cyl + coefs[2]*df$wt + coefs[3]) - sum(df$mpg))^2
return(out)
}
par = c(1, 1, 30) # initial value
lb = c(-1, -1, -300000) # lower bound for coefs
ub = c(30, 30, 30000) # upper bound
result <- hjkb(par = par, fn = minfunc, lower = lb, upper = ub)
与lm
相比:
> lm(mpg ~ cyl + wt, data = mtcars)
Call:
lm(formula = mpg ~ cyl + wt, data = mtcars)
Coefficients:
(Intercept) cyl wt
39.686 -1.508 -3.191
> result$par
[1] 0.00000 -1.00000 23.30788
# cyl wt constant
正如预期的那样,结果有所不同。算法的收敛性和最终结果取决于优化算法的选择和初始输入。我以hjkb
为例,但它不是最好的算法。您可能希望根据需要尝试不同的算法。
https://stackoverflow.com/questions/50766431
复制相似问题