Skip to content

MAR & time-gap imputation improvements, 4.5x faster imputation pipeline#47

Merged
CyrilJl merged 5 commits into
mainfrom
feat/imputation-mar-time-gaps
Jul 3, 2026
Merged

MAR & time-gap imputation improvements, 4.5x faster imputation pipeline#47
CyrilJl merged 5 commits into
mainfrom
feat/imputation-mar-time-gaps

Conversation

@CyrilJl

@CyrilJl CyrilJl commented Jul 3, 2026

Copy link
Copy Markdown
Owner

Summary

This PR improves TimeSeriesImputer for missing-at-random values and contiguous timestamp gaps, then makes the whole imputation pipeline substantially faster and lighter in memory — with imputation results unchanged (verified elementwise, differences at float32 rounding level only).

Imputation improvements (cf66f9e)

  • TimeSeriesImputer can now infer a regular DatetimeIndex frequency, reinsert missing timestamp rows inside the observed range, and impute them.
  • Optional deterministic calendar/trend features (add_time_features=True) that stay fully observed through contiguous gaps, so blocks of missing timestamps can be filled even when all lag features are NaN.
  • Training subsets that end up identical across missingness patterns are fitted once and reused.

Performance (b12ff96, df2e12c)

  • Gram-based ridge fast path: with the default FastRidge regressor, per-pattern models are solved from an augmented [X, y, 1] Gram matrix accumulated once per column over the globally complete rows plus a small per-pattern correction, instead of materializing and refitting a large row subset for every missingness pattern (~500 patterns/column on the benchmark). Custom regressors and categorical targets keep the exact estimator.fit path.
  • Cheaper pattern handling: per-pattern complete training rows are found from a CSC layout of NaN positions with epoch-stamped scratch buffers — cost scales with the NaN count in excluded columns instead of n_rows × n_usable_cols.
  • Fixed-cost reductions: fused masked normalization stats (replacing nanmean/nanstd full-matrix copies, applied in place), feature-selection scoring rewritten from masked sums (same math, no pre-impute copy), lag/lead features built in one preallocated numpy matrix instead of df.shift + pd.concat, and output sliced before the DataFrame wrap so pandas CoW does not copy the full feature matrix.
  • Memory fix: nan_positions over-allocated two m·n uint32 buffers kept alive by the returned slices; NaN indexing now allocates exactly what it needs. Dead helpers and an unused NaN-position pipeline (computed per call, never read) were removed.

Before / after

Reference benchmark: perf/timeseries_imputer_benchmark.py — 30,000 rows × 250 series (15-min frequency), 2% MAR + 8 series with 3,000-row outage blocks, 3 target series, n_nearest_features=35, lags=(1, 2, 3, -1, -2, -3). "Before" is this branch prior to the optimization commits; same machine, same environment.

Metric Before After Change
Wall time (steady-state run) 5.88 s 1.32 s 4.5× faster
Time per imputed column ~0.87 s ~0.16 s 5.4× faster
Peak RAM (peak working set) 1,746 MB 1,181 MB −32%
RSS retained after the call 512 MB 317 MB −38%
Imputation MAE on masked cells 0.31700122 0.31700116 unchanged

The all-columns DataFrame path benefits as well (scripts/multivariate_benchmark.py, same environment): Diabetes MAR 10% drops from 1.20 s to 0.39 s with identical quality metrics on every dataset/pattern combination.

Quality verification

  • Elementwise comparison of imputed values before/after on three scenarios (time series MAR + blocks, multivariate full-features, multivariate with n_nearest_features + min_samples_train): max relative difference ~1e-4, MAE identical to 7 decimals.
  • scripts/multivariate_benchmark.py run on baseline and optimized code in the same environment produces identical metrics (RMSE/R²/accuracy) on all datasets.
  • New regression tests pin the fast paths to reference implementations: complete_rows_excluding vs a plain-numpy oracle, the Gram path vs a materialized FastRidge, and the rewritten scoring vs the pre-impute formulation.

Testing

  • pytest — 39 passed.
  • ruff check / ruff format --check — clean.
  • Benchmarks and profiles: perf/timeseries_imputer_benchmark.py, perf/timeseries_imputer_profile.py, scripts/multivariate_benchmark.py.

CyrilJl and others added 5 commits July 3, 2026 23:24
…m full-matrix overheads

Speeds up the reference TimeSeriesImputer benchmark (30k rows x 250
series, 3 targets, n_nearest_features=35) from 5.9s to 1.4s and cuts
peak RAM from ~1.75GB to ~1.18GB, with imputation results unchanged up
to float32 rounding.

- Solve default FastRidge fits from an augmented [X, y, 1] Gram matrix
  accumulated once per column over globally complete rows plus a small
  per-pattern correction, instead of materializing and refitting a large
  row subset for every missingness pattern. Custom regressors and
  categorical targets keep the materialized estimator.fit path.
- Find per-pattern complete training rows from a CSC layout of NaN
  positions with epoch-stamped scratch buffers, scaling with the NaN
  count in excluded columns instead of n_rows x n_usable_cols.
- Extract NaN positions with exact-size allocations; nan_positions
  over-allocated two m*n uint32 buffers kept alive by returned slices.
- Compute normalization stats with a fused two-pass masked computation
  and apply full-width normalization in place, replacing nanmean/nanstd
  full-matrix copies.
- Rewrite feature-selection scoring from masked sums, reusing the shared
  NaN mask and avoiding the preimpute copy and standardization temps.
- Build TimeSeriesImputer lag/lead and calendar features in one
  preallocated numpy matrix instead of df.shift + pd.concat, and slice
  the imputed array before wrapping so pandas CoW does not copy the full
  feature matrix.
- Add regression tests pinning complete_rows_excluding, the Gram fast
  path, and the rewritten scoring to their reference implementations.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Drop the global iy/ix NaN positions computed in
  MultivariateImputer.__call__ and threaded through _impute_col: the
  method only ever used positions recomputed from the per-column
  training subset, so this also removes a full-matrix scan per call.
  nan_positions_from_mask goes with it as its only caller.
- Delete nan_positions_subset, which had no callers.
- Delete numba_apply_permutation and the apply_permutation wrapper in
  _optimask; both call sites use the in-place variant directly.
- Move complete_rows_for_cols and preimpute out of the library into
  tests/test_multivariate.py as plain-numpy reference oracles for the
  complete_rows_excluding and scoring equivalence tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Fix TimeSeriesImputer.__call__ docstring: the index frequency is now
  inferred and missing timestamps reinserted, not required upfront.
- Rewrite the algorithm page around per-pattern models: complete-case
  selection first, optimask as fallback, and Gram-based solving for the
  default ridge regressor.
- Update the README "How It Works" paragraph and the AGENTS.md
  algorithm overview accordingly.
- Add a v0.2.4 changelog entry for the MAR/time-gap features and the
  performance work.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@CyrilJl CyrilJl merged commit 02235f3 into main Jul 3, 2026
3 checks passed
@CyrilJl CyrilJl deleted the feat/imputation-mar-time-gaps branch July 3, 2026 22:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant