Skip to content

policyscope 0.3.0: переработка оценки политик, отчётов и проверки - #44

Merged
Yurashku merged 12 commits into
mainfrom
modernize-policyscope
Oct 27, 2026
Merged

Yurashku merged 12 commits into
mainfrom
modernize-policyscope

Conversation

@Yurashku

Copy link
Copy Markdown
Owner

Что это

Переработка policyscope в версию 0.3.0: пакет написан заново, API спроектирован вокруг сценариев использования. Обратной совместимости с 0.1 нет. Таблица перехода — в CHANGELOG.md.

import policyscope as ps

report = ps.evaluate(logs, new_policy, action="offer", reward=["accepted", "revenue"],
                     propensity="propensity", cluster="client_id")
report  # вывод, Δ с интервалом, p-value с поправкой Romano–Wolf, находки диагностики

Главное

Оценки

  • Оценщики DR (по умолчанию), SNDR, IPS и SNIPS. Все строятся из построчных вкладов, у самонормированных оценщиков вклады линеаризованы дельта-методом.
  • DM доступен только явно (estimator="dm") и всегда с bootstrap-интервалом. Почему так — в docs/estimators.md.
  • Модели исхода и пропенсити всегда обучаются кросс-фиттингом. Фолды группируются по кластерам.
  • Модель исхода выбирается по данным: логистическая регрессия для бинарной метрики, двухчастная модель (logit × Gamma) для выручки с нулями, иначе Ridge.

Интервалы и p-value

  • Аналитический интервал по функции влияния с кластерно-устойчивой ошибкой (CR1).
  • Кластерный bootstrap с переобучением моделей.
  • inference="auto" выбирает метод сам: аналитический при логированных пропенсити, bootstrap при оценённых.
  • При нескольких метриках p-value поправляются по Romano–Wolf.

Отчёт

  • Вывод: лучше, хуже, без разницы, «сделать нельзя» или не посчитано.
  • Структурированные находки диагностики: код, уровень, числа, совет. Среди проверок:
    • перекрытие и ESS;
    • хвосты весов;
    • сверка DR с IPS и DM;
    • утечки исхода в признаки;
    • постоянная метрика.
  • Любая блокирующая находка переводит вывод в «сделать нельзя».

Проверка

  • examples/validate.py — 8 сценариев на симуляторе с аналитическим оракулом: покрытие интервалов, смещение, MCSE. Результаты — в docs/validation.md.
  • docs/estimators.md — исследование оценщиков, в том числе ответ на вопрос «почему DM не по умолчанию, если он самый мощный».
  • Пошаговый туториал — examples/tutorial.ipynb. Методология и коды находок — docs/methodology.md.

Упаковка и CI

  • Метаданные по PEP 621/639, версия задаётся в одном месте (policyscope.__version__).
  • CI:
    • тесты на Python 3.10–3.14;
    • прогон на минимальных версиях зависимостей;
    • сборка wheel, 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.

Проверено локально

  • flake8 без замечаний.
  • 184 быстрых теста: на Python 3.12 со свежими зависимостями и на 3.10 с минимальными версиями.
  • Медленные тесты.
  • validate.py --runs 30 --clients 2000 --n-boot 60 --strict.
  • Туториал исполняется.
  • wheel и sdist собираются, проходят twine check --strict и тесты из установленного пакета.

🤖 Generated with Claude Code

Yurashku and others added 10 commits October 20, 2026 16:31
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>
Yurashku and others added 2 commits October 27, 2026 23:08
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>
@Yurashku
Yurashku merged commit 1e3a544 into main Oct 27, 2026
8 checks passed
@Yurashku
Yurashku deleted the modernize-policyscope branch October 28, 2026 14:47
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