Synthetic Learner (SL)#

When to Use This Estimator#

Every estimator in this library predicts what would have happened to one treated unit had the treatment not arrived, and each does it by committing to an assumption. VanillaSC assumes a convex combination of control units tracks the treated one. FDID assumes parallel trends on a selected subset. GSYNTH assumes a low-dimensional factor structure. If the assumption holds the answer is good, and if it does not the answer is wrong without saying so.

SL, from Viviano and Bradic [VB2023], declines the commitment. It keeps a library of predictors, called experts, fits each on part of the pre-treatment window, and then scores them against the part they did not see. The prediction is a weighted combination, with weight going to whichever experts forecast the held-out stretch well. Nothing in the procedure requires any single expert to be correctly specified.

The default library is the authors’ own four: a cross-validated lasso of the treated outcome on the donors, a one-factor model of the donor pool loaded onto the treated unit, a random forest that also reads any covariates, and difference-in-differences over the whole donor pool. The last of these is the conventional estimate FDID reports beside its forward one, and SL calls that fit instead of keeping a second copy of the formula.

The forest is the only member with an information set of its own, so covariates reach it and nothing else. covariates names panel columns and gives the forest every unit’s path for each; external_covariates takes a frame of series for units that are not in the panel at all, aligned by period label. The second exists because the first cannot express the authors’ own application, which hands the forest employment for 50 states against a donor pool of six.

The inference is where SL differs most from its neighbours. It supplies a hypothesis test of the no-effect null, with a critical value from a moving-block bootstrap and a size guarantee that does not lean on the experts being right. It does not supply a standard error or a confidence interval, and neither does the paper. See Inference and Diagnostics.

Reach for it when

  • one unit is treated and the rest are not;

  • you can name several plausible ways to build the counterfactual and cannot defend a choice among them;

  • what you want is a defensible test of whether anything happened, more than a precise interval around how much;

  • the pre-treatment window is long enough to split in two and still leave both halves usable. Roughly twenty periods on each side is the regime the paper works in; much less and neither the experts nor the weights have anything to learn from.

Reach for something else when the pre-window is short, since the split costs half of it, or when you need an interval, not a test.

Notation#

Let \(i = 1, \dots, N\) index units and \(t = 1, \dots, T\) index periods. Unit 1 is treated from \(T_0 + 1\) onward and units \(2, \dots, N\) never are. Write \(y_{t}\) for the treated unit’s outcome, \(\mathbf{x}_t = (y_{2t}, \dots, y_{Nt})'\) for the control outcomes, and \(y^0_t\) for the treated unit’s untreated outcome, observed up to \(T_0\) and to be predicted after.

The pre-treatment window splits at \(T_1 < T_0\). Periods \(1, \dots, T_1\) are the training window \(\mathcal{T}\); periods \(T_1 + 1, \dots, T_0\) are the weighting window \(\mathcal{W}\).

An expert is a map \(k \mapsto \hat{m}_k\), fit on \(\mathcal{T}\) alone, that returns a predicted path \(\hat{m}_k(t)\) for every \(t\). With \(K\) experts, collect them as \(\hat{\mathbf{m}}(t) \in \mathbb{R}^K\). The ensemble carries weights \(\mathbf{w}\) on the simplex, and its prediction is \(\hat{y}^0_t = \mathbf{w}' \hat{\mathbf{m}}(t)\).

Assumptions#

  1. One treated unit, and the controls are never treated.

    Remark. SL reads the treated unit and the control pool from the panel through dataprep(). A control contaminated by the treatment enters the experts’ training data as though it were clean, and every expert inherits the contamination, so the ensemble cannot detect it.

  2. The pre-treatment window splits into two usable halves, and no expert sees the weighting window while fitting.

    Remark. This is the whole basis of the weighting. Equation 12 scores an expert by its loss on \(\mathcal{W}\), which is informative only if that loss is out of sample. An expert that chose a hyperparameter by cross-validating over the entire pre-window has already seen \(\mathcal{W}\), and its score flatters it. Every hyperparameter in this implementation is pinned by the configuration or derived from \(\mathcal{T}\) alone.

  3. No expert has to be correctly specified.

    Remark. This is what the method buys. The regret bound of Lemma C.1 measures the ensemble against the best single expert in the library, not against the truth, so the guarantee survives every expert being misspecified. What the bound does not promise is that the best expert is any good. If the library spans nothing close to the counterfactual, SL returns a confident weighted average of wrong answers.

  4. Under the null of no effect, the periods outside the training window are exchangeable in blocks.

    Remark. Algorithm 2 builds the null distribution by resampling blocks of those periods, so this is the assumption the size guarantee of Theorem 3.1 rests on. A block length of 3, the paper’s choice, absorbs serial correlation up to roughly that horizon and no further. A panel with a trend that survives the split violates it, and the test will over-reject.

  5. The effect is constant enough over the measured window that its mean is worth reporting.

    Remark. Equation 10’s estimate is an average over the post window, so an effect that reverses sign inside it averages toward zero while the test statistic, a sum of squares, still fires. Divergence between a small att and a significant p_value is that case, and post_skip is how to measure away from the switch-on.

Inference and Diagnostics#

The test statistic of Equations 7 and 8 is

\[S = \frac{1}{\sqrt{|\mathcal{P}|}} \sum_{t \in \mathcal{P}} \bigl(\hat{y}^0_t - y_t\bigr)^2 ,\]

over the measured post window \(\mathcal{P}\). Algorithm 2 resamples blocks of the periods outside the training window, refits the weights inside each replicate, and recomputes \(S\); the upper quantiles of those draws are the critical values, and the share of draws at or above the observed \(S\) is the p-value.

\(S\) is non-negative and quadratic, so its null quantiles are critical values and not interval endpoints. The result therefore reports inference.p_value and fit.critical_values, and leaves effects.att_std_err, inference.standard_error and the interval fields empty. That is not an omission in the implementation: the method has no standard error. An interval for the effect would come from inverting this test over a grid of candidate constant effects, which is separate work and is not offered here.

Three diagnostics on the result are not in the paper, and each answers a question the point estimate cannot.

effective_k is the perplexity of the weights, between 1 and \(K\). At 1 the weighting picked a single expert; at \(K\) it is the simple average. The learning rate decides where a fit lands, and the paper’s own \(\eta = 1 / (\sqrt{T}\,\widehat{\operatorname{Var}}(y))\) lands near \(K\): on its own application effective_k is 3.69 of 4, and concentrating on the best expert there needs \(\eta\) between 17 and 60 times larger. An SL fit reported without this number does not say whether the ensembling did anything.

error_participation_ratio is the effective number of independent directions in the experts’ errors on \(\mathcal{W}\), also between 1 and \(K\). Averaging cancels error when the members err independently. Measured on two panels this ratio is 1.19 and 1.03 of 4, so they do not: the members miss in the same direction at the same times, and an equal-weight ensemble of four donor-projection experts comes out at 1.17 and 2.92 times the best single member’s in-window error. A ratio near 1 says the library is one expert wearing several hats, and adding more of the same kind will not help.

degenerate_experts names a member that is constant on \(\mathcal{W}\), so contributes only a level, or one fitting an order of magnitude worse than the best while still carrying weight. The second case is real: on Prop 99 an l2 expert fits 51 times worse than the best and keeps 14 percent of the weight, because \(\eta\) is too small to discriminate, and that is what drags the ensemble’s estimate away from every member that fits.

dropped_experts names a member that could not be built at all, with the reason. A single-donor panel drops the factor expert, for instance. A dropped expert changes the library and therefore the estimate, so it is recorded, not silently absent.

Example#

import numpy as np
import pandas as pd
from mlsynth import SL

rng = np.random.default_rng(0)
T, T0, N = 60, 40, 7
f = rng.standard_normal((T, 2))
lam = rng.standard_normal((N, 2))
Y = 10.0 + f @ lam.T + 0.5 * rng.standard_normal((T, N))
Y[T0:, 0] -= 3.0                       # the effect to be recovered

units = np.repeat(np.arange(N), T)
times = np.tile(np.arange(T), N)
panel = pd.DataFrame({
    "unit": units, "time": times, "y": Y.T.ravel(),
    "D": ((units == 0) & (times >= T0)).astype(int),
})

res = SL({
    "df": panel, "outcome": "y", "treat": "D",
    "unitid": "unit", "time": "time",
    "n_boot": 2000, "display_graphs": False,
}).fit()

print(res.effects.att)                       # about -3
print(res.fit.p_value, res.fit.critical_values[0.05])
print(res.fit.effective_k, res.fit.error_participation_ratio)
print(res.fit.weights)
print(res.fit.degenerate_experts or "library healthy")

The plotter returns its figure and does not display it:

from mlsynth.utils.sl_helpers import plot_sl

fig = plot_sl(res)
fig.savefig("sl.png", dpi=150)

Verification#

Two pinned cases, and the full account is on SL: Viviano and Bradic (2023).

benchmarks/cases/sl.py is Path B: the size and power of the paper’s own test on the paper’s own Monte Carlo design.

benchmarks/cases/sl_table4.py is Path A: their published Table 4 on the TennCare panel, reproduced through SL(...).fit() with their design passed as external_covariates and their learning rate as eta. The effect agrees to 0.03 percent at the worst of four horizons, the statistic to 0.56 percent, and their non-rejection reproduces.

benchmarks/cases/sl_tennessee.py is a cross-validation against an R implementation of the authors’ own expert library on their empirical panel. On the three experts that are algorithmically determined the two implementations agree to 2.3e-12, 4.9e-11 and 7.0e-07 path by path, and the effect to 3.9e-06 at every horizon. That last figure is a floor set by the lasso solution’s non-uniqueness at the penalty their grid selects, not a target.

Two corrections to the authors’ replication code are part of what is validated: their bootstrap refits the ensemble with a different learning rate than the point estimate, and their lasso expert’s penalty is drawn from the random number generator instead of being computed from the data. Two defects in this port are also pinned there, both found by the cross-validation and by nothing else – the paper’s two penalty grids, which it did not carry, and glmnet’s default standardization of the design, which it did not do.

Core API#

class mlsynth.SL(config: SLConfig | dict)#

Synthetic learner estimator.

Parameters:

config (SLConfig or dict) – Validated configuration. Beyond the common fields, SL reads experts (the library), covariates (read by the forest expert), eta and train_periods (the weighting), post_skip (which post window to measure), n_boot / block / seed (the bootstrap) and alpha.

Examples

>>> from mlsynth import SL
>>> res = SL({
...     "df": panel, "outcome": "y", "treat": "D",
...     "unitid": "unit", "time": "time",
... }).fit()
>>> res.fit.effective_k
3.88

References

Viviano, D., & Bradic, J. (2023). Synthetic learner: model evaluation with limited overlap. Journal of Econometrics, 234(2), 691-713.

fit() → SLResults#

Run SL and return the standardized result.

Returns:

SLResults

Raises:
  • MlsynthDataError – If the panel is unbalanced, has no donors, has fewer than two pre-treatment periods, or names a covariate it does not carry.

  • MlsynthConfigError – If the split leaves no weighting window, or post_skip consumes the whole post window.

class mlsynth.config_models.SLConfig(*, df: ~pandas.DataFrame, outcome: str, treat: str, unitid: str, time: str, display_graphs: bool = True, save: bool | str = False, counterfactual_color: ~typing.List[str] = <factory>, treated_color: str = 'black', plot: ~mlsynth.config_models.PlotConfig = <factory>, experts: ~typing.List[~typing.Literal['lasso', 'factor', 'forest', 'did']] = <factory>, covariates: ~typing.List[str] = <factory>, external_covariates: ~pandas.DataFrame | None = None, train_periods: ~typing.Annotated[int | None, ~annotated_types.Gt(gt=0)] = None, eta: ~typing.Annotated[float | None, ~annotated_types.Ge(ge=0.0)] = None, post_skip: ~typing.Annotated[int, ~annotated_types.Ge(ge=0)] = 0, n_boot: ~typing.Annotated[int, ~annotated_types.Gt(gt=0)] = 10000, block: ~typing.Annotated[int, ~annotated_types.Gt(gt=0)] = 3, alpha: ~typing.Annotated[float, ~annotated_types.Gt(gt=0.0), ~annotated_types.Lt(lt=1.0)] = 0.05, seed: int = 0, lasso_folds: ~typing.Annotated[int, ~annotated_types.Ge(ge=2)] = 5, factor_rank: ~typing.Annotated[int, ~annotated_types.Ge(ge=1)] = 1, forest_trees: ~typing.Annotated[int, ~annotated_types.Ge(ge=1)] = 500, forest_max_leaf_nodes: ~typing.Annotated[int, ~annotated_types.Ge(ge=2)] = 20)#

Configuration for the synthetic learner (SL).

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid'}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mlsynth.utils.sl_helpers.structures.SLResults(*, effects: ~mlsynth.config_models.EffectsResults | None = None, fit_diagnostics: ~mlsynth.config_models.FitDiagnosticsResults | None = None, time_series: ~mlsynth.config_models.TimeSeriesResults | None = None, weights: ~mlsynth.config_models.WeightsResults | None = None, inference: ~mlsynth.config_models.InferenceResults | None = None, method_details: ~mlsynth.config_models.MethodDetailsResults | None = None, sub_method_results: ~typing.Dict[str, ~typing.Any] | None = None, additional_outputs: ~typing.Dict[str, ~typing.Any] | None = None, raw_results: ~typing.Dict[str, ~typing.Any] | None = None, execution_summary: ~typing.Dict[str, ~typing.Any] | None = None, plot_config: ~mlsynth.config_models.PlotConfig | None = None, inputs: ~mlsynth.utils.sl_helpers.structures.SLInputs, fit: ~mlsynth.utils.sl_helpers.structures.SLFit, metadata: ~typing.Dict[str, ~typing.Any] = <factory>)#

Top-level container returned by mlsynth.SL.fit().

An EffectResult. Two things about the standardized sub-models are deliberate.

effects.att_std_err and inference.standard_error are None. The method has no standard error: Theorem 3.1 controls the size of a test, and the statistic it controls is a non-negative quadratic whose null quantiles are critical values. Populating a standard error field from them would be an invention. inference.p_value and the critical values on fit are the inference. With interval="conformal" the interval fields carry a conformal ATT interval and method names it.

weights.donor_weights holds the expert weights. The units being combined here are forecasters, not donors, and summary_stats records that along with effective_k.

Parameters:
  • inputs (SLInputs) – The preprocessed panel.

  • fit (SLFit) – The ensemble, the test, and the library diagnostics.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'frozen': True, 'json_encoders': {<class 'numpy.ndarray'>: <function BaseEstimatorResults.Config.<lambda>>}}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class mlsynth.utils.sl_helpers.structures.SLFit(experts: ~typing.Tuple[str, ...], predictions: ~numpy.ndarray, weights: ~typing.Dict[str, float], eta: float, effective_k: float, counterfactual: ~numpy.ndarray, gap: ~numpy.ndarray, att: float, bias: float, test_statistic: float, critical_values: ~typing.Dict[float, float], p_value: float, expert_ssr: ~typing.Dict[str, float], error_correlation: ~numpy.ndarray, error_participation_ratio: float, degenerate_experts: ~typing.Dict[str, str], dropped_experts: ~typing.Dict[str, str], train_periods: int, weight_periods: int, post_periods: int, details: ~typing.Dict[str, ~typing.Dict[str, ~typing.Any]] = <factory>, metadata: ~typing.Dict[str, ~typing.Any] = <factory>)#

One SL fit: the ensemble, the test, and what the library was doing.

Parameters:
  • experts (tuple of str) – The members that fit, in the column order of predictions.

  • predictions (np.ndarray) – Each expert’s counterfactual path, shape (T, K).

  • weights (dict) – Equation 12’s weights by expert name. A simplex point, not regression coefficients.

  • eta (float) – The learning rate actually used, resolved from the config.

  • effective_k (float) – Perplexity of the weights, in [1, K]. At 1 the weighting picked one expert; at K it is the simple average. The paper’s own eta puts this at 3.69 of 4, so its ensemble averages.

  • counterfactual (np.ndarray) – predictions @ weights, shape (T,).

  • gap (np.ndarray) – Observed minus counterfactual, shape (T,).

  • att (float) – Equation 10’s bias-adjusted average effect on the measured post window.

  • bias (float) – The in-sample gap the adjustment removes.

  • test_statistic (float) – Equations 7-8 on the measured post window.

  • critical_values (dict) – Level to the null distribution’s upper quantile, from Algorithm 2. Critical values for a non-negative quadratic, not interval endpoints.

  • p_value (float) – Upper-tail bootstrap p-value against the no-effect null.

  • expert_ssr (dict) – In-window squared loss per expert, the input to Equation 12.

  • error_correlation (np.ndarray) – Correlation between the experts’ weighting-window errors, (K, K).

  • error_participation_ratio (float) – Effective number of independent error directions, in [1, K]. Near 1 the members err alike and averaging cannot cancel anything.

  • degenerate_experts (dict) – Member to the reason it is not doing the job the library assumes.

  • dropped_experts (dict) – Member to the reason it could not be built at all.

  • train_periods, weight_periods, post_periods (int) – Algorithm 1’s split, and the measured post window’s length.

  • details (dict) – Per-expert provenance, including the lasso’s chosen penalty.

mlsynth.utils.sl_helpers.weights.exponential_weights(ssr: ndarray, eta: float) → ndarray#

Equation 12: w_k proportional to exp(-eta * cumulative loss_k).

Parameters:
  • ssr (np.ndarray) – Cumulative squared loss per expert on the weighting window, shape (K,).

  • eta (float) – Learning rate. 0 gives the simple average; larger concentrates.

Returns:

np.ndarray – Weights on the simplex, shape (K,).

mlsynth.utils.sl_helpers.weights.effective_k(weights: ndarray) → float#

Perplexity of the weights: 1 when one expert carries everything, K when the weighting is the simple average.

This is the number that says whether the exponential weighting selected or averaged, which the paper does not report and which decides how much the ensembling bought.

mlsynth.utils.sl_helpers.experts.build_experts(Yco: ndarray, y: ndarray, train: slice, names: Sequence[str] = ('lasso', 'factor', 'forest', 'did'), *, covariates: ndarray | None = None, seed: int = 0, lasso_folds: int = 5, factor_rank: int = 1, forest_trees: int = 500, forest_max_leaf_nodes: int = 20) → ExpertLibrary#

Fit each requested expert on train and predict over every period.

Parameters:
  • Yco (np.ndarray) – Donor outcomes, shape (T, N).

  • y (np.ndarray) – Treated outcome, shape (T,).

  • train (slice) – The expert-training split of Algorithm 1. No expert sees anything outside it while fitting, which is what makes the weighting window out of sample.

  • names (sequence of str) – Which experts to build, in the order they should occupy columns.

  • covariates (np.ndarray, optional) – Time-varying covariates, shape (T, m), read by forest only.

  • seed (int) – Seed for the forest. The other three are deterministic.

  • lasso_folds, factor_rank, forest_trees, forest_max_leaf_nodes – Pinned hyperparameters. None of them is drawn.

Returns:

ExpertLibrary

Raises:

MlsynthDataError – If no requested expert could be built.

mlsynth.utils.sl_helpers.inference.block_bootstrap_test(predictions: ndarray, y: ndarray, train: slice, weight: ndarray, post: ndarray, *, eta: float, n_boot: int, block: int, seed: int = 0, levels: Sequence[float] = (0.01, 0.05, 0.1, 0.2)) → BootstrapResult#

Algorithm 2: the statistic’s null distribution by resampling blocks.

The resampling pool is every period outside the expert-training split, which is the weighting window plus the post window – exchangeable under the null of no effect, which is the null being tested. Each replicate resamples that pool in blocks, refits the ensemble weights on the first len(weight) draws, and evaluates the statistic on the rest.

Parameters:
  • predictions (np.ndarray) – Expert predictions, shape (T, K). Held fixed across replicates: the bootstrap resamples periods and refits the weights, not the experts.

  • y (np.ndarray) – Treated outcome, shape (T,).

  • train (slice) – The expert-training split, excluded from the pool.

  • weight, post (np.ndarray) – Period indices for the weighting and evaluation windows.

  • eta (float) – The same learning rate the point estimate used.

  • n_boot (int) – Replicates.

  • block (int) – Block length; clamped to the pool size.

  • seed (int) – Seed for the resampling.

  • levels (sequence of float) – Levels to report critical values at.

Returns:

BootstrapResult

mlsynth.utils.sl_helpers.diagnostics.participation_ratio(errors: ndarray) → float#

Effective number of independent error directions, in [1, K].

(sum s_i^2)^2 / sum s_i^4 on the singular values. One means every expert errs in the same direction, so averaging cannot cancel anything; K means the errors are orthogonal and averaging is worth the full variance reduction.

The matrix is not centred. Its column means are the experts’ biases, and correlated bias is exactly what this is meant to detect.

mlsynth.utils.sl_helpers.plotter.plot_sl(results: Any, *, outcome: str = 'Outcome', time: str = 'Time', treated_color: str = 'black', counterfactual_color: str | List[str] = '#3b78e7', title: str | None = None)#

Observed against the ensemble counterfactual, with the gap beneath.

Parameters:
  • results (SLResults) – A fitted result.

  • outcome, time (str) – Axis labels.

  • treated_color, counterfactual_color (str or list of str) – Line colours. A list is accepted because BaseEstimatorConfig types the counterfactual colour that way.

  • title (str, optional) – Overrides the default, which reports the library size, the weights’ perplexity and the test’s p-value.

Returns:

matplotlib.figure.Figure

References#

[VB2023]

Viviano, D., & Bradic, J. (2023). Synthetic learner: model evaluation with limited overlap. Journal of Econometrics, 234(2), 691-713. https://doi.org/10.1016/j.jeconom.2022.07.005