Skip to content

[DOCS] Add a leave-one-out link ratio example with GridSearch - #1673

Open
scks1 wants to merge 4 commits into
casact:mainfrom
scks1:docs-leave-one-out-gridsearch-1658
Open

scks1 wants to merge 4 commits into
casact:mainfrom
scks1:docs-leave-one-out-gridsearch-1658

Conversation

@scks1

@scks1 scks1 commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Summary of Changes

This PR adds a gallery notebook, docs/gallery/plot_leave_one_out.ipynb, that drops each observed link ratio in turn and refits. A helper builds the GridSearch param_grid {"dev__drop": [None, (origin, age), ...]} and keeps every age. Two scoring callables return total IBNR and the ldf_ array. The notebook tabulates the largest moves on raa and genins and draws a heatmap of the change in total IBNR for every cell. The PR also adds the gallery card, the card image and a verdonck2011 entry in references.bib.

Related GitHub Issue(s)

Closes #1658

AI/LLM Usage

This change was made with Árbol, an AI assistant running on Muse, working under my direction. It wrote the notebook, the helper and the plot, ran the checks below and drafted this description.

Additional Context for Reviewers

  1. The notebook keeps all ages, as you asked in the issue. Both sample triangles have one ratio at 108-120, so the 2001 at 108 row on genins and the 1981 at 108 row on raa leave that ldf_ as NaN. cdf_ at 108 then reads 1, and Chainladder treats the factor as 1. The notebook says that row measures setting the last factor to 1, and the heatmap boxes those cells. [BUG] Development(drop=...) can remove every link ratio at an age, and Chainladder then uses a factor of 1 without a warning #1661 covers the docstring side.

  2. Values from the executed notebook on main at 687e329:

Triangle Base IBNR Largest move Change Share
raa 52,135 1985 at 60 3,363 6.5%
genins 18,680,856 2001 at 108 -855,780 -4.6%
genins, without the single-ratio row 18,680,856 2002 at 96 -549,914 -2.9%
  1. I executed the notebook with nbconvert. ruff@0.16.1 check and format --check pass on it. I did not run the full jb build.

Submitter's Checklist

  • I have reviewed and am adhering to the standards outlined in the project Governing Doc.
  • The PR subject title summarizes the changes, with one proper prefix ([FIX], [FEAT], [DOCS], [TST], [CHORE], or [BRK]).
  • I am a human (not a bot), and this PR form is written by a human.

Reviewer's Checklist

  • The implementation addresses the associated issue(s).
  • The implementation is appropriate, maintainable, and follows ARCHITECTURE.md.
  • PR subject title has the proper prefix and the subject is appropriate.
  • Relevant issue(s) are linked.
  • AI/LLM usage is disclosed and appropriate.
  • Documentation and tests are appropriate.
  • CI tests passed, or any failures are acceptable.
  • Leave a comment with the final recommendation (e.g. approve as is, request a secondary review, or flag an area for more review).

The new gallery notebook builds a GridSearch param_grid that drops each
observed link ratio in turn through Development(drop=...), keeping every
age, and scores each refit on total IBNR and ldf_. On raa the largest
move is 1985 at 60, at +3,363 or 6.5% of IBNR. On genins the largest row
drops the only ratio at 108-120, which leaves that ldf_ as NaN, and the
notebook explains what that row measures. A heatmap shows the change for
every cell of both triangles.

Closes casact#1658.

Developed with an AI assistant (Árbol, running Muse).
@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Pyright Type Completeness

View the full pyright --verifytypes output for this commit

Project (full chainladder package, at this PR's head): 17.6% of exported symbols fully typed (310 / 1759)

Known Ambiguous Unknown Total
Project (head) 310 102 1347 1759

Other symbols referenced but not exported by chainladder: 30

Known Ambiguous Unknown Total
Other (head) 13 1 16 30

Symbols without documentation:

  • Functions without docstring: 338
  • Functions without default param: 0
  • Classes without docstring: 10

Patch (exported symbols added or changed by this PR): 21.1% fully typed (4 / 19)

Known Ambiguous Unknown Total
Patch 4 0 15 19
Patch symbol details
Symbol Status Change
chainladder.workflow.gridsearch.GridSearch.compare_results ❌ unknown new
chainladder.workflow.gridsearch.GridSearch.ibnr ❌ unknown new
chainladder.workflow.gridsearch.GridSearch.ldf ❌ unknown new
chainladder.workflow.gridsearch.GridSearch.leave_one_out_grid ❌ unknown new
chainladder.workflow.gridsearch.LeaveOneOutGrid ❌ unknown new
chainladder.workflow.gridsearch.LeaveOneOutGrid.__init__ ❌ unknown new
chainladder.workflow.gridsearch.LeaveOneOutGrid.key ✅ known new
chainladder.workflow.gridsearch.LeaveOneOutGrid.labels ✅ known new
chainladder.workflow.tests.test_workflow.loo_pipe ✅ known new
chainladder.workflow.tests.test_workflow.loo_search ✅ known new
chainladder.workflow.tests.test_workflow.test_compare_results_accepts_a_single_scorer ❌ unknown new
chainladder.workflow.tests.test_workflow.test_compare_results_keeps_raw_index_for_other_grids ❌ unknown new
chainladder.workflow.tests.test_workflow.test_compare_results_ldf_on_an_ordinary_grid_has_no_age ❌ unknown new
chainladder.workflow.tests.test_workflow.test_compare_results_marks_single_ratio_ages ❌ unknown new
chainladder.workflow.tests.test_workflow.test_compare_results_orders_by_ibnr_change ❌ unknown new
chainladder.workflow.tests.test_workflow.test_leave_one_out_base_row_matches_plain_fit ❌ unknown new
chainladder.workflow.tests.test_workflow.test_leave_one_out_grid_covers_every_observed_ratio ❌ unknown new
chainladder.workflow.tests.test_workflow.test_leave_one_out_grid_rejects_more_than_one_column ❌ unknown new
chainladder.workflow.tests.test_workflow.test_leave_one_out_grid_survives_clone ❌ unknown new

@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.30%. Comparing base (88763a0) to head (d16d13f).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1673      +/-   ##
==========================================
+ Coverage   95.16%   95.30%   +0.14%     
==========================================
  Files         100      100              
  Lines        6593     6693     +100     
  Branches      828      842      +14     
==========================================
+ Hits         6274     6379     +105     
+ Misses        202      199       -3     
+ Partials      117      115       -2     
Flag Coverage Δ
unittests 95.30% <100.00%> (+0.14%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@henrydingliu

Copy link
Copy Markdown
Member

good stuff.

should leave_one_out_grid, ldf, ibnr, and summarize to GridSearch in this PR? or do you want the ad-hoc implementation to live on in this example and follow up with a PR to beef up GridSearch?

i have some small edits once we nail down the scope of the PR.

@scks1

scks1 commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. I'm happy to move them into GridSearch in this PR.

Here is the shape I have in mind.

  1. GridSearch.leave_one_out(estimator, X, step="dev"), a classmethod in workflow/gridsearch.py. It builds the {step}__drop grid from X.link_ratio, supplies the ibnr and ldf scorers, fits, and returns the fitted search.
  2. A summary_ DataFrame on that search with one row per dropped ratio. It carries the origin, age, link ratio, LDF before and after, and the IBNR change and share, sorted from the largest move to the smallest.
  3. The notebook then calls cl.GridSearch.leave_one_out(pipe, raa).summary_ and keeps the prose, the single-ratio cells and the heatmap.

The first version would take a triangle with one index and one column and raise a ValueError otherwise. The estimator has to end in a reserving method such as Chainladder so the ibnr scorer can read ibnr_. Tests in workflow/tests/test_workflow.py would check the base row against a plain fit, the grid against the observed ratios, and the ValueError.

Does that shape work, or would you rather have a standalone cl.leave_one_out function next to GridSearch? Once we settle it I'll write it up, and your small edits are welcome on the notebook in the meantime.

(This comment was written with Árbol, an AI assistant, under my direction.)

@henrydingliu

henrydingliu commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

GridSearch.leave_one_out(estimator, X, step="dev"), a classmethod in workflow/gridsearch.py. It builds the {step}__drop grid from X.link_ratio, supplies the ibnr and ldf scorers, fits, and returns the fitted search.

would this classmethod be called by fit() or parallel to fit()? GridSearch is still a sklearn estimator at the end of the day. I was originally thinking that we only have two ways to play the sklearn game:

  • implement LeaveOneOut, a subclass of GridSearch
  • implement leave_one_out_grid as a helper method

can we also have ibnr and ldf be defined under GridSearch?

A summary_ DataFrame on that search with one row per dropped ratio. It carries the origin, age, link ratio, LDF before and after, and the IBNR change and share, sorted from the largest move to the smallest.

i was thinking a compare_results(base, head) classmethod to generalize summary_ across other param_grids and scores.

  • why the name change?
    • "summary" didn't capture what we are doing because we are not really summarizing.
  • how to generalize origin/age/link ratio?
    • each pre-defined param_grid, like leave_one_out_grid, should also generate labels that the class stores and compare_results() uses to replace the index in results_
    • for ad-hoc param_grid, the raw index from results_ is used
  • how to generalize ldf before, ldf after, ibnr change, share of ibnr?
    • each pre-defined score, like ibnr, should also be mapped to metrics like shared of ibnr, that's calc'd off of results_, and then presented through compared_results
  • how to generalize the ordering
    • each pre-defined score, like ibnr, should provide an ordering lambda
  • what is base?
    • the label of the base element of param_grid that every row gets compared to

The notebook then calls cl.GridSearch.leave_one_out(pipe, raa).summary_ and keeps the prose, the single-ratio cells and the heatmap.

i think it'll connect with readers more if we called it "sensitivity of individual age-to-age factors", and setup the narrative that way.

@scks1

scks1 commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, this helps.

It would run parallel to fit(), so I'll drop the classmethod. fit() stays as it is and GridSearch stays a plain sklearn estimator.

Here is the shape I'd build.

  1. GridSearch.leave_one_out_grid(X, step="dev") is a static helper. It returns the {step}__drop grid as a dict subclass that also carries a label table with the origin, age and link ratio of each entry. GridSearch stores it as param_grid, so get_params and clone keep working with no new constructor argument.
  2. GridSearch.ibnr and GridSearch.ldf are built-in scorers. Each one brings its derived metrics and its sort order. For ibnr that means the IBNR change and the share of IBNR. For ldf it means the factor before and after at the dropped age.
  3. compare_results(base, head=None) swaps the results_ index for the grid's labels when the grid has them and keeps the raw index for an ad-hoc grid. It adds the metrics of each built-in scorer and sorts by the first one. I'd make it a regular method, because it reads results_ from the fitted search.

The notebook would then call

search = cl.GridSearch(
    pipe,
    cl.GridSearch.leave_one_out_grid(raa),
    scoring={"ibnr": cl.GridSearch.ibnr, "ldf": cl.GridSearch.ldf},
).fit(raa)
search.compare_results("base")

On head, my guess is the labels to compare with base, with every other row as the default, the way a diff compares a base with a head. Did you mean that, or a row count like DataFrame.head?

The first version takes one index and one column and raises a ValueError otherwise. Tests check the base row against a plain fit, the grid length against the observed link ratios, the ValueError, and get_params and clone on a search built from the helper.

I'll retitle the notebook around the sensitivity of individual age-to-age factors and rebuild the story that way. A prototype on raa reproduces the notebook's top rows with fit() unchanged. Your small edits are welcome whenever you're ready.

(This comment was written with Árbol, an AI assistant, under my direction.)

@henrydingliu

Copy link
Copy Markdown
Member

yes, i did mean head like Dataframe.head. on second thought, it's probably not necessary.

everything else checks out. i quite liked what's in this notebook already. just putting in some suggestions on making this into a repeatable framework that we can expand upon.

@henrydingliu

Copy link
Copy Markdown
Member

@scks1 did i miss a push here like i did on #1605?

…rs and compare_results

GridSearch.leave_one_out_grid builds a {step}__drop grid with the base fit
and one (origin, age) entry per observed link ratio. The grid is a dict
subclass that carries a label table, so GridSearch stores it as param_grid
and get_params and clone keep working without a new constructor argument.

GridSearch.ibnr and GridSearch.ldf are built-in scorers. compare_results
compares every candidate with a base row, adds the IBNR change and share
and the factor at the dropped age before and after, and sorts by the first
built-in scorer. Other grids keep the results_ index, and other scorers
keep their columns.

The leave-one-out gallery notebook now uses these helpers in place of its
local leave_one_out_grid and summarize functions.

Developed with an AI assistant (Árbol, running Muse).
@scks1

scks1 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

You didn't miss anything. The GridSearch version is up now in 16c5c71.

  • GridSearch.leave_one_out_grid(X, step="dev") returns the {step}__drop grid as a dict subclass with a label table. GridSearch stores it as param_grid, so get_params and clone work unchanged.
  • GridSearch.ibnr and GridSearch.ldf are built-in scorers.
  • compare_results(base) labels each row by origin and age, adds the IBNR change and share and the factor before and after the drop, and sorts by the first built-in scorer. It has no head.
  • The notebook uses these helpers in place of its local functions. I also merged main to clear the gallery index conflict.

On raa the top three rows match the notebook.

Snippet
import chainladder as cl

raa = cl.load_sample("raa")
pipe = cl.Pipeline([("dev", cl.Development()), ("model", cl.Chainladder())])
search = cl.GridSearch(
    pipe,
    cl.GridSearch.leave_one_out_grid(raa),
    scoring={"ibnr": cl.GridSearch.ibnr, "ldf": cl.GridSearch.ldf},
).fit(raa)
print(search.compare_results("base").head(3).round(4).to_string())

On 16c5c71 this prints

         origin  age  link_ratio  ibnr_change  ibnr_share  ldf_before  ldf_after
1985, 60   1985   60      1.0087    3362.8852      0.0645      1.1134     1.1525
1981, 96   1981   96      1.0029    2818.0421      0.0541      1.0169     1.0331
1981, 12   1981   12      1.6498    2467.6774      0.0473      2.9994     3.4016

One question. Development also takes drop_valuation, so leave_one_out_grid(X, axis="valuation") could leave out a whole diagonal and reuse the same scorers. Would you want that in this PR or in a follow-up?

(This comment was written with Árbol, an AI assistant, under my direction.)

Add two tests for the compare_results paths the leave-one-out tests
did not reach. One fits the ldf scorer on an ordinary grid, where no
dropped age exists and both ldf columns are NaN. The other passes a
single scoring callable, which keeps its score column and the results_
order.

Developed with an AI assistant (Árbol, running Muse).
@henrydingliu

Copy link
Copy Markdown
Member

@scks1 this is tremendously slick.

image

a couple macro thoughts I'd like to get your feedback.

  • should the class LeaveOneOutGrid be a more generic _Grid class? i.e. would we create another class if we want to define another commonly use param_grid?
  • do you think LeaveOneOutGrid or _Grid is over-complicating things? is it more intuitive than the alternative approach of:
    • leave_one_out_grid remains a staticmethod that returns the grid
    • leave_one_out_grid_labels is a separate method that takes label and returns origin, age, link_ratio
    • compare_results takes an additional optional argument result_labels that's a callable applied to labels in results_, i.e. leave_one_out_grid_labels
  • i noticed that _ibnr_metrics and _ldf_metrics are actually score-agnostic, i.e. i could define a score using ultimate_ and still use _ibnr_metrics. this feels more elegant than my original suggestion, i.e. the _Scorer class. what do you think of the alternative approach of:
    • cl.GridSearch.ibnr is just the callable _ibnr,
    • _ibnr_metrics becomes cl.GridSearch.metrics.change and cl.GridSearch.metrics.share
    • compare_results takes an additional optional argument result_metrics that's a dict. keys of the dict are the same keys of scoring; values of the dict are lists of metric callables, i.e. {"ibnr": [cl.GridSearch.metrics.change, cl.GridSearch.metrics.share]}
  • these two alternatives taken together would result in a call like this
raa_table = raa_search.compare_results(
    base="base",
    result_labels=cl.GridSearch.leave_one_out_grid_labels,
    result_metrics={
        "ibnr": [cl.GridSearch.metrics.change, cl.GridSearch.metrics.share],
        "ldf": [cl.GridSearch.metrics.before, cl.GridSearch.metrics.after],
    },
)

@scks1

scks1 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks! I agree with both alternatives. They are simpler, and plain callables leave room for other grids without a class for each one.

Three details to settle before I rework it.

  1. A label alone can't give link_ratio, since that needs the triangle. I'd have leave_one_out_grid_labels take the grid value, the (origin, age) pair in results_, and return origin and age. ldf_before and ldf_after already show what the drop does to the factor, so link_ratio could leave the table. If you want to keep it, leave_one_out_grid_labels(X) could return the callable instead.
  2. Each metric keeps today's inputs, the scorer name, the compared rows, the base row and the label columns, and returns a named Series such as ibnr_change. before and after read the age column from result_labels, so without it they give NaN, as they do now.
  3. Today the rows sort by the largest change under the first built-in scorer. With plain callables I'd sort by the absolute value of the first metric column, so change would go first in its list. A sort_by argument is the other option.

cl.GridSearch.ibnr and cl.GridSearch.ldf become the plain _ibnr and _ldf, and _Scorer and LeaveOneOutGrid go away. I'll push once you're happy with these three.

(This comment was written with Árbol, an AI assistant, under my direction.)

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.

[DOC] Example: show how much each link ratio moves ldf_ and IBNR by refitting without it

2 participants