Espartaco

“Is that to say we are against Free Trade? No, we are for Free Trade, because by Free Trade all economical laws, with their most astounding contradictions, will act upon a larger scale, upon the territory of the whole earth; and because from the uniting of all these contradictions in a single group, where they will stand face to face, will result the struggle which will itself eventuate in the emancipation of the proletariat.”

Karl Heinrich Marx · Marx-Engels Collected Works, Vol. VI, p. 290

28,317 views since December 2020

28,317 visitas desde diciembre de 2020

EnglishEspañol

SELECTING EXPLANATORY VARIABLES IN STATISTICAL MODELS

Mathematical statistics · Philosophy of science

Selecting Explanatory Variables in Statistical Models

Parsimony, structure, prediction, and methodological critique

25 MAR 2022 · REVISED 08 NOV 2026

Selecting a model requires deciding which relationships to preserve and how to test their consequences. This exposition connects philosophical discussion of parsimony with a reproducible comparison of 128 regressions for the fifty U.S. states. It presents selection criteria, derives PRESS, distinguishes influence from prediction error, and validates the entire procedure. Its central result—four predictors and an outer RMSE of 0.793 years under AIC selection—remains conditional on the model family, historical data, and analytical purpose.

1. Select for a specific question

A statistical model organizes relationships among observed quantities through assumptions about a population or process. Selecting explanatory variables means delimiting a representation: deciding which terms to retain, what information they contribute, and what uncertainty the decision introduces. The goal is more than shortening a list of columns. The scientific question, measurement quality, design structure, and intended use all matter.

Three tasks should be distinguished. Description summarizes associations within the data. Prediction approximates responses for observations that did not participate in fitting. Causal explanation identifies what would change under an intervention, requiring additional substantive and identification assumptions. An observational regression selected by AIC does not automatically answer that last question.

PurposeCentral decisionRequired evidence
DescriptionSummarize relationships clearlyMeasurement, fit, and diagnostics
PredictionReduce out-of-sample lossValidation of the entire procedure
CausalityIdentify a defined effectDesign, temporal order, and confounding control

The word explanatory, commonly used to denote a predictor, does not guarantee a mechanistic explanation. A predictive variable may proxy other conditions; a confounder may need to remain even when its coefficient fails a conventional threshold. Before automation, define the candidate universe and any variables that scientific reasoning requires retaining.

2. Parsimony, abstraction, and material structure

The principle of parsimony discourages unnecessary complications when several representations are adequate for a purpose. Its historical connection to Occam’s razor does not make simplicity a guarantee of truth or the exclusive property of one probabilistic school. Adequacy must be justified: a short description may omit a decisive relationship, while a long one may capture noise.

From the standpoint of Dialectical Materialism, scientific abstraction can be understood as a conceptual reconstruction of objective, historically determined relationships. Particular and general determinations are connected: concepts do not exist independently of all material activity, but their content is not merely an arbitrary collection of names. Within this framework, variable reduction should be assessed by the determinations it preserves and the mediations it removes. This is a philosophical interpretation of modelling, not a selection theorem.

The distinction between outward appearance and internal connection is central to Marx’s critique of representations of economic relations in Capital, volume III, chapter 48 (Marx, 1894/1999). Carefully applied to statistics, it encourages questions about why an association appears and under which conditions it recurs. It does not justify inferring a social cause from a coefficient’s sign or declaring the shortest model true.

The economy of a representation must remain subordinate to the adequacy of the relationships it represents.

Four meanings of complexity should be separated: the complexity of a material phenomenon, the parameter count of a representation, an algorithm’s execution cost, and the difficulty of interpreting its output. An efficient algorithm can search a large model family; a small parameter set can describe a complex process. Analogies across these levels are useful when their limits are explicit.

A rigorous critique of nominalism or subjectivism requires its own arguments. Associating Occam’s name with a penalty formula is insufficient, as is treating every prior distribution as an arbitrary choice. Practical objectivity is strengthened by explicit assumptions, tests of consequences, and sensitivity analysis in both frequentist and Bayesian procedures.

3. Linear models, assumptions, and hierarchy

Consider the conditional mean model y = Xβ + ε. The design matrix X has n rows and p columns; p includes the intercept. With full column rank and n > p, the ordinary least squares estimator and projection matrix are:

β̂ = (XᵀX)−1Xᵀy   ·   ŷ = Hy   ·   H = X(XᵀX)−1Xᵀ

The formula describes the algebraic solution; unbiased estimation of β requires E(ε | X) = 0. The classical variance σ²(XᵀX)−1 requires Var(ε | X) = σ²I. Conditional normality gives exact t and F distributions for a specification fixed in advance. A selection algorithm does not establish these conditions. Numerical implementation should use QR, as lm() does, rather than explicitly forming an inverse.

Term hierarchy should be distinguished from multilevel models. In the former sense, a specification containing xz usually retains x and z; one containing x² usually retains x. This is a construction and interpretation rule, especially useful under changes of origin and scale. Substantive restrictions may justify exceptions. In the latter sense, hierarchy describes levels of variation, such as people within regions, often with random effects.

E(Y | x, z) = β₀ + β₁x + β₂z + β₃xz   ;   E(Y | x) = β₀ + β₁x + β₂x²

A fixed-degree polynomial regression remains parametric and linear in its coefficients even though its response curve is nonlinear in x. Centering can reduce some collinearity; orthogonal bases re-express the same fitted space when degree is held fixed. Orthogonal columns do not establish statistical independence of the original variables. Transformation constants must be retained for prediction, and unjustified extrapolation should be avoided (Kutner et al., 2005).

4. What each criterion measures

RSS denotes the residual sum of squares and TSS the total sum of squares around the mean. R² increases or stays unchanged when columns are added to a nested model fitted on the same observations. Its adjusted version penalizes consumed degrees of freedom:

R² = 1 − RSS/TSS   ;   R̄² = 1 − [RSS/(n − p)]/[TSS/(n − 1)]

Mallows’ subset comparison uses a common estimate of residual variance from the full model, s²full. Seeking a small Cp near p presumes that this reference is reasonable. Cp < p is not a test proving absence of bias; the statistic fluctuates and depends on the reference model (Mallows, 1973).

Cp = RSS/s²full − n + 2p

For likelihood-based criteria, K denotes the total number of estimated parameters. In Gaussian regression with unknown variance, K = p + 1. AIC estimates a predictive discrepancy through an adjustment to fit; BIC corresponds to an asymptotic evidence approximation under regularity conditions. Their goals are not interchangeable (Akaike, 1974; Schwarz, 1978).

AIC = −2ℓ(θ̂) + 2K
BIC = −2ℓ(θ̂) + K log(n)
AICc = AIC + 2K(K + 1)/(n − K − 1)

The stated AICc expression applies to Gaussian linear regression and requires n > K + 1; it should not be transferred indiscriminately to every model family. It is relevant when K is not negligible relative to n (Hurvich & Tsai, 1989).

CriterionPreferred directionInterpretive limit
Adjusted R²HigherPenalized in-sample fit
CpSmall; assess relation to pDepends on full-model variance estimate
AIC / AICcLowerRelative comparison, not a diagnostic
BICLowerAssumption-dependent approximation
PRESS / LOOCV RMSELowerPrediction with a fixed formula

Comparisons require compatible responses, scales, observations, and likelihood treatment. Absolute values from AIC() differ from extractAIC(), used by step(), through constants and variance parameter counting. Across comparable Gaussian models with the same n, these differences do not change the ordering. All tables here use AIC() and BIC() (R Core Team, n.d.-c).

5. The fifty-state example

The example uses datasets::state.x77, a matrix included in R containing eight variables for the fifty U.S. states in alphabetical order. R’s documentation traces the information to U.S. Bureau of the Census publications from 1977. This reconstructs the originally described case without private files or machine-specific paths. The following numbers refer to this public dataset, not to an inspection of the unpublished Vida.Rdata file (R Core Team, n.d.-e).

Name usedMeasurementTime reference
lifeLife expectancy, years1969–1971
popPopulation, thousands of residents1 July 1975
incomePer capita income, dollars1974
illiteracyIlliteracy, percent1970
murderMurder and non-negligent manslaughter per 100,000 residents1976
hsgradHigh-school graduation, percent1970
frostMean days with minimum below 32 °F (0 °C), capital or large city1931–1960
areaLand area, square milesGeographic measure

murder does not measure crime in general. frost measures the frequency of days below freezing, not mean temperature. Measurements also refer to different periods: some covariates postdate the response. This is a retrospective association comparison, not a prospective prediction exercise using information available in 1969.

base <- as.data.frame(datasets::state.x77)
names(base) <- c("pop", "income", "illiteracy", "life",
                 "murder", "hsgrad", "frost", "area")
stopifnot(nrow(base) == 50L, !anyNA(base))
full <- lm(life ~ ., data = base)

6. Exhaustive search and results

Seven numeric predictors and a mandatory intercept produce 2⁷ = 128 subsets, including the intercept-only model; 127 contain at least one predictor. This family excludes interactions, polynomials, and additional transformations. Its best candidate is therefore best within that universe, not among every conceivable representation.

Branch-and-bound can locate best subsets by size without naively fitting every combination. However, the returned table depends on how many candidates per size are requested. leaps() and regsubsets() are search tools; choosing a size and evaluating the result remain additional decisions. Nor does retaining only the lowest RSS per size guarantee the minimum PRESS, which also depends on leverage. All 128 candidates were fitted here to check every criterion (Lumley, n.d.).

Top eight by AIC; all models include an intercept.
#PredictorspR̄²CₚAICBICPRESS
1pop + murder + hsgrad + frost50.71262.020115.733127.20529.648
2pop + income + murder + hsgrad + frost60.70614.009117.720131.10431.322
3pop + illiteracy + murder + hsgrad + frost60.70614.013117.724131.10831.053
4pop + murder + hsgrad + frost + area60.70604.018117.731131.11534.284
5murder + hsgrad + frost40.69393.740117.974127.53431.197
6income + murder + hsgrad + frost50.68945.411119.614131.08632.695
7illiteracy + murder + hsgrad + frost50.68925.430119.634131.10732.721
8pop + income + illiteracy + murder + hsgrad + frost70.69936.002119.712135.00832.953

The model containing pop + murder + hsgrad + frost maximizes adjusted R² and minimizes Cp, AIC, AICc, BIC, and PRESS. It has p = 5 regression coefficients and K = 6 parameters including variance. Its values are RSS = 23.308; R² = 0.7360; adjusted R² = 0.7126; AICc = 117.686; and Cp = 2.020. Agreement among six criteria is a feature of this example, not a general equivalence.

Two plots of delta AIC and delta BIC against number of predictors, with their minima at four predictors.
Figure 1. Differences from each criterion’s minimum across 128 candidates. The diamond identifies the selected model. Reference line at Δ = 2; this is not a hypothesis test. Original calculations.

The three-predictor candidate murder + hsgrad + frost has BIC = 127.534, only 0.330 above the minimum. This supports acknowledging uncertainty about whether population is needed rather than declaring a decisive victory. Adding income, illiteracy, or area barely reduces RSS while consuming additional parameters.

7. PRESS: prediction with one observation omitted

Let ei = yi − ŷi be the ordinary residual and hii the corresponding diagonal entry of H. When the formula stays fixed and deletion fits retain full rank, the prediction residual obtained by excluding observation i is:

di = yi − ŷi(i) = ei/(1 − hii)
PRESS = Σi=1ndi²   ;   RMSELOOCV = √(PRESS/n)

This identity avoids refitting the same model n times. PRESS sums squared prediction errors; dividing by n gives the LOOCV mean squared error, and taking its square root restores the response unit. If d is a column vector, dᵀd is its squared Euclidean norm, a scalar. It is not obtained by taking a determinant of d.

In the income-only model, Alaska has an observed life expectancy of 69.310 years and a fitted value of 72.275. When Alaska is excluded, its predicted response rises to 73.068 years. The ordinary residual is −2.965, hii = 0.210875, and the deleted residual is −3.758. The relevant error compares the prediction to the observed response, rather than subtracting the two predictions from each other (R Core Team, n.d.-d).

dAlaska = −2.965474/(1 − 0.210875) = −3.757926
Income and life-expectancy scatterplot with two regression lines; Alaska lies below both.
Figure 2. Regression of life expectancy on income using all fifty states and excluding Alaska. The vertical line shows Alaska’s prediction residual when it does not participate in fitting. Original calculations.

A high PRESS does not establish that a particular observation has greater influence. The statistic aggregates errors over all units and combines residuals with design geometry. Attributing influence to Alaska or another state requires individual quantities, such as Cook’s distance or changes in coefficients.

8. Compare models with visible results

The table combines specifications from the original exercise with the selected candidate. The original four predictors are population, income, illiteracy, and area. The selected four are population, murder, high-school graduation, and frost. Every value uses the same fifty observations and includes an intercept.

ModelRSSR̄²PRESSRMSE LOOCV
Intercept only88.2990.000091.9401.356
Income78.0760.097489.3221.337
Population + murder30.4450.640534.0660.825
Original four55.6020.314391.4271.352
Selected four23.3080.712629.6480.770
Seven predictors23.2970.692241.3220.909
Comparison of six models; the selected four yield RMSE 0.770 years and the full model 0.909.
Figure 3. LOOCV RMSE for each fixed formula. Bars correspond to the table and do not include repeating variable selection within each partition. Original calculations.

Compared with the selected model, the full model reduces RSS from 23.308 to 23.297, a negligible fitting improvement, but increases PRESS from 29.648 to 41.322. Additional terms can improve the description of the sample while worsening prediction. This does not establish that omitted variables lack historical, health-related, or causal relevance; within this model family and dataset, including them fails to improve the compared criteria.

9. Stepwise selection and partial tests

Forward selection starts with mandatory terms and adds candidates; backward elimination starts with a larger model and removes terms; bidirectional search allows both operations. These are local traversals of a model family. They can stop at different solutions and do not guarantee a global optimum. They should not be confused with Gaussian elimination, which solves linear systems rather than comparing specifications.

In this example, forward and backward AIC searches reach the same candidate as exhaustive search. The trajectories below use the numerical convention of AIC(). Printed step() tables have different absolute values, while preserving the differences and ordering here.

DirectionStepTermsAIC
Backward0pop + income + illiteracy + murder + hsgrad + frost + area121.709
1pop + income + illiteracy + murder + hsgrad + frost119.712
2pop + income + murder + hsgrad + frost117.720
3pop + murder + hsgrad + frost115.733
Forward01174.329
1murder129.285
2murder + hsgrad123.968
3murder + hsgrad + frost117.974
4pop + murder + hsgrad + frost115.733

For a partial test between nested models, let q be the rank difference, RSSR the reduced model’s residual sum of squares, and RSSF that of the larger model, which has pF coefficients. Under the null that the removed block contributes nothing and classical Gaussian assumptions:

F = [(RSSR − RSSF)/q] / [RSSF/(n − pF)]   ∼   Fq, n−pF

A large F indicates greater loss of fit under the restriction. The p-value is the probability, under H₀ and the assumptions, of a statistic at least as extreme; it is not the probability that H₀ is true. drop1(model, test = "F") tests each term against the current model. A factor with several categories may involve multiple coefficients. For one coefficient, F = t² and the F-test and two-sided t-test p-values agree.

Removing terms with large p-values is an exploration rule, not proof of irrelevance. A threshold of α = 0.15 needs justification, and repeated tests do not automatically preserve a global Type I error rate of 0.15. Under AIC or BIC, a search proceeds while the criterion decreases; the aim is not to increase AIC. In step(), k = 2 gives AIC, while k = log(n) gives the BIC-penalized search (R Core Team, n.d.-a, n.d.-b).

10. Coefficients and diagnostics answer different questions

The selected model estimates the following conditional mean, in years. Population is measured in thousands of people; high-school graduation in percentage points; murder per 100,000 residents; and frost in days.

ŷ = 71.02713 + 0.00005014·pop − 0.30015·murder
+ 0.04658·hsgrad − 0.005943·frost
Termβ̂SEtp-value
Intercept71.027130.9528574.542< 0.0001
pop0.00005010.00002511.9960.0520
murder-0.300150.03661-8.199< 0.0001
hsgrad0.046580.014833.1420.0030
frost-0.005940.00242-2.4550.0180

Holding other covariates fixed, a ten-percentage-point difference in graduation is associated with 0.466 years in the fitted mean. This is not an educational policy effect. Population’s p-value is about 0.052 even though AIC retains it; different decision rules can disagree without a logical contradiction.

In diagnostics, leverage describes location in predictor space; an outlying residual describes vertical discrepancy; and influence describes how much the fit changes when an observation is removed. High hii alone does not establish influence. Internally and externally studentized residuals differ as follows:

s² = RSS/(n − p)   ;   ri = ei/[s√(1 − hii)]
s²(i) = [RSS − ei²/(1 − hii)]/(n − p − 1)
ti = ei/[s(i)√(1 − hii)]

With a fixed formula, independent normal errors, and constant variance, ti follows a t distribution with n − p − 1 degrees of freedom. This supports observation diagnostics; it is not the justification for the t-test on β. Cook’s distance combines residual size and leverage to assess influence:

Di = [ei²/(p s²)] · hii/(1 − hii)²
StatehᵢᵢtᵢCook D
Hawaii0.23982.5430.3638
Washington0.1717-1.4900.0896
Maine0.0642-2.2010.0613
South Carolina0.1029-1.6460.0599
Arizona0.1443-1.3080.0568
Residual plot with Hawaii and Maine labelled and Cook’s-distance plot peaking at Hawaii.
Figure 4. Residuals versus fitted values and Cook’s distances for the selected model. The 4/n line is a screening guide, not an automatic exclusion threshold. Original calculations.

Hawaii has the largest Cook’s D (0.364), followed by Washington. This calls for contextual examination and sensitivity analysis, not deleting states to improve the result. Selected-model VIFs range from 1.190 to 1.728, giving no indication of severe collinearity among these four predictors. They do not establish correct specification. Functional form, residual spread, normal quantiles, and geographic dependence also require examination; a set of plots does not certify every assumption.

11. Validate the selection procedure

LOOCV for a formula chosen using all data does not reproduce a procedure that first selects and then predicts. The omitted observation’s response has already affected the initial selection. To evaluate the procedure, exclude each state before selecting: fit all 128 candidates on the remaining 49, choose the minimum AIC or BIC, and predict the held-out state. Aggregate the fifty errors. When internal selection uses validation to tune hyperparameters, an additional inner loop is required; here internal choice uses an information criterion.

ProcedureSum of squared errorsRMSE, years
Formula selected on all data, followed by LOOCV29.6480.770
Exhaustive AIC selection within each partition31.4760.793
Exhaustive BIC selection within each partition36.2550.852

Although AIC and BIC choose the same formula using all fifty states, their procedures have different errors when retrained. The decision path matters. These values describe a leave-state-out experiment within this candidate family; they establish neither universal AIC superiority nor performance in future years.

Stability can also be summarized by counting inclusions across the fifty training sets. Under AIC, population, murder, and graduation appear in 50/50; frost appears in 49/50. Under BIC, population appears in 38/50, murder and graduation in 50/50, and frost in 49/50. Income, illiteracy, and area never appear. These are local sensitivity frequencies under single-unit deletion, not posterior inclusion probabilities or independent population resamples.

Cawley and Talbot (2010) demonstrate that optimizing an estimated criterion can overfit model selection itself. Consequently, imputation, standardization, learned transformations, and term choice should occur within the relevant training set. Choosing between AIC, BIC, and other strategies after inspecting these outer results introduces another selection layer requiring independent evaluation.

12. Bayesian complexity: evidence, BIC, and DIC

A Bayesian model M specifies a likelihood p(y | θ, M) and a prior distribution p(θ | M). Marginal evidence integrates the likelihood with respect to that distribution:

p(y | M) = ∫ p(y | θ, M) p(θ | M) dθ

Evidence averages fit over the allowed parameter space. It can therefore disfavor a flexible model that fits extremely well in a small region while assigning much of its prior mass to regions poorly compatible with the data. The Occam factor describes this effect under particular decompositions or approximations; it should not simply be equated with K log(n). BIC approximates −2 log p(y | M), apart from lower-order terms, under asymptotic and regularity assumptions. Priors matter and may require sensitivity analysis (Bishop, 2006).

DIC uses the posterior distribution. In the formulation of Spiegelhalter et al. (2002), effective complexity pD compares posterior mean deviance with deviance evaluated at the posterior mean:

D(θ) = −2 log p(y | θ) + C
pD = E[D(θ) | y] − D(E[θ | y])
DIC = E[D(θ) | y] + pD

Its relationship to AIC does not make DIC foreign to Bayesian analysis, nor identical to BIC. Interpretation can be problematic with multimodal posteriors, unsuitable parameterizations, or latent structures. Difficulty constructing a universal complexity measure does not imply absence of mathematical definitions or impossibility of formalization in set theory.

The published discussion remains instructive. Brooks questions the posterior summary; Smith examines priors and compatible parameterizations; Plummer challenges parts of the justification; Robert and Titterington discuss data use. Nelder emphasizes reviewing distribution, link, and predictor; Atkinson stresses diagnostics. These are specific, varied objections, not a single refutation of all Bayesian inference.

The stack loss example in that discussion illustrates a broader issue: an observation can appear outlying under one specification and cease to do so after a justified change of family or link. Removing observations is not always the answer. Selecting columns is only one part of selecting structure.

WAIC and LOO cross-validation provide other tools for Bayesian predictive evaluation, each with conditions and diagnostics. Vehtari et al. (2017) study their computation and assessment. This article does not fit a Bayesian model or calculate DIC or WAIC for the states: these concepts are introduced to distinguish problems rather than treat different criteria as one universal scale.

13. Alternatives and extensions

Discrete selection changes a formula abruptly: a coefficient stays or disappears. Regularization controls complexity gradually. Ridge shrinks coefficients with a quadratic penalty; lasso can produce exact zeros with an absolute-value penalty; elastic net combines both. The intercept is usually unpenalized. Predictor scales and the choice of λ matter (Friedman et al., 2010).

β̂λ = arg minβ { RSS(β)/(2n)
+ λ[α Σj≥1|βj| + (1 − α)Σj≥1βj²/2] }

Setting α = 0 gives ridge and α = 1 gives lasso. Choosing λ or α belongs inside training for each outer evaluation. Standardization must also be estimated there. With correlated predictors, inclusion stability can remain limited; penalization neither identifies causes nor fixes measurement problems.

Other extensions include sets of plausible models, predictive averaging, additive models for justified curvature, regional effects, and validation in geographic blocks. Specialized methods exist for post-selection inference, but validity depends on the procedure and target; applying ordinary intervals to the winner is insufficient. For a confirmatory question, prespecification or independent inference data may be preferable.

Once factors, interactions, or spline bases are introduced, selecting variables and selecting columns no longer coincide. A categorical variable can occupy several columns; an interaction may require retaining lower-order terms. Search should operate on blocks and restrictions consistent with the scientific meaning of the terms.

14. A reasoned selection protocol

  1. Define purpose and unit of analysis. Specify whether the target is association, prediction, or a causal effect, and the population or situation of intended generalization.
  2. Audit measurement and timing. Examine units, missingness, errors, predictor availability, and dependence among observations.
  3. Delimit candidates and restrictions. Justify mandatory terms, blocks, interactions, and transformations before evaluating results.
  4. Compare against a simple reference. Use the same observations, a common parameter-counting convention, and compatible criteria.
  5. Validate the entire procedure. Repeat selection and learned transformations inside training; reserve outer evaluation.
  6. Assess diagnostics and stability. Examine residuals, influence, functional form, and sensitivity to reasonable decisions.
  7. Interpret with explicit scope. Distinguish association from mechanism, acknowledge selection uncertainty, and document limitations.

For the fifty states, four predictors provide a favorable fit–prediction compromise within the additive family studied. Agreement among criteria, the nearby three-variable candidate, and different AIC/BIC stability patterns should be communicated together. The scientific result is more than a winning formula: it includes its scope, the decisions that produced it, and the conditions that might require revision.

Rigorous selection preserves relevant relationships, checks consequences, and makes the uncertainty of reduction visible.

Appendix A. Complete code and checks

The following script reproduces the search, tables, estimates, direct PRESS calculation, stepwise paths, VIFs, and evaluation with selection inside each training set. Its core uses only base R. The leaps block is optional and runs only if that package is installed. Variable names are identical in both languages to facilitate comparison.

It was executed in R 4.3.3, and the principal quantities were also checked through an independent QR calculation. Analytic PRESS was compared with explicit refits; stopifnot() checks detect unexpected numerical changes. No random simulation is involved. Article figures were generated from the same quantities; plot(chosen) supplies additional R diagnostics.

# Run blocks in their displayed order. All core calculations use base R.
base <- as.data.frame(datasets::state.x77)
names(base) <- c("pop", "income", "illiteracy", "life",
                 "murder", "hsgrad", "frost", "area")
xvars <- setdiff(names(base), "life")
stopifnot(nrow(base) == 50L, !anyNA(base))
subsets <- c(list(character(0)), unlist(lapply(seq_along(xvars), function(j) {
  combn(xvars, j, simplify = FALSE)
}), recursive = FALSE))
forms <- lapply(subsets, function(v) {
  if (length(v)) reformulate(v, response = "life") else life ~ 1
})
fits <- lapply(forms, lm, data = base)
full <- lm(life ~ ., data = base)
sigma2_full <- deviance(full) / df.residual(full)
score <- function(m, sigma2_ref = sigma2_full) {
  n <- nobs(m)
  p <- m$rank                  # regression coefficients, including intercept
  K <- attr(logLik(m), "df")   # p + residual variance for Gaussian lm
  press <- sum((residuals(m) / (1 - hatvalues(m)))^2)
  c(p = p, K = K, RSS = deviance(m),
    adjR2 = summary(m)$adj.r.squared,
    Cp = deviance(m) / sigma2_ref - n + 2 * p,
    AIC = AIC(m), BIC = BIC(m),
    AICc = AIC(m) + 2 * K * (K + 1) / (n - K - 1),
    PRESS = press, RMSEloo = sqrt(press / n))
}
tab <- as.data.frame(t(vapply(fits, score, numeric(10))))
tab$terms <- vapply(subsets, function(v) {
  if (length(v)) paste(v, collapse = " + ") else "Intercept only"
}, character(1))
stopifnot(nrow(tab) == 128L)
best_id <- which.min(tab$AIC)
chosen <- fits[[best_id]]
tab[order(tab$AIC), c("terms", "p", "adjR2", "Cp", "AIC", "BIC", "AICc", "PRESS")][1:8, ]
# All six criteria choose the same candidate in this particular search.
stopifnot(length(unique(c(best_id, which.min(tab$BIC),
  which.min(tab$AICc), which.min(tab$Cp), which.min(tab$PRESS),
  which.max(tab$adjR2)))) == 1L)
stopifnot(abs(deviance(chosen) - 23.308042796884) < 1e-8,
          abs(score(chosen)["PRESS"] - 29.648232954953) < 1e-8)

# Direct exhaustive search using leaps (optional; core code above needs no package).
if (requireNamespace("leaps", quietly = TRUE)) {
  search <- leaps::regsubsets(life ~ ., data = base,
                             nvmax = 7, nbest = 1, method = "exhaustive")
  summary(search)$which
  summary(search)$adjr2
}

# PRESS and the Alaska deletion example.
income_model <- lm(life ~ income, data = base)
i <- match("Alaska", rownames(base))
without_i <- lm(life ~ income, data = base[-i, , drop = FALSE])
c(observed = base$life[i], fitted = fitted(income_model)[i],
  heldout = predict(without_i, newdata = base[i, , drop = FALSE]),
  deleted = residuals(income_model)[i] / (1 - hatvalues(income_model)[i]))
press_fast <- sum((residuals(chosen) / (1 - hatvalues(chosen)))^2)
press_direct <- sum(vapply(seq_len(nrow(base)), function(i) {
  m <- lm(formula(chosen), data = base[-i, , drop = FALSE])
  (base$life[i] - predict(m, newdata = base[i, , drop = FALSE]))^2
}, numeric(1)))
stopifnot(isTRUE(all.equal(unname(press_fast), unname(press_direct), tolerance = 1e-10)))

# Stepwise candidates: same data, explicit scopes and directions.
lower <- lm(life ~ 1, data = base)
scope <- list(lower = formula(lower), upper = formula(full))
back_aic <- step(full, scope = scope, direction = "backward", trace = 0)
fwd_aic <- step(lower, scope = scope, direction = "forward", trace = 0)
back_bic <- step(full, scope = scope, direction = "backward",
                 k = log(nrow(base)), trace = 0)
drop1(full, test = "F")
add1(lower, scope = formula(full), test = "F")

# Estimates and diagnostics; conventional inference conditions on a fixed formula.
coef(summary(chosen))
confint(chosen)
diag_tab <- data.frame(state = rownames(base),
  leverage = hatvalues(chosen), rstudent = rstudent(chosen),
  Cook = cooks.distance(chosen),
  deleted = residuals(chosen) / (1 - hatvalues(chosen)))
diag_tab[order(-diag_tab$Cook), ][1:5, ]
selected_vars <- attr(terms(chosen), "term.labels")
vif <- vapply(selected_vars, function(v) {
  others <- setdiff(selected_vars, v)
  1 / (1 - summary(lm(reformulate(others, response = v), data = base))$r.squared)
}, numeric(1))
vif
# Optional plotting in an interactive R session:
# par(mfrow = c(2, 2)); plot(chosen); par(mfrow = c(1, 1))

# Outer leave-one-state-out validation of the entire exhaustive AIC/BIC search.
# No held-out response is used to choose the candidate in its training partition.
outer_errors <- matrix(NA_real_, nrow(base), 2,
                       dimnames = list(rownames(base), c("AIC", "BIC")))
inclusions <- matrix(0L, length(xvars), 2,
                     dimnames = list(xvars, c("AIC", "BIC")))
for (i in seq_len(nrow(base))) {
  train <- base[-i, , drop = FALSE]
  local_fits <- lapply(forms, lm, data = train)
  for (criterion in colnames(outer_errors)) {
    criterion_fun <- get(criterion, mode = "function")
    id <- which.min(vapply(local_fits, criterion_fun, numeric(1)))
    winner <- local_fits[[id]]
    outer_errors[i, criterion] <- base$life[i] -
      predict(winner, newdata = base[i, , drop = FALSE])
    v <- attr(terms(winner), "term.labels")
    inclusions[v, criterion] <- inclusions[v, criterion] + 1L
  }
}
colSums(outer_errors^2)
sqrt(colMeans(outer_errors^2))
inclusions
stopifnot(abs(sqrt(mean(outer_errors[, "AIC"]^2)) - 0.793422289702) < 1e-8,
          abs(sqrt(mean(outer_errors[, "BIC"]^2)) - 0.851525323981) < 1e-8)
# Local inclusion frequencies are sensitivity summaries, not posterior probabilities.
cat("All numerical checks passed.\n")
sessionInfo()

Appendix B. Data used

All fifty records are embedded below. English state names preserve correspondence with R row names. Units are specified in section 5.

View all 50 states and eight variables
Statepopincomeilliteracylifemurderhsgradfrostarea
Alabama361536242.169.0515.141.32050708
Alaska36563151.569.3111.366.7152566432
Arizona221245301.870.557.858.115113417
Arkansas211033781.970.6610.139.96551945
California2119851141.171.7110.362.620156361
Colorado254148840.772.066.863.9166103766
Connecticut310053481.172.483.1561394862
Delaware57948090.970.066.254.61031982
Florida827748151.370.6610.752.61154090
Georgia49314091268.5413.940.66058073
Hawaii86849631.973.66.261.906425
Idaho81341190.671.875.359.512682677
Illinois1119751070.970.1410.352.612755748
Indiana531344580.770.887.152.912236097
Iowa286146280.572.562.35914055941
Kansas228046690.672.584.559.911481787
Kentucky338737121.670.110.638.59539650
Louisiana380635452.868.7613.242.21244930
Maine105836940.770.392.754.716130920
Maryland412252990.970.228.552.31019891
Massachusetts581447551.171.833.358.51037826
Michigan911147510.970.6311.152.812556817
Minnesota392146750.672.962.357.616079289
Mississippi234130982.468.0912.5415047296
Missouri476742540.870.699.348.810868995
Montana74643470.670.56559.2155145587
Nebraska154445080.672.62.959.313976483
Nevada59051490.569.0311.565.2188109889
New Hampshire81242810.771.233.357.61749027
New Jersey733352371.170.935.252.51157521
New Mexico114436012.270.329.755.2120121412
New York1807649031.470.5510.952.78247831
North Carolina544138751.869.2111.138.58048798
North Dakota63750870.872.781.450.318669273
Ohio1073545610.870.827.453.212440975
Oklahoma271539831.171.426.451.68268782
Oregon228446600.672.134.2604496184
Pennsylvania118604449170.436.150.212644966
Rhode Island93145581.371.92.446.41271049
South Carolina281636352.367.9611.637.86530225
South Dakota68141670.572.081.753.317275955
Tennessee417338211.770.111141.87041328
Texas1223741882.270.912.247.435262134
Utah120340220.672.94.567.313782096
Vermont47239070.671.645.557.11689267
Virginia498147011.470.089.547.88539780
Washington355948640.671.724.363.53266570
West Virginia179936171.469.486.741.610024070
Wisconsin458944680.772.48354.514954464
Wyoming37645660.670.296.962.917397203

References

Akaike, H. (1974). A new look at the statistical model identification. IEEE Transactions on Automatic Control, 19(6), 716–723. https://doi.org/10.1109/TAC.1974.1100705

Bishop, C. M. (2006). Pattern recognition and machine learning. Springer. https://www.microsoft.com/en-us/research/publication/pattern-recognition-machine-learning/

Cawley, G. C., & Talbot, N. L. C. (2010). On over-fitting in model selection and subsequent selection bias in performance evaluation. Journal of Machine Learning Research, 11, 2079–2107. https://jmlr.org/papers/v11/cawley10a.html

Friedman, J., Hastie, T., & Tibshirani, R. (2010). Regularization paths for generalized linear models via coordinate descent. Journal of Statistical Software, 33(1), 1–22. https://doi.org/10.18637/jss.v033.i01

Hurvich, C. M., & Tsai, C.-L. (1989). Regression and time series model selection in small samples. Biometrika, 76(2), 297–307. https://doi.org/10.1093/biomet/76.2.297

Kutner, M. H., Nachtsheim, C. J., Neter, J., & Li, W. (2005). Applied linear statistical models (5th ed.). McGraw-Hill/Irwin.

Lumley, T. (n.d.). leaps: Regression subset selection [Package manual]. https://cran.r-universe.dev/leaps/doc/manual.html

Mallows, C. L. (1973). Some comments on Cp. Technometrics, 15(4), 661–675. https://doi.org/10.1080/00401706.1973.10489103

Marx, K. (1999). Capital (Vol. III, Chap. 48, “The trinity formula”). Marxists Internet Archive. (Original work published 1894). https://www.marxists.org/archive/marx/works/1894-c3/ch48.htm

R Core Team. (n.d.-a). Add or drop all possible single terms to a model [Documentation]. https://stat.ethz.ch/R-manual/R-devel/library/stats/html/add1.html

R Core Team. (n.d.-b). Choose a model by AIC in a stepwise algorithm [Documentation]. https://stat.ethz.ch/R-manual/R-devel/library/stats/html/step.html

R Core Team. (n.d.-c). Extract AIC from a fitted model [Documentation]. https://stat.ethz.ch/R-manual/R-devel/library/stats/html/extractAIC.html

R Core Team. (n.d.-d). Regression deletion diagnostics [Documentation]. https://stat.ethz.ch/R-manual/R-devel/library/stats/html/influence.measures.html

R Core Team. (n.d.-e). US state facts and figures [Dataset documentation]. https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/state.html

Schwarz, G. (1978). Estimating the dimension of a model. The Annals of Statistics, 6(2), 461–464. https://doi.org/10.1214/aos/1176344136

Spiegelhalter, D. J., Best, N. G., Carlin, B. P., & van der Linde, A. (2002). Bayesian measures of model complexity and fit. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 64(4), 583–639. https://doi.org/10.1111/1467-9868.00353

Vehtari, A., Gelman, A., & Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27, 1413–1432. https://doi.org/10.1007/s11222-016-9696-4


Discover more from Marxist Philosophy of Science

Subscribe to get the latest posts sent to your email.

Follow the blogSeguí al blog

Comments

Leave a Comment/Deja un Comentario