Fitting Simplex-Constrained Action Weights for a Usage Score
Statistics & ExperimentsModel answerLast updated
Estimate non-negative, sum-to-one weights for four user actions predicting time spent, handle collinearity, quantify uncertainty, stabilize with priors, and tune Elastic Net by cross-validation.
Scenario
You work on the data science team of a large social app. You want a single "usage score" per user built from four kinds of actions taken in the past 30 days: likes (L), comments (C), shares (S) and saves (V). You have data for 1 million users, including each user's total time spent in the app, T.
You propose a linear model:
T = wL·L + wC·C + wS·S + wV·V + ε
Questions
-
Estimating the weights
- How would you estimate the weights if each must be non-negative and all four must sum to 1?
- Likes and shares are strongly correlated. How do you deal with that?
-
Uncertainty and stability
- Describe how you would produce a 95% confidence interval for each weight.
- The model fits the training data well but its estimates vary a lot on held-out data. How would Bayesian priors help stabilize them?
-
Implementation
- Suppose you drop the hard constraints and use Elastic Net instead. Outline, in pseudo-code or a clear logic flow, k-fold cross-validation to choose the regularization parameters.
Considerations
- The four counts are on different scales and heavily right-skewed.
- Newer users often have zeros for some actions simply because they have been around briefly.
- State explicitly what you assume about the distribution of the error term ε, and justify it.
Hints
Hint 1
Ask what units the weights have. If T is in minutes, can the weights meaningfully sum to 1? Consider separating an overall scale factor from the relative importance of each action.
Hint 2
With only four parameters, the constrained fit is a small convex quadratic program. Think about KKT conditions, and about why weights that sit exactly at 0 break standard asymptotic confidence intervals.
Hint 3
A Gaussian prior on coefficients corresponds to ridge, and a Dirichlet prior is the natural choice on the simplex. For cross-validation, ask which steps (log transform, scaling) must be fit inside each fold to avoid leakage.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing and assumptions
Start by stating assumptions, since the question explicitly asks for them.
Error term. Assume E[ε | X] = 0 (correct specification on average) and independent users. Do not assume Gaussian, constant-variance errors. Time spent is non-negative and right-skewed, and its variance grows with activity, so errors are heteroskedastic. Consequently I use least-squares point estimates but rely on robust inference (bootstrap or HC standard errors). If residuals are badly skewed, model log(T) or use a Gamma/Tweedie likelihood.
Scale and skew. Apply log1p to each count, then standardize. This matters because penalties are scale-dependent and because a sum-to-one constraint is only interpretable if features share a scale.
The sum-to-one trap. If T is in minutes, the raw coefficients carry units of minutes per action, so forcing them to sum to 1 is meaningless. Separate scale from relative importance:
T = a + b·(wL·L̃ + wC·C̃ + wS·S̃ + wV·Ṽ) + ε, w ≥ 0, Σw = 1
Here b absorbs units and w is each action's share of the score. Equivalently, fit non-negative β and set w = β / Σβ.
Sparse new users. A zero for a 2-day-old account means "no opportunity yet", not "no interest". Normalize by exposure (actions per active day or per impression), add tenure as a covariate, exclude users below a minimum tenure, or pool them toward global weights with a hierarchical prior.
1. Constrained estimation
The problem is a convex QP:
min_w ||y − Xw||² s.t. w ≥ 0, 1ᵀw = 1
KKT: 2Xᵀ(Xw − y) + λ1 − μ = 0, μ ≥ 0, μ_k·w_k = 0. Each weight is either positive with zero adjusted gradient or pinned at 0.
Practical solvers:
- A QP solver (cvxpy, quadprog). Precompute
XᵀX(4×4) once, so 1M rows is irrelevant. - NNLS with an augmented row
M·1ᵀand targetMfor a largeM, which approximates the equality constraint. - Projected gradient descent onto the simplex.
Likes vs. shares collinearity.
- Diagnose with VIF, the condition number of the standardized
XᵀX, and bootstrap instability (weight swinging between L and S). - Collinearity inflates the variance of individual weights, not prediction error. Predictions can be fine while attribution is unstable.
- Remedies: add an L2 term
γ||w||²(spreads weight across correlated features; note the simplex alone behaves like an L1 ball and tends to zero out one of the pair); reparameterize into volumeL+Sand a ratio likeS/(L+1); or use PCA, which decorrelates but destroys per-action interpretability, so I would mention and deprioritize it.
2. Uncertainty and Bayesian stabilization
Confidence intervals. Normal-theory intervals fail because weights near 0 lie on the parameter-space boundary and ε is non-normal. Use a pairs bootstrap:
- Resample users with replacement, B ≈ 1,000–2,000.
- Rerun the whole pipeline (transforms, scaling, constrained fit) on each resample.
- Take the 2.5% and 97.5% percentiles (or BCa) per weight.
- Report the fraction of resamples where each weight is exactly 0, because the bootstrap distribution has a point mass there.
If users cluster (region, friend groups), resample clusters. For speed, use subsampling or the Bag of Little Bootstraps; with four parameters, precomputed sufficient statistics make each refit cheap.
Priors to reduce out-of-sample variance.
w ~ Dirichlet(α)respects the simplex. Larger, equal α shrinks toward equal weights; informed α encodes prior knowledge from past experiments or research.- Without the simplex, use half-normal or log-normal priors on
β ≥ 0. - A Gaussian prior gives ridge as the MAP estimate, linking the Bayesian and penalized views.
- Use a Student-t or Gamma likelihood for heavy tails.
- Hierarchical pooling by cohort (tenure bucket, country):
w_g ~ Dirichlet(κ·w_global), so sparse cohorts borrow strength; learnκfrom data. - Fit with NUTS (Stan/PyMC) on a stratified subsample, or variational inference, and report 95% credible intervals.
3. Cross-validation for Elastic Net
l1_grid = [0.1, 0.3, 0.5, 0.7, 0.9, 1.0]
lam_grid = logspace(-4, 1, 50)
folds = split_by_user(K=5, stratify=[tenure_bucket, has_share])
for r in l1_grid:
for lam in lam_grid:
errs = []
for k in 1..K:
train, val = all_except(k), fold[k]
prep = fit(log1p + scaler, on=train) # train only
model = ElasticNet(alpha=lam, l1_ratio=r, positive=True)
model.fit(prep(train.X), train.y)
errs.append(RMSE(val.y, model.predict(prep(val.X))))
cv[r, lam] = (mean(errs), stderr(errs))
best = argmin(cv.mean)
chosen = largest lam with cv.mean <= cv[best].mean + cv[best].se # 1-SE rule
refit on all data; optionally normalize coefficients to sum to 1
Key points: fit preprocessing inside each fold to avoid leakage, stratify so rare sharers appear in every fold, use warm starts along the λ path, and use an out-of-time holdout if the data has a time dimension.
Trade-offs and common mistakes
- Imposing sum-to-one on raw, unit-bearing coefficients without a separate scale term.
- Using normal-theory CIs for weights that sit on the boundary.
- Fitting scalers or transforms on the full dataset before cross-validation.
- Treating zeros from new users as true "no engagement".
- Interpreting individual weights as causal. This is a predictive association; engagement time can also drive actions (reverse causality).
- Reading unstable L/S weights as meaningful when the real issue is collinearity.
Constrained fits give interpretable shares but are biased if the constraint is wrong; Elastic Net is more flexible and predictive but yields weights you must renormalize. Presenting both and comparing out-of-sample error is a sound final recommendation.