R语言solnp约束优化:如何获取[-1,1]区间内的均值与标准差最优值
Fixing the Bounds Issue in Your solnp Optimization
Hey there! The problem you're facing is that you haven't specified the box constraints (the [-1, 1] limits for each x variable) in your solnp setup. Without these bounds, the solver can freely explore parameter values outside your valid encoded data range, which leads to those extreme, invalid parameter values you're seeing in the iteration logs.
How to Add Variable Bounds to solnp
The solnp function supports LB (lower bounds) and UB (upper bounds) arguments to restrict each variable to a specific range. Here's how to modify your code to enforce the [-1, 1] constraint for all three x variables:
# Define your standard deviation objective function (to minimize) fn1 <- function(x) { intercept1 + x1S*x[1] + x2S*x[2] + x3S*x[3] + x4S*x[1]*x[2] + x5S*x[1]*x[3] + x6S*x[2]*x[3] + x7S*x[1]^2 + x8S*x[2]^2 + x9S*x[3]^2 } # Define the mean equality constraint (must equal 500) eqn1 <- function(x) { intercept2 + x1m*x[1] + x2m*x[2] + x3m*x[3] + x4m*x[1]*x[2] + x5m*x[1]*x[3] + x6m*x[2]*x[3] + x7m*x[1]^2 + x8m*x[2]^2 + x9m*x[3]^2 } # Set constraints constraint <- c(500) x0 <- c(-1, -1, -1) # Initial guess within valid range # Add lower and upper bounds for each x variable (all [-1, 1]) LB <- c(-1, -1, -1) UB <- c(1, 1, 1) # Run optimization with bounds LG <- solnp(x0, fun = fn1, eqfun = eqn1, eqB = constraint, LB = LB, UB = UB)
Key Notes:
- Bounds Enforcement: The
LBandUBvectors explicitly tell the solver that eachxparameter can't go below -1 or above 1. This will keep all iterations within your valid encoded data range. - Why Your Previous Run Failed: Without bounds, the solver was allowed to push parameters to extreme values in an attempt to minimize the standard deviation (even though this led to nonsensical results for your use case). Adding bounds forces it to find the best solution within your valid input space.
- Check for Feasibility: If the solver returns an error about infeasibility, it means there's no combination of
xin [-1,1] that makes the mean equal to 500. In that case, you might need to adjust your constraint (e.g., relax it to a range) or verify your mean function's correctness. - Initial Guess: Using an initial guess (
x0) within the valid bounds helps the solver converge faster to a feasible solution.
内容的提问来源于stack exchange,提问作者Jane
相关产品推荐
相关产品推荐

