Repository navigation
Conversation
…ce in MethodBase BootstrapODPSample takes process_dist, "gamma" by default or None, and sets it on the sample next to scale_ and the seed. transform no longer binds _get_process_variance to the sample. MethodBase._include_process_variance draws the noise from the fitted triangle's own values with those three attributes, so a copy or a slice of the sample no longer draws from the original sample (casact#1703). Developed with an AI assistant (Árbol, running Muse).
A subset of simulations now draws its process variance over its own rows, so predict no longer needs the warning and point-estimate fallback for a shape mismatch. Remove that branch and update test_predict_subset_of_simulations_keeps_shape (casact#1703). Developed with an AI assistant (Árbol, running Muse).
Pyright Type CompletenessView the full Project (full
Other symbols referenced but not exported by
Symbols without documentation:
Patch (exported symbols added or changed by this PR): 0.0% fully typed (0 / 6)
Patch symbol details
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1736 +/- ##
==========================================
+ Coverage 95.38% 95.42% +0.03%
==========================================
Files 101 101
Lines 6810 6865 +55
Branches 855 861 +6
==========================================
+ Hits 6496 6551 +55
Misses 199 199
Partials 115 115
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Add a test where a sample's process_dist changes after sampling to a value the methods cannot draw, so Chainladder.fit raises (casact#1703). Developed with an AI assistant (Árbol, running Muse).
|
|
||
| @staticmethod | ||
| def _has_process_variance(X): | ||
| """ |
There was a problem hiding this comment.
can you please add type hinting?
There was a problem hiding this comment.
I pushed 7118a15, which adds type hints to _has_process_variance and to _draw_process_variance next to it. They follow the style of validate_ldf in the same file, with X: Triangle and a return type.
(This comment was written with Árbol, an AI assistant, under my direction.)
| assert np.allclose( | ||
| plain.full_triangle_.values[..., -1:], plain.ultimate_.values, equal_nan=True | ||
| ) | ||
| if estimator is cl.MackChainladder: |
There was a problem hiding this comment.
Yes. The branch is there only for #1738. MackChainladder.predict raises "Index data must be 1-dimensional" on a bootstrap sample, with or without process variance. With a #1738-style fix patched in for a local check, the Mack case passes both predict checks in this test. Once #1738 is fixed, the branch and its comment can go.
Snippet and output on this PR's head 47a645c
import warnings
import numpy as np
import pandas as pd
import chainladder as cl
from chainladder.methods.mack import MackChainladder
warnings.simplefilter("ignore")
raa = cl.load_sample("raa")
without = cl.BootstrapODPSample(
n_sims=50, random_state=42, process_dist=None
).fit_transform(raa)
plain = cl.MackChainladder().fit(without)
try:
plain.predict(without)
print("head: predict ok")
except ValueError as e:
print("head: predict ValueError", e)
def patched(self, obj):
obj = obj.total_process_risk_**2 + obj.total_parameter_risk_**2
out = obj.sqrt().values[..., 0, -1]
index = obj.index.iloc[:, 0] if len(obj.key_labels) == 1 else obj.index
return pd.DataFrame(out, index=index, columns=obj.columns)
MackChainladder._get_total_mack_std_err_ = patched
pred = plain.predict(without)
print("patched: process_variance_ is None", pred.process_variance_ is None)
print(
"patched: ultimate matches",
np.allclose(pred.ultimate_.values, plain.ultimate_.values, equal_nan=True),
)head: predict ValueError Index data must be 1-dimensional
patched: process_variance_ is None True
patched: ultimate matches True
(This comment was written with Árbol, an AI assistant, under my direction.)
| equal_nan=True, | ||
| ) | ||
| part = cl.Chainladder().fit(sims.iloc[:5]) | ||
| assert part.ultimate_.shape == (5, 1, 10, 1) |
There was a problem hiding this comment.
do we know if part.ultimate_ is the same as fit(sims).ultimate_[:5]?
There was a problem hiding this comment.
or is this same as a previous situation where integer seed makes them the same but Generator doesn't
There was a problem hiding this comment.
Yes, it is the same situation as the RandomState case on #1703. With an integer seed each draw builds a fresh RandomState(seed + 1) at base.py line 200, and gamma fills the array with the simulations on the first axis. So fit(sims.iloc[:5]) gets the same first draws as fit(sims) and matches fit(sims).ultimate_[:5] exactly. sims.iloc[5:] starts the stream over and differs. A RandomState instance moves forward on every fit, so even iloc[:5] differs, and two fits on the same sims differ too. With process_dist=None every slice matches for both. A numpy Generator from np.random.default_rng raises in BootstrapODPSample because the seed handling only accepts an integer, a RandomState or None.
Snippet and output on this PR's head 7118a15
import warnings
import numpy as np
import chainladder as cl
warnings.filterwarnings("ignore")
raa = cl.load_sample("raa")
for name in ["int", "RandomState"]:
for dist in ["gamma", None]:
rs = 42 if name == "int" else np.random.RandomState(42)
sims = cl.BootstrapODPSample(n_sims=10, random_state=rs, process_dist=dist).fit_transform(raa)
whole = cl.Chainladder().fit(sims).ultimate_.values
out = []
for a, b in [(0, 5), (5, 10)]:
part = cl.Chainladder().fit(sims.iloc[a:b]).ultimate_.values
same = np.array_equal(part, whole[a:b], equal_nan=True)
out.append(f"iloc[{a}:{b}] {same}")
print(f"{name:>11} {str(dist):>5}", *out) int gamma iloc[0:5] True iloc[5:10] False
int None iloc[0:5] True iloc[5:10] True
RandomState gamma iloc[0:5] False iloc[5:10] False
RandomState None iloc[0:5] True iloc[5:10] True
(This comment was written with Árbol, an AI assistant, under my direction.)
| X_new = self.resampled_triangles_ | ||
| X_new.scale_ = self.scale_ | ||
| X_new.random_state = self.random_state_ | ||
| X_new._get_process_variance = types.MethodType(_get_process_variance, X_new) |
There was a problem hiding this comment.
in hindsight, i don't think i fully understood why X._get_process_variance wasn't impacted by slicing. after sub = sims.iloc[:5], why would the self in _get_process_variance still refer to sims?
There was a problem hiding this comment.
On main, transform stores a bound method on the sample at bootstrap.py line 380. types.MethodType fixes its self to that sample when it runs. iloc builds the slice by calling Triangle.copy at slice.py line 61, and copy runs X.__dict__.update(vars(self)) at triangle.py line 2267. That puts the same bound method object on the slice.
Python binds self only when it finds a plain function on the class. A bound method that sits in the instance dict comes back as it is. So sub._get_process_variance.__self__ is still sims, and the draw reads sims.cum_to_incr() and returns all ten simulations.
Snippet and output on main at ebde49b
import chainladder as cl
raa = cl.load_sample("raa")
sims = cl.BootstrapODPSample(n_sims=10, random_state=42).fit_transform(raa)
sub = sims.iloc[:5]
print("bound method in vars(sub):", "_get_process_variance" in vars(sub))
print("same object as on sims:", vars(sub)["_get_process_variance"] is vars(sims)["_get_process_variance"])
print("__self__ is sims:", sub._get_process_variance.__self__ is sims)
print("sub.shape:", sub.shape)
print("fit(sub).ultimate_.shape:", cl.Chainladder().fit(sub).ultimate_.shape)bound method in vars(sub): True
same object as on sims: True
__self__ is sims: True
sub.shape: (5, 1, 10, 10)
fit(sub).ultimate_.shape: (10, 1, 10, 1)
(This comment was written with Árbol, an AI assistant, under my direction.)
Developed with an AI assistant (Árbol, running Muse).
Closes #1703. This is the first of the three steps agreed on #1703. #1706 and #1705 follow.
BootstrapODPSampletakes a newprocess_distparameter. The default"gamma"keeps today's results.Noneleaves process variance out, so a method fit on the sample gives parameter risk only andprocess_variance_comes backNone.scale_stays as fitted either way.transformsetsprocess_diston the sample next toscale_and the seed and no longer binds_get_process_varianceto it.MethodBase._include_process_variancenow draws the gamma noise itself from those three attributes and from the values of the triangle the method was fit on. The draws for an unchanged sample match main, so the existing seeded tests and docstring outputs still pass.Because the draw now reads the fitted triangle and not the original sample, a slice of simulations fits on its own rows. On main
Chainladder().fit(sims.iloc[:5]).ultimate_comes back with every simulation. With this change it has 5. Simulation 3 of the slice no longer matches simulation 3 of the full fit, which we agreed on #1703 is fine for now.The second commit changes an existing test.
predicton a subset of simulations used to warn and fall back to point estimates. The subset now draws its own process variance, so the shape check can no longer fail. The commit removes that warning branch and updatestest_predict_subset_of_simulations_keeps_shapeto expect process variance on the subset.New tests in
test_bootstrap.pycheck the attributes on the sample,process_dist=Nonefor Chainladder, MackChainladder, Benktander and BornhuetterFerguson, the rejection of an unknownprocess_dist, and fits on a copy and a slice.MackChainladder.predictfails on a bootstrap sample on main with "Index data must be 1-dimensional", with or without process variance. The new test skips the Mack predict check for that reason. I can open a separate issue for it.The
RandomStateMixinmove ontoTriangleand therandom_statemerge stay out of this PR, as agreed.I used Árbol, an AI assistant running on Muse, under my direction to write the change, the tests and this description.