【问题标题】:Weight optimization to find out least squared error in R [closed]权重优化以找出 R 中的最小二乘误差 [关闭]
【发布时间】:2019-05-09 06:29:42
【问题描述】:

我有实际值和四个不同的模型及其预测值和拟合值。使用这些拟合值,我想找到最佳权重,以便 (summation(wifi)-actuals)^2 最小化。这里 wi 是我想要找到的最佳权重 & fi 是每个模型的拟合值。

我对 wi 的限制是;

  1. 权重必须大于 0,
  2. 权重必须小于 1,
  3. 权重之和必须为 1

我在这里看到了一个类似的示例 [https://stats.stackexchange.com/questions/385372/weight-optimization-in-order-to-maximize-correlation-r],但我无法针对我的特定问题复制它。

让我们生成示例数据以更好地理解问题

actuals <- floor(runif(10, 500,1700)) 
model1_fitted <- floor(runif(10, 600,1800)) 
model2_fitted <- floor(runif(10, 400,1600)) 
model3_fitted <- floor(runif(10, 300,1500)) 
model4_fitted <- floor(runif(10, 300,1200)) 
sample_model <- data.frame(actuals, model1_fitted, model2_fitted,model3_fitted,model4_fitted)

现在,我需要以最佳方式找到 (w1,w2,w3,w4) 以便 (summation(wifi)-actuals)^2 最小化。我想保存权重,正如我提到的,我也有这四个模型的预测。如果我得到最佳权重,我对集成模型的预测值将是这些权重和预测值的线性函数。集成的第一个预测值如下所示,

ensemble_pred_1 = w1*model1_pred1+w2*model2_pred1+w3*model3_pred1+w4*model4_pred1

请帮助我找到最佳 wi,以便我可以根据需要生成集成模型。

【问题讨论】:

  • 这是一个具有线性约束的二次规划。尝试 quadprog 包中的 solve.QP 函数
  • @Rohit,你能用一个简单的例子详细说明一下吗?

标签: r optimization weighting


【解决方案1】:

根据优化问题构建您的问题并计算所需的约束:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
set.seed(123)
model1_fitted <- floor(runif(10, 600,1800)) 
model2_fitted <- floor(runif(10, 400,1600)) 
model3_fitted <- floor(runif(10, 300,1500)) 
model4_fitted <- floor(runif(10, 300,1200)) 
w <- c(0.2,0.3,0.1,0.4) # sample coefficients
sample_model <- tibble(model1_fitted, model2_fitted,model3_fitted,model4_fitted) %>%
  mutate(actuals= as.vector(as.matrix(.) %*% w)  + rnorm(10,sd=10))


X <- as.matrix(sample_model[,1:4])
y <- as.matrix(sample_model[,5])

# From solve.QP description
# solving quadratic programming problems of the form min(-d^T b + 1/2 b^T D b) with the constraints A^T b >= b_0.

# Your problem
# Minimize       || Xw - y ||^2     => Minimize 1/2 w'X'Xw - (y'X)w  => D=X'X , d= X'y
# Constraint w>0,w<1, sum(w)=1      => A'w >= b0

d <- t(X) %*% y
D <- t(X) %*% X
A <- cbind(rep(1,4),diag(4)) #constraint LHS
b0 <- c(1,numeric(4)) # constraint RHS

library(quadprog)
soln <- solve.QP(D,d,A,b0,meq = 1)
w1 <- soln$solution  # Your model wieghts
w1
#> [1] 0.20996764 0.29773563 0.07146838 0.42082836

reprex package (v0.2.1) 于 2019 年 5 月 9 日创建

【讨论】:

  • 感谢您的回答。我有点忙,所以回复迟了。在 soln
  • 逗号是错字,已修复。如果您的数据中有 NA/NaN/Inf 值,您将收到该错误。在训练模型之前删除这些行。请参阅:stackoverflow.com/questions/15773189/… 和其他类似线程
猜你喜欢
  • 2015-09-24
  • 2015-09-26
  • 1970-01-01
  • 2013-02-20
  • 2018-12-27
  • 2014-07-25
  • 1970-01-01
  • 2012-04-29
  • 2018-06-02
相关资源
最近更新 更多