Repository navigation
policyscope 0.3.0: переработка оценки политик, отчётов и проверки - #44
Merged
Merged
Conversation
Snapshot of the uncommitted 0.2.0 revision (see CHANGELOG.md) so that the 0.3.0 rewrite can be reviewed as a separate diff. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ference Ground-up rewrite of the package around one entry point (Evaluator / evaluate / compare) and one formula path (estimators.contributions). Correctness fixes over 0.2: - estimated propensities are always out-of-fold and floored per action; DR error on epsilon-greedy logs drops from RMSE 7.7 to ~0.03 - inference="auto" switches to a nuisance-refitting cluster bootstrap when propensities are estimated (the influence CI ignores their estimation error) - policies are probability tables keyed by action labels, evaluated once on the full logs: reordered columns can no longer silently mismatch actions - NaN rewards/features fail loudly; categorical features are one-hot encoded; outcome-like columns (another metric) are excluded from auto features - cross-fitting folds inside bootstrap replicas are grouped by source row - CR1 cluster-robust SE with t(G-1) critical values New: triangulation checks (DR-IPS for propensities, DR-DM for the outcome model), propensity-column validity and exploration checks, Romano-Wolf multiplicity adjustment, baseline policies, candidate leaderboard, a synthetic offer simulator with an analytic oracle, statistical test suite and a validation script. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- README rebuilt around the customer journey: try it in a minute, prepare logs, describe policy B, evaluate, read the report, compare candidates, when not to trust the estimate, how correctness is verified - docs/methodology.md: estimators, cross-fitting, propensity floor, CR1 and bootstrap intervals, Romano-Wolf, triangulation checks, assumptions, package layout and invariants (replaces AGENTS.md and the old docs) - docs/validation.md: fresh simulation results; the trust verdict separates no-overlap runs (RMSE 13 if ignored) from usable ones (RMSE 0.05, coverage 0.96) - executed tutorial notebook: model-based candidate trained on early logs and evaluated on later ones, leaderboard, production baseline, missing propensities, repeat visits, cases where the estimate must not be trusted - CI runs lint, fast and statistical tests, validation and the tutorial - bootstrap fails loudly when no replicate can be computed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The gaussian multiplier bootstrap with fixed cluster sums is exactly N(0, R); drawing J-dimensional normals instead of n_draws x G multipliers cuts evaluating an extra candidate on 50k rows from 3.5 s to 0.3 s. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…study An estimator study (literature, simulations, adversarial verification) showed that the 0.3 ban on DM was argued wrongly: its 0.77 coverage came from a variance formula that ignored outcome-model estimation, not from bias. DM is 1.3-2.8x more precise than DR when the outcome model is right, but its bias is invisible in the logs, so DR stays the default. - Outcome model: no clipping of continuous predictions; non-negative rewards with zeros use a two-part model (logistic x Gamma log-link) with the positive part capped at the observed maximum; per-metric outcome models. DM bias on revenue drops from +6.5 to +0.5 (A3->B5) and from -3.7 to -0.4 (softmax logging); DR stays unbiased. - DM row reports a contrast DM(B) - mean(mu(x_i, a_i)). - estimator="dm" is allowed as an explicit choice: bootstrap CI only, built-in outcome model only, model_based_estimate caution, blocking DR-DM check computed on the reported Delta. Validation: coverage 0.97-1.00. - Guards: non-finite outcome predictions and estimates, unknown metrics in the outcome_model dict. - Finding texts no longer recommend SNDR, blame logged propensities for heavy-tail DR-IPS gaps, or call DR doubly robust with estimated propensities. - docs/estimators.md explains every estimator decision with evidence and verification status; validation, methodology, README, tutorial updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Decisions with a NaN interval bound are now 'inconclusive' and flagged, never 'no difference'; end-to-end regression test with an outlying income. - outcome_model accepts any Mapping; unknown metric keys are rejected in fit_nuisance too. - Tests: the DR-DM check equals the difference of the reported Delta rows (with and without a baseline) and is exactly zero for B = A. - Docs: with estimated propensities DR is biased under any outcome model (A8->B6: -8.5 two-part vs +5.3 clipped Ridge); new validation scenario estimated_pair2 shows it (-13.8 +- 2.7, coverage 0.87) and is reported but not enforced; support-violation flagging ~85% at n=3000, ~60% at 12-48k; corrected the contrast's bias-reduction claim; efficiency caveat for DM. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rite The 14 commits on main polish the 0.1 API (compare_policies, policy_adapters, learning notebooks). Their ideas are covered by 0.3: leakage-safe auto features, deterministic action-column policies, data-driven binary rewards and label-based diagnostics. The "when is OPE enough vs an A/B test" guidance from docs/how_to_interpret_ope_outputs_ru.md is ported to the README separately. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…dtypes - policy rows: an ndarray is always positional; a default 0..n-1 index on a policy table with logs whose index is a permutation of 0..n-1 (after sort or sample) is now an explicit ambiguity error instead of a silent label match - a metric that is constant in the logs is a blocking finding instead of a confident "B is worse, p<0.001" on rounding noise - Romano-Wolf isolates hypotheses with zero/NaN SE; bootstrap percentiles and SDs no longer emit numpy RuntimeWarnings for empty columns - categorical columns with unused levels are encoded without pandas warnings; action labels are Python scalars; nullable NA propensities give the friendly error; huge explicit categoricals and propensity-like auto features refused - too few rows / clusters for the folds are explained up front; random_state validated; lower_is_better accepts a string; ps.evaluate(baseline_name=...) - bootstrap duration notice via warnings (visible in Jupyter) - Leaderboard ranks candidates, has __repr__/to_json and only mentions Romano-Wolf when p-values were adjusted; decisions name the baseline - simulator validates policy tables Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The bootstrap duration warning now names the caller's line (first frame outside the package) and gives a hint that fits the situation: logged propensities, DM, or influence. The Romano-Wolf caption declines "метрика" by count. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- pyproject: PEP 621/639 metadata, SPDX license, dynamic version from policyscope.__version__, classifiers 3.10-3.14, project URLs, threadpoolctl>=3.5, build/twine in the dev extra; MANIFEST.in ships docs, examples and tests in the sdist. - CI: Python 3.10-3.14 matrix, minimum-dependency job, wheel build with twine check and tests against the installed wheel, weekly schedule, slow statistical validation and tutorial execution. - release.yml (dormant until a v* tag) and RELEASING.md: Trusted Publishing via TestPyPI -> PyPI -> GitHub Release. - README: absolute links for the PyPI page, install from GitHub until the PyPI release, "OPE or A/B test" section, corrected config example. - CHANGELOG rewritten around 0.3.0 with a migration table from 0.1; methodology gets the full table of finding codes; estimators and validation docs reconciled; tutorial compares both metrics with the truth in the no-propensity section and is re-executed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…warning pandas 2.3 deprecates Index dtype inference from object Series; with interval categories (pd.cut) Categorical(..., categories=...) hit it. Seen on the py3.10 CI job, which resolves to pandas 2.3.3. Co-Authored-By: Claude Opus 5.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.
Что это
Переработка
policyscopeв версию 0.3.0: пакет написан заново, API спроектирован вокруг сценариев использования. Обратной совместимости с 0.1 нет. Таблица перехода — в CHANGELOG.md.Главное
Оценки
estimator="dm") и всегда с bootstrap-интервалом. Почему так — вdocs/estimators.md.Интервалы и p-value
inference="auto"выбирает метод сам: аналитический при логированных пропенсити, bootstrap при оценённых.Отчёт
Проверка
examples/validate.py— 8 сценариев на симуляторе с аналитическим оракулом: покрытие интервалов, смещение, MCSE. Результаты — вdocs/validation.md.docs/estimators.md— исследование оценщиков, в том числе ответ на вопрос «почему DM не по умолчанию, если он самый мощный».examples/tutorial.ipynb. Методология и коды находок —docs/methodology.md.Упаковка и CI
policyscope.__version__).twine checkи тесты против установленного wheel;release.ymlиRELEASING.mdподготовлены для публикации на PyPI через Trusted Publishing. Workflow срабатывает только по тегуv*; публикация в этот PR не входит.Как ветка связана с main
Коммиты из
main(PR #41, #42) влиты стратегией-s ours: история сохранена, код заменён переработкой. Их идеи в 0.3 уже покрыты:Раздел «Когда OPE достаточно, а когда нужен A/B-тест» перенесён в README.
Проверено локально
validate.py --runs 30 --clients 2000 --n-boot 60 --strict.twine check --strictи тесты из установленного пакета.🤖 Generated with Claude Code