MAR & time-gap imputation improvements, 4.5x faster imputation pipeline#47
Merged
Conversation
…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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR improves
TimeSeriesImputerfor 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)TimeSeriesImputercan now infer a regularDatetimeIndexfrequency, reinsert missing timestamp rows inside the observed range, and impute them.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.Performance (
b12ff96,df2e12c)FastRidgeregressor, 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 exactestimator.fitpath.n_rows × n_usable_cols.nanmean/nanstdfull-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 ofdf.shift+pd.concat, and output sliced before the DataFrame wrap so pandas CoW does not copy the full feature matrix.nan_positionsover-allocated twom·nuint32 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.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
n_nearest_features+min_samples_train): max relative difference ~1e-4, MAE identical to 7 decimals.scripts/multivariate_benchmark.pyrun on baseline and optimized code in the same environment produces identical metrics (RMSE/R²/accuracy) on all datasets.complete_rows_excludingvs a plain-numpy oracle, the Gram path vs a materializedFastRidge, and the rewritten scoring vs the pre-impute formulation.Testing
pytest— 39 passed.ruff check/ruff format --check— clean.perf/timeseries_imputer_benchmark.py,perf/timeseries_imputer_profile.py,scripts/multivariate_benchmark.py.