-
Notifications
You must be signed in to change notification settings - Fork 473
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
Uncertainty: Conformal Prediction V1.1 - add Conformal class to conformal_prediction.py and rename file to conformal.py #1074
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
fc1936a
Replaced yhat1 with the step_number for conformal.
Kevin-Chen2 322b239
Moved conformal_predict() method logic into conformal_prediction.py a…
Kevin-Chen2 e084a41
Changed self.config_train.quantiles to quantiles in conformal_predict…
Kevin-Chen2 d2be041
Removed q_hats in _conformalize().
Kevin-Chen2 74165b8
Renamed conformal_prediction.py to conformal.py and added the Conform…
Kevin-Chen2 2777838
Modified to resolve flake8.
Kevin-Chen2 fc6af41
Rerun uncertainty_conformal_prediction.ipynb.
Kevin-Chen2 b857202
Merge branch 'main' into refactor/conformal-class
Kevin-Chen0 8558c9d
Merge branch 'main' into refactor/conformal-class
Kevin-Chen0 828e2b0
Turn Conformal into dataclass and added _get_nonconformity_scores() a…
Kevin-Chen2 3e7b56a
Removed plot_interval_width_per_timestep() method in plot_forecast_ma…
Kevin-Chen2 b8f90ac
Merge branch 'main' into refactor/conformal-class
ourownstory cb15e7f
Update neuralprophet/conformal.py
Kevin-Chen0 f259edc
Update neuralprophet/conformal.py
Kevin-Chen0 f54ec10
Remved a blank line for conformal.py
Kevin-Chen2 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 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,151 @@ | ||
from dataclasses import dataclass | ||
|
||
import matplotlib | ||
import pandas as pd | ||
|
||
from neuralprophet.plot_forecast_matplotlib import plot_nonconformity_scores | ||
from neuralprophet.plot_forecast_plotly import plot_nonconformity_scores as plot_nonconformity_scores_plotly | ||
|
||
|
||
@dataclass | ||
class Conformal: | ||
"""Conformal prediction dataclass | ||
|
||
Parameters | ||
---------- | ||
alpha : float | ||
user-specified significance level of the prediction interval | ||
method : str | ||
name of conformal prediction technique used | ||
|
||
Options | ||
* ``naive``: Naive or Absolute Residual | ||
* ``cqr``: Conformalized Quantile Regression | ||
quantiles : list | ||
optional, list of quantiles for quantile regression uncertainty estimate | ||
|
||
""" | ||
|
||
alpha: float | ||
method: str | ||
quantiles: list = None | ||
|
||
def predict(self, df, df_cal): | ||
"""Apply a given conformal prediction technique to get the uncertainty prediction intervals (or q-hat) for test dataframe. | ||
|
||
Parameters | ||
---------- | ||
df : pd.DataFrame | ||
test dataframe | ||
df_cal : pd.DataFrame | ||
calibration dataframe | ||
|
||
Returns | ||
------- | ||
pd.DataFrame | ||
test dataframe with uncertainty prediction intervals | ||
|
||
""" | ||
# conformalize | ||
self.noncon_scores = self._get_nonconformity_scores(df_cal) | ||
self.q_hat = self._get_q_hat(df_cal) | ||
df["qhat1"] = self.q_hat | ||
if self.method == "naive": | ||
df["yhat1 - qhat1"] = df["yhat1"] - self.q_hat | ||
df["yhat1 + qhat1"] = df["yhat1"] + self.q_hat | ||
elif self.method == "cqr": | ||
quantile_hi = str(max(self.quantiles) * 100) | ||
quantile_lo = str(min(self.quantiles) * 100) | ||
df[f"yhat1 {quantile_hi}% - qhat1"] = df[f"yhat1 {quantile_hi}%"] - self.q_hat | ||
df[f"yhat1 {quantile_hi}% + qhat1"] = df[f"yhat1 {quantile_hi}%"] + self.q_hat | ||
df[f"yhat1 {quantile_lo}% - qhat1"] = df[f"yhat1 {quantile_lo}%"] - self.q_hat | ||
df[f"yhat1 {quantile_lo}% + qhat1"] = df[f"yhat1 {quantile_lo}%"] + self.q_hat | ||
else: | ||
raise ValueError( | ||
f"Unknown conformal prediction method '{self.method}'. Please input either 'naive' or 'cqr'." | ||
) | ||
|
||
return df | ||
|
||
def _get_nonconformity_scores(self, df_cal): | ||
"""Get the nonconformity scores using the given conformal prediction technique. | ||
|
||
Parameters | ||
---------- | ||
df_cal : pd.DataFrame | ||
calibration dataframe | ||
|
||
Returns | ||
------- | ||
np.ndarray | ||
nonconformity scores from the calibration datapoints | ||
|
||
""" | ||
if self.method == "cqr": | ||
# CQR nonconformity scoring function | ||
quantile_hi = str(max(self.quantiles) * 100) | ||
quantile_lo = str(min(self.quantiles) * 100) | ||
cqr_scoring_func = ( | ||
lambda row: [None, None] | ||
if row[f"yhat1 {quantile_lo}%"] is None or row[f"yhat1 {quantile_hi}%"] is None | ||
else [ | ||
max( | ||
row[f"yhat1 {quantile_lo}%"] - row["y"], | ||
row["y"] - row[f"yhat1 {quantile_hi}%"], | ||
), | ||
0 if row[f"yhat1 {quantile_lo}%"] - row["y"] > row["y"] - row[f"yhat1 {quantile_hi}%"] else 1, | ||
] | ||
) | ||
scores_df = df_cal.apply(cqr_scoring_func, axis=1, result_type="expand") | ||
scores_df.columns = ["scores", "arg"] | ||
noncon_scores = scores_df["scores"].values | ||
else: # self.method == "naive" | ||
# Naive nonconformity scoring function | ||
noncon_scores = abs(df_cal["y"] - df_cal["yhat1"]).values | ||
# Remove NaN values | ||
noncon_scores = noncon_scores[~pd.isnull(noncon_scores)] | ||
# Sort | ||
noncon_scores.sort() | ||
|
||
return noncon_scores | ||
|
||
def _get_q_hat(self, df_cal): | ||
"""Get the q_hat that is derived from the nonconformity scores. | ||
|
||
Parameters | ||
---------- | ||
df_cal : pd.DataFrame | ||
calibration dataframe | ||
|
||
Returns | ||
------- | ||
float | ||
q_hat value, or the one-sided prediction interval width | ||
|
||
""" | ||
# Get the q-hat index and value | ||
q_hat_idx = int(len(self.noncon_scores) * self.alpha) | ||
q_hat = self.noncon_scores[-q_hat_idx] | ||
|
||
return q_hat | ||
|
||
def plot(self, plotting_backend): | ||
"""Apply a given conformal prediction technique to get the uncertainty prediction intervals (or q-hats). | ||
|
||
Parameters | ||
---------- | ||
plotting_backend : str | ||
specifies the plotting backend for the nonconformity scores plot, if any | ||
|
||
Options | ||
* ``matplotlib``: Use matplotlib backend for plotting | ||
* ``plotly``: Use the plotly backend for plotting | ||
|
||
""" | ||
method = self.method.upper() if "cqr" in self.method.lower() else self.method.title() | ||
if plotting_backend == "plotly": | ||
fig = plot_nonconformity_scores_plotly(self.noncon_scores, self.alpha, self.q_hat, method) | ||
elif plotting_backend == "matplotlib": | ||
fig = plot_nonconformity_scores(self.noncon_scores, self.alpha, self.q_hat, method) | ||
if plotting_backend in ["matplotlib", "plotly"] and matplotlib.is_interactive(): | ||
fig.show() |
This file was deleted.
Oops, something went wrong.
This file contains 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
Oops, something went wrong.
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.
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.
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.
Why can this be
None
?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
None
, NeuralProphet will automatically set it to[]
behind-the-scene. Then, if0.5
doesn't exist in the input quantiles list, then NP will automatically add it to the front of the list. Therefore, defaultNone
will become[0.5]
.