-
Notifications
You must be signed in to change notification settings - Fork 62
refactor: Output format of conformal predictions #221
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
baggiponte
wants to merge
6
commits into
main
Choose a base branch
from
refactor2024/conformal-pred
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
25e5fcf
refactor: update type annotations
baggiponte 035ce09
refactor!: make conformalize args positional only
baggiponte 8555dfd
refactor: extract alphas validation
baggiponte f582b9a
test: _validate_alphas
baggiponte c859091
docs: add docstrings
baggiponte 16e35e1
refactor: add type annotations
baggiponte File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,76 +1,109 @@ | ||
from __future__ import annotations | ||
|
||
from typing import List, Optional | ||
from typing import TYPE_CHECKING | ||
|
||
if TYPE_CHECKING: | ||
from typing import Optional, Sequence, Union | ||
|
||
import polars as pl | ||
|
||
|
||
def enbpi( | ||
y_pred: pl.LazyFrame, | ||
y_resid: pl.LazyFrame, | ||
alphas: List[float], | ||
def conformalize( | ||
*, | ||
y_pred: Union[pl.DataFrame, pl.LazyFrame], | ||
y_preds: Union[pl.DataFrame, pl.LazyFrame], | ||
y_resids: Union[pl.DataFrame, pl.LazyFrame], | ||
alphas: Optional[Sequence[float]] = None, | ||
) -> pl.DataFrame: | ||
"""Compute prediction intervals using ensemble batch prediction intervals (ENBPI). | ||
Parameters | ||
---------- | ||
y_pred : Union[pl.DataFrame, pl.LazyFrame] | ||
The predicted values. | ||
y_preds : Union[pl.DataFrame, pl.LazyFrame] | ||
The predictions resulting from backtesting. | ||
y_resids : Union[pl.DataFrame, pl.LazyFrame] | ||
The backtesting residuals. | ||
alphas : Optional[Sequence[float]] | ||
The quantile levels to use for the prediction intervals. Defaults to (0.1, 0.9). | ||
Quantiles must be two values between 0 and 1 (exclusive). | ||
Returns | ||
------- | ||
pl.DataFrame | ||
The prediction intervals. | ||
""" | ||
alphas = _validate_alphas(alphas) | ||
|
||
entity_col, time_col, target_col = y_pred.columns[:3] | ||
schema = y_pred.schema | ||
|
||
_y_resids: pl.LazyFrame = y_resids.lazy().select(y_resids.columns[:3]) | ||
_y_preds: pl.LazyFrame = pl.concat( | ||
[ | ||
y_pred.lazy(), | ||
y_preds.lazy().select( | ||
entity_col, | ||
pl.col(time_col).cast(schema[time_col]), | ||
pl.col(target_col).cast(schema[target_col]), | ||
), | ||
] | ||
) | ||
|
||
y_pred_quantiles = _compute_enbpi( | ||
y_preds=_y_preds, | ||
y_resids=_y_resids, | ||
alphas=alphas, | ||
) | ||
|
||
# Make alpha base 100 | ||
y_pred_quantiles = y_pred_quantiles.with_columns( | ||
(pl.col("quantile") * 100).cast(pl.Int16) | ||
) | ||
|
||
return y_pred_quantiles | ||
|
||
|
||
def _compute_enbpi( | ||
*, | ||
y_preds: pl.LazyFrame, | ||
y_resids: pl.LazyFrame, | ||
alphas: Sequence[float], | ||
) -> pl.DataFrame: | ||
"""Compute prediction intervals using ensemble batch prediction intervals (ENBPI).""" | ||
|
||
# 1. Group residuals by entity | ||
entity_col, time_col = y_pred.columns[:2] | ||
y_resid = y_resid.collect() | ||
entity_col, time_col = y_preds.columns[:2] | ||
|
||
# 2. Forecast future prediction intervals: use constant residual quantile | ||
schema = y_pred.schema | ||
schema = y_preds.schema | ||
y_pred_qnts = [] | ||
for alpha in alphas: | ||
y_pred_qnt = y_pred.join( | ||
y_resid.group_by(entity_col) | ||
.agg(pl.col(y_resid.columns[-1]).quantile(alpha).alias("score")) | ||
y_pred_qnt = y_preds.join( | ||
y_resids.group_by(entity_col) | ||
.agg(pl.col(y_resids.columns[-1]).quantile(alpha).alias("score")) | ||
.lazy(), | ||
how="left", | ||
on=entity_col, | ||
).select( | ||
[ | ||
pl.col(entity_col).cast(schema[entity_col]), | ||
pl.col(time_col).cast(schema[time_col]), | ||
pl.col(y_pred.columns[-1]) + pl.col("score"), | ||
pl.col(y_preds.columns[-1]) + pl.col("score"), | ||
pl.lit(alpha).alias("quantile"), | ||
] | ||
) | ||
y_pred_qnts.append(y_pred_qnt) | ||
|
||
y_pred_qnts = pl.concat(y_pred_qnts).sort([entity_col, time_col]).collect() | ||
return y_pred_qnts | ||
|
||
|
||
def conformalize( | ||
y_pred: pl.DataFrame, | ||
y_preds: pl.DataFrame, | ||
y_resids: pl.DataFrame, | ||
alphas: Optional[List[float]] = None, | ||
) -> pl.DataFrame: | ||
"""Compute prediction intervals using ensemble batch prediction intervals (ENBPI).""" | ||
|
||
alphas = alphas or [0.1, 0.9] | ||
entity_col, time_col, target_col = y_pred.columns[:3] | ||
schema = y_pred.schema | ||
y_preds = pl.concat( | ||
[ | ||
y_pred, | ||
y_preds.select( | ||
[ | ||
entity_col, | ||
pl.col(time_col).cast(schema[time_col]), | ||
pl.col(target_col).cast(schema[target_col]), | ||
] | ||
), | ||
] | ||
) | ||
|
||
y_preds = y_preds.lazy() | ||
y_resids = y_resids.select(y_resids.columns[:3]).lazy() | ||
y_pred_quantiles = enbpi(y_preds, y_resids, alphas) | ||
return pl.concat(y_pred_qnts).sort([entity_col, time_col]).collect() | ||
|
||
# Make alpha base 100 | ||
y_pred_quantiles = y_pred_quantiles.with_columns( | ||
(pl.col("quantile") * 100).cast(pl.Int16) | ||
) | ||
|
||
return y_pred_quantiles | ||
def _validate_alphas(alphas: Optional[Sequence[float]]) -> Sequence[float]: | ||
if alphas is None: | ||
return (0.1, 0.9) | ||
elif len(alphas) != 2: | ||
raise ValueError("alphas must be a list of length 2") | ||
elif not all(0 < alpha < 1 for alpha in alphas): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should we also check that the sequence is sorted? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. IIRC the function returns the alphas sorted, so that should be OK. Am I correct? |
||
raise ValueError("alphas must be between 0 and 1") | ||
return alphas |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
from __future__ import annotations | ||
|
||
import pytest | ||
|
||
from functime.conformal import _validate_alphas | ||
|
||
|
||
def test_validate_alphas(): | ||
assert _validate_alphas(None) == (0.1, 0.9) | ||
assert _validate_alphas([0.1, 0.9]) == [0.1, 0.9] | ||
assert _validate_alphas([0.1, 0.5]) == [0.1, 0.5] | ||
assert _validate_alphas([0.5, 0.9]) == [0.5, 0.9] | ||
|
||
with pytest.raises(ValueError): | ||
_validate_alphas([0.1, 0.5, 0.9, 0.2]) | ||
with pytest.raises(ValueError): | ||
_validate_alphas([0.1, 0.5, 0.9, 0.2, 0.3]) | ||
with pytest.raises(ValueError): | ||
_validate_alphas([0.1, -0.5]) | ||
with pytest.raises(ValueError): | ||
_validate_alphas([0.1, 1.5]) | ||
with pytest.raises(ValueError): | ||
_validate_alphas([-0.1, 0.5]) | ||
with pytest.raises(ValueError): | ||
_validate_alphas([1.1, 0.5]) |
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.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If you have more than 2 decimal places, then the casting would just truncate the decimal values 🤔
Example:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's correct; I am still to change that bit of the code fortunately. This column won't exist once I'm done ✔️