Practice in Lab: Project: nested group validation with auditable outer predictions →
Project: nested group validation with auditable outer predictions
Using cross-validation to choose a hyperparameter and then reporting the same best score is optimistic. Nested validation gives the selection procedure its own outer evaluation boundary. Group identities must remain intact in both loops. This project repeatedly fits real ridge regressors and exposes which samples trained each outer model. Poisoning an outer group's labels must leave its predictions and selected penalty unchanged, although its measured error changes. The result estimates this small selection procedure under the declared grouping; it does not establish independence or deployment representativeness.
groups = ['a','a','b','b','c','c']
for held in sorted(set(groups)):
train_ids = [i for i,g in enumerate(groups) if g != held]
print(held, train_ids)Review the design
Explain inner selection versus outer evaluation, group weighting and the final refit that would follow evaluation. Audit sample identities, not only aggregate scores.
Your task
Rows have unique id, string group, finite scalar x,y. Require at least three groups and positive finite penalties. Outer leave-one-group-out evaluation must exclude that group's rows from both tuning and fitting. For each penalty, inner leave-one-group-out validation over the remaining groups computes equal-fold mean MSE; choose (MSE,penalty) minimum. Fit centered one-feature ridge with slope=sum((x-mx)*(y-my))/(sum((x-mx)**2)+alpha), unpenalized intercept. Return oof mapping, row-weighted outer mse and folds with group, alpha, fit_ids, held_ids.
The explanation opens here once every check passes.