id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
167,365 | import torch.nn as nn
import torch
import numpy as np
import torch.nn.functional as F
import math
from torchlibrosa.stft import magphase
The provided code snippet includes necessary dependencies for implementing the `init_gru` function. Write a Python function `def init_gru(rnn)` to solve the following problem:
Initialize a GRU layer.
Here is the function:
def init_gru(rnn):
"""Initialize a GRU layer. """
def _concat_init(tensor, init_funcs):
(length, fan_out) = tensor.shape
fan_in = length // len(init_funcs)
for (i, init_func) in enumerate(init_funcs):
init_func(tensor[i * fan_in : (i + 1) * fan_in, :])
def _inner_uniform(tensor):
fan_in = nn.init._calculate_correct_fan(tensor, "fan_in")
nn.init.uniform_(tensor, -math.sqrt(3 / fan_in), math.sqrt(3 / fan_in))
for i in range(rnn.num_layers):
_concat_init(
getattr(rnn, "weight_ih_l{}".format(i)),
[_inner_uniform, _inner_uniform, _inner_uniform],
)
torch.nn.init.constant_(getattr(rnn, "bias_ih_l{}".format(i)), 0)
_concat_init(
getattr(rnn, "weight_hh_l{}".format(i)),
[_inner_uniform, _inner_uniform, nn.init.orthogonal_],
)
torch.nn.init.constant_(getattr(rnn, "bias_hh_l{}".format(i)), 0) | Initialize a GRU layer. |
167,366 | import torch.nn as nn
import torch
import numpy as np
import torch.nn.functional as F
import math
from torchlibrosa.stft import magphase
def act(x, activation):
if activation == "relu":
return F.relu_(x)
elif activation == "leaky_relu":
return F.leaky_relu_(x, negative_slope=0.01)
elif activation == "swish":
return x * torch.sigmoid(x)
else:
raise Exception("Incorrect activation!") | null |
167,367 | import numpy as np
from typing import Dict, List, NoReturn, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchlibrosa.stft import STFT, ISTFT, magphase
from models.base import Base, init_layer, init_bn, act
def get_film_meta(module):
film_meta = {}
if hasattr(module, 'has_film'):\
if module.has_film:
film_meta['beta1'] = module.bn1.num_features
film_meta['beta2'] = module.bn2.num_features
else:
film_meta['beta1'] = 0
film_meta['beta2'] = 0
for child_name, child_module in module.named_children():
child_meta = get_film_meta(child_module)
if len(child_meta) > 0:
film_meta[child_name] = child_meta
return film_meta | null |
167,368 | import warnings
import numpy as np
import pandas as pd
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import convert_date_to_continuous_time
from greykite.common.time_properties import describe_timeseries
def convert_date_to_continuous_time(dt):
"""Converts date to continuous time. Each year is one unit.
Parameters
----------
dt : datetime object
the date to convert
Returns
-------
conti_date : `float`
the date represented in years
"""
year_length = datetime(dt.year, 12, 31).timetuple().tm_yday
tt = dt.timetuple()
return (dt.year +
(tt.tm_yday - 1
+ dt.hour / 24
+ dt.minute / (24 * 60)
+ dt.second / (24 * 3600)) / float(year_length))
def build_time_features_df(
dt,
conti_year_origin,
add_dst_info=True):
"""This function gets a datetime-like vector and creates new columns containing temporal
features useful for time series analysis and forecasting e.g. year, week of year, etc.
Parameters
----------
dt : array-like (1-dimensional)
A vector of datetime-like values
conti_year_origin : `float`
The origin used for creating continuous time which is in years unit.
add_dst_info : `bool`, default True
Determines if daylight saving columns for US and Europe should be added.
Returns
-------
time_features_df : `pandas.DataFrame`
Dataframe with the following time features.
* "datetime": `datetime.datetime` object, a combination of date and a time
* "date": `datetime.date` object, date with the format (year, month, day)
* "year": integer, year of the date e.g. 2018
* "year_length": integer, number of days in the year e.g. 365 or 366
* "quarter": integer, quarter of the date, 1, 2, 3, 4
* "quarter_start": `pandas.DatetimeIndex`, date of beginning of the current quarter
* "quarter_length": integer, number of days in the quarter, 90/91 for Q1, 91 for Q2, 92 for Q3 and Q4
* "month": integer, month of the year, January=1, February=2, ..., December=12
* "month_length": integer, number of days in the month, 28/ 29/ 30/ 31
* "woy": integer, ISO 8601 week of the year where a week starts from Monday, 1, 2, ..., 53
* "doy": integer, ordinal day of the year, 1, 2, ..., year_length
* "doq": integer, ordinal day of the quarter, 1, 2, ..., quarter_length
* "dom": integer, ordinal day of the month, 1, 2, ..., month_length
* "dow": integer, day of the week, Monday=1, Tuesday=2, ..., Sunday=7
* "str_dow": string, day of the week as a string e.g. "1-Mon", "2-Tue", ..., "7-Sun"
* "str_doy": string, day of the year e.g. "2020-03-20" for March 20, 2020
* "hour": integer, discrete hours of the datetime, 0, 1, ..., 23
* "minute": integer, minutes of the datetime, 0, 1, ..., 59
* "second": integer, seconds of the datetime, 0, 1, ..., 3599
* "year_month": string, (year, month) e.g. "2020-03" for March 2020
* "year_woy": string, (year, week of year) e.g. "2020_42" for 42nd week of 2020
* "month_dom": string, (month, day of month) e.g. "02/20" for February 20th
* "year_woy_dow": string, (year, week of year, day of week) e.g. "2020_03_6" for Saturday of 3rd week in 2020
* "woy_dow": string, (week of year, day of week) e.g. "03_6" for Saturday of 3rd week
* "dow_hr": string, (day of week, hour) e.g. "4_09" for 9am on Thursday
* "dow_hr_min": string, (day of week, hour, minute) e.g. "4_09_10" for 9:10am on Thursday
* "tod": float, time of day, continuous, 0.0 to 24.0
* "tow": float, time of week, continuous, 0.0 to 7.0
* "tom": float, standardized time of month, continuous, 0.0 to 1.0
* "toq": float, time of quarter, continuous, 0.0 to 1.0
* "toy": float, standardized time of year, continuous, 0.0 to 1.0
* "conti_year": float, year in continuous time, eg 2018.5 means middle of the year 2018
* "is_weekend": boolean, weekend indicator, True for weekend, else False
* "dow_grouped": string, Monday-Thursday=1234-MTuWTh, Friday=5-Fri, Saturday=6-Sat, Sunday=7-Sun
* "ct1": float, linear growth based on conti_year_origin, -infinity to infinity
* "ct2": float, signed quadratic growth, -infinity to infinity
* "ct3": float, signed cubic growth, -infinity to infinity
* "ct_sqrt": float, signed square root growth, -infinity to infinity
* "ct_root3": float, signed cubic root growth, -infinity to infinity
* "us_dst": bool, determines if the time inside the daylight saving time of US
This column is only generated if ``add_dst_info=True``
* "eu_dst": bool, determines if the time inside the daylight saving time of Europe. This column is only generated if ``add_dst_info=True``
"""
dt = pd.DatetimeIndex(dt)
if len(dt) == 0:
raise ValueError("Length of dt cannot be zero.")
# basic time features
date = dt.date
year = dt.year
year_length = (365.0 + dt.is_leap_year)
quarter = dt.quarter
month = dt.month
month_length = dt.days_in_month
# finds first day of quarter
quarter_start = pd.DatetimeIndex(
dt.year.map(str) + "-" + (3 * quarter - 2).map(int).map(str) + "-01")
next_quarter_start = dt + pd.tseries.offsets.QuarterBegin(startingMonth=1)
quarter_length = (next_quarter_start - quarter_start).days
# finds offset from first day of quarter (rounds down to nearest day)
doq = ((dt - quarter_start) / pd.to_timedelta("1D") + 1).astype(int)
# week of year, "woy", follows ISO 8601:
# - Week 01 is the week with the year's first Thursday in it.
# - A week begins with Monday and ends with Sunday.
# So the week number of the week that overlaps both years, is 1, 52, or 53,
# depending on whether it has more days in the previous year or new year.
# - e.g. Jan 1st, 2018 is Monday. woy of first 8 days = [1, 1, 1, 1, 1, 1, 1, 2]
# - e.g. Jan 1st, 2019 is Tuesday. woy of first 8 days = [1, 1, 1, 1, 1, 1, 2, 2]
# - e.g. Jan 1st, 2020 is Wednesday. woy of first 8 days = [1, 1, 1, 1, 1, 2, 2, 2]
# - e.g. Jan 1st, 2015 is Thursday. woy of first 8 days = [1, 1, 1, 1, 2, 2, 2, 2]
# - e.g. Jan 1st, 2021 is Friday. woy of first 8 days = [53, 53, 53, 1, 1, 1, 1, 1]
# - e.g. Jan 1st, 2022 is Saturday. woy of first 8 days = [52, 52, 1, 1, 1, 1, 1, 1]
# - e.g. Jan 1st, 2023 is Sunday. woy of first 8 days = [52, 1, 1, 1, 1, 1, 1, 1]
woy = dt.strftime("%V").astype(int)
doy = dt.dayofyear
dom = dt.day
dow = dt.strftime("%u").astype(int)
str_dow = dt.strftime("%u-%a") # e.g. 1-Mon, 2-Tue, ..., 7-Sun
hour = dt.hour
minute = dt.minute
second = dt.second
# grouped time feature
year_quarter = dt.strftime("%Y-") + quarter.astype(str) # e.g. 2020-1 for March 2020
str_doy = dt.strftime("%Y-%m-%d") # e.g. 2020-03-20 for March 20, 2020
year_month = dt.strftime("%Y-%m") # e.g. 2020-03 for March 2020
month_dom = dt.strftime("%m/%d") # e.g. 02/20 for February 20th
year_woy = dt.strftime("%Y_%V") # e.g. 2020_42 for 42nd week of 2020
year_woy_dow = dt.strftime("%Y_%V_%u") # e.g. 2020_03_6 for Saturday of 3rd week in 2020
woy_dow = dt.strftime("%W_%u") # e.g. 03_6 for Saturday of 3rd week
dow_hr = dt.strftime("%u_%H") # e.g. 4_09 for 9am on Thursday
dow_hr_min = dt.strftime("%u_%H_%M") # e.g. 4_09_10 for 9:10am on Thursday
# iso features https://en.wikipedia.org/wiki/ISO_week_date
# Uses `pd.Index` to avoid overriding the indices in the output df.
year_iso = pd.Index(dt.isocalendar()["year"])
year_woy_iso = pd.Index(year_iso.astype(str) + "_" + dt.strftime("%V"))
year_woy_dow_iso = pd.Index(year_woy_iso + "_" + dt.isocalendar()["day"].astype(str))
# derived time features
tod = hour + (minute / 60.0) + (second / 3600.0)
tow = dow - 1 + (tod / 24.0)
tom = (dom - 1 + (tod / 24.0)) / month_length
toq = (doq - 1 + (tod / 24.0)) / quarter_length
# time of year, continuous, 0.0 to 1.0. e.g. Jan 1, 12 am = 0/365, Jan 2, 12 am = 1/365, ...
# To handle leap years, Feb 28 = 58/365 - 59/365, Feb 29 = 59/365, Mar 1 = 59/365 - 60/365
# offset term is nonzero only in leap years
# doy_offset reduces doy by 1 from from Mar 1st (doy > 60)
doy_offset = (year_length == 366) * 1.0 * (doy > 60)
# tod_offset sets tod to 0 on Feb 29th (doy == 60)
tod_offset = 1 - (year_length == 366) * 1.0 * (doy == 60)
toy = (doy - 1 - doy_offset + (tod / 24.0) * tod_offset) / 365.0
# year of date in continuous time, eg 2018.5 means middle of year 2018
# this is useful for modeling features that do not care about leap year e.g. environmental variables
conti_year = year + (doy - 1 + (tod / 24.0)) / year_length
is_weekend = pd.Series(dow).apply(lambda x: x in [6, 7]).values # weekend indicator
# categorical var with levels (Mon-Thu, Fri, Sat, Sun), could help when training data are sparse.
dow_grouped = pd.Series(str_dow).apply(
lambda x: "1234-MTuWTh" if (x in ["1-Mon", "2-Tue", "3-Wed", "4-Thu"]) else x).values
# growth terms
ct1 = conti_year - conti_year_origin
ct2 = signed_pow(ct1, 2)
ct3 = signed_pow(ct1, 3)
ct_sqrt = signed_pow(ct1, 1/2)
ct_root3 = signed_pow(ct1, 1/3)
# All keys must be added to constants.
features_dict = {
cst.TimeFeaturesEnum.datetime.value: dt,
cst.TimeFeaturesEnum.date.value: date,
cst.TimeFeaturesEnum.year.value: year,
cst.TimeFeaturesEnum.year_length.value: year_length,
cst.TimeFeaturesEnum.quarter.value: quarter,
cst.TimeFeaturesEnum.quarter_start.value: quarter_start,
cst.TimeFeaturesEnum.quarter_length.value: quarter_length,
cst.TimeFeaturesEnum.month.value: month,
cst.TimeFeaturesEnum.month_length.value: month_length,
cst.TimeFeaturesEnum.woy.value: woy,
cst.TimeFeaturesEnum.doy.value: doy,
cst.TimeFeaturesEnum.doq.value: doq,
cst.TimeFeaturesEnum.dom.value: dom,
cst.TimeFeaturesEnum.dow.value: dow,
cst.TimeFeaturesEnum.str_dow.value: str_dow,
cst.TimeFeaturesEnum.str_doy.value: str_doy,
cst.TimeFeaturesEnum.hour.value: hour,
cst.TimeFeaturesEnum.minute.value: minute,
cst.TimeFeaturesEnum.second.value: second,
cst.TimeFeaturesEnum.year_quarter.value: year_quarter,
cst.TimeFeaturesEnum.year_month.value: year_month,
cst.TimeFeaturesEnum.year_woy.value: year_woy,
cst.TimeFeaturesEnum.month_dom.value: month_dom,
cst.TimeFeaturesEnum.year_woy_dow.value: year_woy_dow,
cst.TimeFeaturesEnum.woy_dow.value: woy_dow,
cst.TimeFeaturesEnum.dow_hr.value: dow_hr,
cst.TimeFeaturesEnum.dow_hr_min.value: dow_hr_min,
cst.TimeFeaturesEnum.year_iso.value: year_iso,
cst.TimeFeaturesEnum.year_woy_iso.value: year_woy_iso,
cst.TimeFeaturesEnum.year_woy_dow_iso.value: year_woy_dow_iso,
cst.TimeFeaturesEnum.tod.value: tod,
cst.TimeFeaturesEnum.tow.value: tow,
cst.TimeFeaturesEnum.tom.value: tom,
cst.TimeFeaturesEnum.toq.value: toq,
cst.TimeFeaturesEnum.toy.value: toy,
cst.TimeFeaturesEnum.conti_year.value: conti_year,
cst.TimeFeaturesEnum.is_weekend.value: is_weekend,
cst.TimeFeaturesEnum.dow_grouped.value: dow_grouped,
cst.TimeFeaturesEnum.ct1.value: ct1,
cst.TimeFeaturesEnum.ct2.value: ct2,
cst.TimeFeaturesEnum.ct3.value: ct3,
cst.TimeFeaturesEnum.ct_sqrt.value: ct_sqrt,
cst.TimeFeaturesEnum.ct_root3.value: ct_root3,
}
df = pd.DataFrame(features_dict)
if add_dst_info:
df[cst.TimeFeaturesEnum.us_dst.value] = is_dst_fcn("US/Pacific")(
df[cst.TimeFeaturesEnum.datetime.value])
df[cst.TimeFeaturesEnum.eu_dst.value] = is_dst_fcn("Europe/London")(
df[cst.TimeFeaturesEnum.datetime.value])
return df
def describe_timeseries(df, time_col):
"""Checks if a time series consists of equal time increments
and if it is in increasing order.
:param df: data.frame which includes the time column in datetime format
:param time_col: time column
:return: a dictionary with following items
- dataframe ("df") with added delta columns
- "regular_increments" booleans to see if time deltas as the same
- "increasing" a boolean to denote if the time increments are increasing
- "min_timestamp": minimum timestamp in data
- "max_timestamp": maximum timestamp in data
- "mean_increment_secs": mean of increments in seconds
- "min_increment_secs": minimum of increments in seconds
- "median_increment_secs": median of increments in seconds
- "mean_delta": mean of time increments
- "min_delta": min of the time increments
- "max_delta": max of the time increments
- "median_delta": median of the time increments
- "freq_in_secs": the frequency of the timeseries in seconds which is defined to be the median time-gap
- "freq_in_days": the frequency of the timeseries in days which is defined to be the median time-gap
- "freq_in_timedelta": the frequency of the timeseries in `datetime.timedelta` which is defined to be the median time-gap
"""
df = df.copy(deep=True)
df[time_col] = pd.to_datetime(df[time_col])
if df.shape[0] < 2:
raise Exception("dataframe needs to have at least two rows")
df["delta"] = (
df[time_col] - df[time_col].shift()).fillna(pd.Timedelta(seconds=0))
df["delta_sec"] = df["delta"].values / np.timedelta64(1, "s")
delta_sec = df["delta_sec"][1:]
mean_increment_secs = np.mean(delta_sec)
min_increment_secs = min(delta_sec)
median_increment_secs = np.median(delta_sec)
regular_increments = (max(delta_sec) == min(delta_sec))
increasing = min(delta_sec > 0)
min_timestamp = df[time_col].min()
max_timestamp = df[time_col].max()
delta = df["delta"][1:]
min_delta = min(delta)
max_delta = max(delta)
mean_delta = np.mean(delta)
median_delta = np.median(delta)
# The frequency is defined by the median time-gap
freq_in_secs = median_increment_secs
freq_in_days = freq_in_secs / (24 * 3600)
freq_in_timedelta = datetime.timedelta(days=freq_in_days)
return {
"df": df,
"regular_increments": regular_increments,
"increasing": increasing,
"min_timestamp": min_timestamp,
"max_timestamp": max_timestamp,
"mean_increment_secs": mean_increment_secs,
"min_increment_secs": min_increment_secs,
"median_increment_secs": median_increment_secs,
"mean_delta": mean_delta,
"median_delta": median_delta,
"min_delta": min_delta,
"max_delta": max_delta,
"freq_in_secs": freq_in_secs,
"freq_in_days": freq_in_days,
"freq_in_timedelta": freq_in_timedelta
}
The provided code snippet includes necessary dependencies for implementing the `forecast_similarity_based` function. Write a Python function `def forecast_similarity_based( df, time_col, value_cols, agg_method, agg_func=None, grid_size_str=None, match_cols=[], origin_for_time_vars=None, recent_k=1)` to solve the following problem:
Fits a basic forecast model which is aggregate based. As an example for an hourly time series we can assign the value of the most recent three weeks at the same time of the week as forecast. This works for multiple responses passed as a list in "value_cols". Also we do not require the timestamps to be regular and for example dataframe can have missing timestamps. :param df: the dataframe which includes the training data, the value_cols and match_cols if needed :param time_col: the column of the dataframe which includes the timestamps of the series :param value_cols: the response columns for which forecast is desired :param agg_method: a string which specifies the aggregation method. Options are "mean": the mean of the values at timestamps which match with desired time on match_cols "median": the median of the values at timestamps which match with desired time on match_cols "min": the min of the values at timestamps which match with desired time on match_cols "max": the max of the values at timestamps which match with desired time on match_cols "most_recent": the mean of "recent_k" (given in last argument of the function) values matching with desired time on match_cols :param agg_func: the aggregation function needed for aggregating w.r.t "match_cols". This is needed if agg_method is not available. :param grid_size_str: the expected time increment. If not provided it is inferred. :param match_cols: the variables used for grouping in aggregation :param origin_for_time_vars: the time origin for continuous time variables :param recent_k: the number of most recent timestamps to consider for aggregation :return: A dictionary consisting of a "model" and a "predict" function. The "model" object is simply a dictionary of two items (dataframes). First item is an aggregated dataframe of "value_cols" w.r.t "match_cols": "pred_df" Second item is an aggregated dataframe across all data: "pred_df_overall". This is useful if a level in match_cols didn't appear in train dataset, therefore in that case we fall back to overall prediction The "predict" is a function which performs prediction for new data The "predict_n" is a function which predicts the future for any given number of steps specified
Here is the function:
def forecast_similarity_based(
df,
time_col,
value_cols,
agg_method,
agg_func=None,
grid_size_str=None,
match_cols=[],
origin_for_time_vars=None,
recent_k=1):
"""Fits a basic forecast model which is aggregate based. As an example for an hourly time series we
can assign the value of the most recent three weeks at the same time of the week as forecast.
This works for multiple responses passed as a list in "value_cols".
Also we do not require the timestamps to be regular and for example dataframe can have missing
timestamps.
:param df: the dataframe which includes the training data, the value_cols and match_cols if needed
:param time_col: the column of the dataframe which includes the timestamps of the series
:param value_cols: the response columns for which forecast is desired
:param agg_method: a string which specifies the aggregation method. Options are
"mean": the mean of the values at timestamps which match with desired time on match_cols
"median": the median of the values at timestamps which match with desired time on match_cols
"min": the min of the values at timestamps which match with desired time on match_cols
"max": the max of the values at timestamps which match with desired time on match_cols
"most_recent": the mean of "recent_k" (given in last argument of the function)
values matching with desired time on match_cols
:param agg_func: the aggregation function needed for aggregating w.r.t "match_cols".
This is needed if agg_method is not available.
:param grid_size_str: the expected time increment. If not provided it is inferred.
:param match_cols: the variables used for grouping in aggregation
:param origin_for_time_vars: the time origin for continuous time variables
:param recent_k: the number of most recent timestamps to consider for aggregation
:return: A dictionary consisting of a "model" and a "predict" function.
The "model" object is simply a dictionary of two items (dataframes).
First item is an aggregated dataframe of "value_cols" w.r.t "match_cols": "pred_df"
Second item is an aggregated dataframe across all data: "pred_df_overall".
This is useful if a level in match_cols didn't appear in train dataset,
therefore in that case we fall back to overall prediction
The "predict" is a function which performs prediction for new data
The "predict_n" is a function which predicts the future for any given number of steps specified
"""
# This is only needed for predict_n function.
# But it makes sense to do this only once for computational efficiency
timeseries_info = describe_timeseries(df, time_col)
if grid_size_str is None:
grid_size = timeseries_info["median_delta"]
grid_size_str = str(int(grid_size / np.timedelta64(1, "s"))) + "s"
max_timestamp = timeseries_info["max_timestamp"]
# a dictionary of methods and their corresponding aggregation function
agg_method_func_dict = {
"mean": (lambda x: np.mean(x)),
"median": (lambda x: np.median(x)),
"min": (lambda x: np.min(x)),
"max": (lambda x: np.max(x)),
"most_recent": (lambda x: np.mean(x[-recent_k:]))
}
if agg_func is None:
if agg_method not in agg_method_func_dict.keys():
raise Exception(
"The aggregation method you specified is not implemented." +
"These are the available methods: mean, median, min, max, most_recent")
agg_func = agg_method_func_dict[agg_method]
# sets default origin so that "ct1" feature from "build_time_features_df" starts at 0 on training start date
if origin_for_time_vars is None:
origin_for_time_vars = convert_date_to_continuous_time(df[time_col][0])
# we calculate time features here which might appear in match_cols and not available in df by default
def add_time_features(df):
time_df = build_time_features_df(dt=df[time_col], conti_year_origin=origin_for_time_vars)
for col in match_cols:
if col not in df.columns:
df[col] = time_df[col].values
return df
df = add_time_features(df=df)
# for value_col in value_cols:
# aggregate w.r.t. given columns in match_cols
agg_dict = {value_col: agg_func for value_col in value_cols}
# we create a coarse prediction by simply aggregating every value column globally
# this is useful for cases where no matching data is available for a given timestamp to be forecasted
pred_df_overall = df.groupby([True]*len(df), as_index=False).agg(agg_dict)
if len(match_cols) == 0:
pred_df = pred_df_overall
else:
pred_df = df.groupby(match_cols, as_index=False).agg(agg_dict)
model = {
"pred_df": pred_df,
"pred_df_overall": pred_df_overall}
def predict(new_df, new_external_regressor_df=None):
"""Predicts for new dataframe (new_df) using the fitted model.
:param new_df: a dataframe of new data which must include the time_col and match_cols
:param new_external_regressor_df: a regressor dataframe if needed
:return: new_df is augmented with predictions for value_cols and returned
"""
new_df = new_df.copy(deep=True)
new_df = add_time_features(df=new_df)
if new_external_regressor_df is not None:
new_df = pd.concat([new_df, new_external_regressor_df])
# if the response columns appear in the new_df columns, we take them out to prevent issues in aggregation
for col in value_cols:
if col in new_df.columns:
warnings.warn(f"{col} is a response column and appeared in new_df. Hence it was removed.")
del new_df[col]
new_df["temporary_overall_dummy"] = 0
pred_df_overall["temporary_overall_dummy"] = 0
new_df_grouped = pd.merge(new_df, pred_df, on=match_cols, how="left")
new_df_overall = pd.merge(new_df, pred_df_overall, on=["temporary_overall_dummy"], how="left")
# when we have missing in the grouped case (which can happen if a level in match_cols didn't appear in train dataset)
# we fall back to the overall case
for col in value_cols:
new_df_grouped.loc[new_df_grouped[col].isnull(), col] = new_df_overall.loc[new_df_grouped[col].isnull(), col]
del new_df_grouped["temporary_overall_dummy"]
return new_df_grouped
def predict_n(fut_time_num, new_external_regressor_df=None):
"""This is the forecast function which can be used to forecast.
It accepts extra predictors if needed in the form of a dataframe: new_external_regressor_df.
:param fut_time_num: number of needed future values
:param new_external_regressor_df: extra predictors if available
"""
# we create the future time grid
date_list = pd.date_range(
start=max_timestamp + pd.Timedelta(grid_size_str),
periods=fut_time_num,
freq=grid_size_str).tolist()
fut_df = pd.DataFrame({time_col: date_list})
return predict(fut_df, new_external_regressor_df=new_external_regressor_df)
return {"model": model, "predict": predict, "predict_n": predict_n} | Fits a basic forecast model which is aggregate based. As an example for an hourly time series we can assign the value of the most recent three weeks at the same time of the week as forecast. This works for multiple responses passed as a list in "value_cols". Also we do not require the timestamps to be regular and for example dataframe can have missing timestamps. :param df: the dataframe which includes the training data, the value_cols and match_cols if needed :param time_col: the column of the dataframe which includes the timestamps of the series :param value_cols: the response columns for which forecast is desired :param agg_method: a string which specifies the aggregation method. Options are "mean": the mean of the values at timestamps which match with desired time on match_cols "median": the median of the values at timestamps which match with desired time on match_cols "min": the min of the values at timestamps which match with desired time on match_cols "max": the max of the values at timestamps which match with desired time on match_cols "most_recent": the mean of "recent_k" (given in last argument of the function) values matching with desired time on match_cols :param agg_func: the aggregation function needed for aggregating w.r.t "match_cols". This is needed if agg_method is not available. :param grid_size_str: the expected time increment. If not provided it is inferred. :param match_cols: the variables used for grouping in aggregation :param origin_for_time_vars: the time origin for continuous time variables :param recent_k: the number of most recent timestamps to consider for aggregation :return: A dictionary consisting of a "model" and a "predict" function. The "model" object is simply a dictionary of two items (dataframes). First item is an aggregated dataframe of "value_cols" w.r.t "match_cols": "pred_df" Second item is an aggregated dataframe across all data: "pred_df_overall". This is useful if a level in match_cols didn't appear in train dataset, therefore in that case we fall back to overall prediction The "predict" is a function which performs prediction for new data The "predict_n" is a function which predicts the future for any given number of steps specified |
167,369 | import warnings
import pandas as pd
from greykite.common import constants as cst
from greykite.common.constants import EVENT_DF_DATE_COL
from greykite.common.constants import EVENT_DF_LABEL_COL
from greykite.common.constants import EVENT_INDICATOR
from greykite.common.features.timeseries_features import add_event_window_multi
from greykite.common.features.timeseries_features import get_fourier_col_name
from greykite.common.features.timeseries_features import get_holidays
from greykite.common.python_utils import split_offset_str
def get_fourier_col_name(k, col_name, function_name="sin", seas_name=None):
"""Returns column name corresponding to a particular fourier term, as returned by fourier_series_fcn
:param k: int
fourier term
:param col_name: str
column in the dataframe used to generate fourier series
:param function_name: str
sin or cos
:param seas_name: strcols_interact
appended to new column names added for fourier terms
:return: str
column name in DataFrame returned by fourier_series_fcn
"""
# patsy doesn't allow "." in formula term. Replace "." with "_" rather than quoting "Q()" all fourier terms
name = f"{function_name}{k:.0f}_{col_name}"
if seas_name is not None:
name = f"{name}_{seas_name}"
return name
The provided code snippet includes necessary dependencies for implementing the `cols_interact` function. Write a Python function `def cols_interact( static_col, fs_name, fs_order, fs_seas_name=None)` to solve the following problem:
Returns all interactions between static_col and fourier series up to specified order :param static_col: column to interact with fourier series. can be an arbitrary patsy model term e.g. "ct1", "C(woy)", "is_weekend:Q('events_Christmas Day')" :param fs_name: column the fourier series is generated from, same as col_name in fourier_series_fcn :param fs_order: int generate interactions up to this order. must be <= order in fourier_series_fcn :param fs_seas_name: str same as seas_name in fourier_series_fcn :return: list[str] interaction terms to include in patsy model formula
Here is the function:
def cols_interact(
static_col,
fs_name,
fs_order,
fs_seas_name=None):
"""Returns all interactions between static_col and fourier series up to specified order
:param static_col:
column to interact with fourier series. can be an arbitrary patsy model term
e.g. "ct1", "C(woy)", "is_weekend:Q('events_Christmas Day')"
:param fs_name:
column the fourier series is generated from, same as col_name in fourier_series_fcn
:param fs_order: int
generate interactions up to this order. must be <= order in fourier_series_fcn
:param fs_seas_name: str
same as seas_name in fourier_series_fcn
:return: list[str]
interaction terms to include in patsy model formula
"""
interaction_columns = [None] * fs_order * 2
for i in range(fs_order):
k = i + 1
sin_col_name = get_fourier_col_name(
k,
fs_name,
function_name="sin",
seas_name=fs_seas_name)
cos_col_name = get_fourier_col_name(
k,
fs_name,
function_name="cos",
seas_name=fs_seas_name)
interaction_columns[2*i] = f"{static_col}:{sin_col_name}"
interaction_columns[2*i + 1] = f"{static_col}:{cos_col_name}"
return interaction_columns | Returns all interactions between static_col and fourier series up to specified order :param static_col: column to interact with fourier series. can be an arbitrary patsy model term e.g. "ct1", "C(woy)", "is_weekend:Q('events_Christmas Day')" :param fs_name: column the fourier series is generated from, same as col_name in fourier_series_fcn :param fs_order: int generate interactions up to this order. must be <= order in fourier_series_fcn :param fs_seas_name: str same as seas_name in fourier_series_fcn :return: list[str] interaction terms to include in patsy model formula |
167,370 | import warnings
import pandas as pd
from greykite.common import constants as cst
from greykite.common.constants import EVENT_DF_DATE_COL
from greykite.common.constants import EVENT_DF_LABEL_COL
from greykite.common.constants import EVENT_INDICATOR
from greykite.common.features.timeseries_features import add_event_window_multi
from greykite.common.features.timeseries_features import get_fourier_col_name
from greykite.common.features.timeseries_features import get_holidays
from greykite.common.python_utils import split_offset_str
def dedup_holiday_dict(holidays_dict):
"""Removes duplicates from get_holidays output
:param holidays_dict: dict(str, pd.DataFrame(EVENT_DF_DATE_COL, EVENT_DF_LABEL_COL))
dictionary from get_holidays
:return:
concatenates rows of all DataFrames in holiday_df
drops duplicate holiday names
"""
result = pd.DataFrame()
for country, country_holiday_df in holidays_dict.items():
result = pd.concat([result, country_holiday_df], axis=0)
result.drop_duplicates(inplace=True)
return result
def split_events_into_dictionaries(
events_df,
events,
date_col=EVENT_DF_DATE_COL,
name_col=EVENT_DF_LABEL_COL,
default_category="Other"):
"""Splits pd.Dataframe(date, holiday) into separate dataframes, one per event
Can be used to create the `daily_event_df_dict` parameter for `forecast_silverkite`.
Each event specified in `events` gets its own effect in the model.
Other events are grouped together and modeled with the same effect
:param events_df: pd.DataFrame with date_col and name_col columns
contains events
:param events: list(str)
names of events in events_df.name_col.unique() to split into separate
dataframes
:param date_col: str, default "date"
column in event_df containing the date
:param name_col: str, default EVENT_DF_LABEL_COL
column in event_df containing the event name
:param default_category: str
name of default event
:return: dict(label: pd.Dataframe(date_col, name_col))
with keys = events + [default_category]
name_col column has a constant value = EVENT_INDICATOR
"""
result = {}
# separates rows corresponding to each event into their own dataframe
for event_name in events:
event_df = events_df[events_df[name_col] == event_name].copy()
if event_df.shape[0] > 0:
event_df[name_col] = EVENT_INDICATOR # All dates in this df are for the event
event_key = event_name.replace("'", "") # ensures patsy module can parse column name in formula
result[event_key] = event_df.drop_duplicates().reset_index(drop=True)
else:
warnings.warn(
f"Requested holiday '{event_name}' does not occur in the provided countries")
# groups other events into the same bucket
other_df = events_df[~events_df[name_col].isin(events)].copy()
if other_df.shape[0] > 0:
other_df[name_col] = EVENT_INDICATOR
default_category = default_category.replace("'", "")
result[default_category] = other_df.drop_duplicates().reset_index(drop=True)
# there must be no duplicated dates in each DataFrame
for k, df in result.items():
assert not any(df[date_col].duplicated())
return result
EVENT_DF_DATE_COL = "date"
EVENT_DF_LABEL_COL = "event_name"
def get_holidays(countries, year_start, year_end):
"""This function extracts a holiday data frame for the period of interest
[year_start to year_end] for the given countries.
This is done using the holidays libraries in pypi:holidays-ext
Parameters
----------
countries : `list` [`str`]
countries for which we need holidays
year_start : `int`
first year of interest, inclusive
year_end : `int`
last year of interest, inclusive
Returns
-------
holiday_df_dict : `dict` [`str`, `pandas.DataFrame`]
- key: country name
- value: data frame with holidays for that country
Each data frame has two columns: EVENT_DF_DATE_COL, EVENT_DF_LABEL_COL
"""
country_holiday_dict = {}
year_list = list(range(year_start, year_end + 1))
country_holidays = get_hdays.get_holiday(
country_list=countries,
years=year_list
)
for country, holidays in country_holidays.items():
country_df = pd.DataFrame({
cst.EVENT_DF_DATE_COL: list(holidays.keys()),
cst.EVENT_DF_LABEL_COL: list(holidays.values())})
# Replaces any occurrence of "/" with ", " in order to avoid saving / loading error in
# `~greykite.framework.templates.pickle_utils` because a holiday name can be the key
# of a dictionary that will be used as directory name.
# For example, "Easter Monday [England/Wales/Northern Ireland]" will be casted to
# "Easter Monday [England, Wales, Northern Ireland]".
country_df[cst.EVENT_DF_LABEL_COL] = country_df[cst.EVENT_DF_LABEL_COL].str.replace("/", ", ")
country_df[cst.EVENT_DF_DATE_COL] = pd.to_datetime(country_df[cst.EVENT_DF_DATE_COL])
country_holiday_dict[country] = country_df
return country_holiday_dict
def add_event_window_multi(
event_df_dict,
time_col,
label_col,
time_delta="1D",
pre_num=1,
post_num=1,
pre_post_num_dict=None):
"""For a given dictionary of events data frames with a time_col and label_col
it adds shifted events prior and after the given events
For example if the event data frame includes the row '2019-12-25, Christmas' as a row
the function will produce dataframes with the events '2019-12-24, Christmas' and '2019-12-26, Christmas' if
pre_num and post_num are 1 or more.
Parameters
----------
event_df_dict: `dict` [`str`, `pandas.DataFrame`]
A dictionary of events data frames
with each having two columns: ``time_col`` and ``label_col``.
time_col: `str`
The column with the timestamp of the events.
This can be daily but does not have to be.
label_col : `str`
The column with labels for the events.
time_delta : `str`, default "1D"
The amount of the shift for each unit specified by a string
e.g. '1D' stands for one day delta
pre_num : `int`, default 1
The number of events to be added prior to the given event for each event in df.
post_num: `int`, default 1
The number of events to be added after to the given event for each event in df.
pre_post_num_dict : `dict` [`str`, (`int`, `int`)] or None, default None
Optionally override ``pre_num`` and ``post_num`` for each key in ``event_df_dict``.
For example, if ``event_df_dict`` has keys "US" and "India", this parameter
can be set to ``pre_post_num_dict = {"US": [1, 3], "India": [1, 2]}``,
denoting that the "US" ``pre_num`` is 1 and ``post_num`` is 3, and "India" ``pre_num`` is 1
and ``post_num`` is 2. Keys not specified by ``pre_post_num_dict`` use the default given by
``pre_num`` and ``post_num``.
Returns
-------
df : `dict` [`str`, `pandas.DataFrame`]
A dictionary of dataframes for each needed shift. For example if pre_num=2 and post_num=3.
2 + 3 = 5 data frames will be stored in the return dictionary.
"""
if pre_post_num_dict is None:
pre_post_num_dict = {}
shifted_df_dict = {}
for event_df_key, event_df in event_df_dict.items():
if event_df_key in pre_post_num_dict.keys():
pre_num0 = pre_post_num_dict[event_df_key][0]
post_num0 = pre_post_num_dict[event_df_key][1]
else:
pre_num0 = pre_num
post_num0 = post_num
df_dict0 = add_event_window(
df=event_df,
time_col=time_col,
label_col=label_col,
time_delta=time_delta,
pre_num=pre_num0,
post_num=post_num0,
events_name=event_df_key)
shifted_df_dict.update(df_dict0)
return shifted_df_dict
The provided code snippet includes necessary dependencies for implementing the `generate_holiday_events` function. Write a Python function `def generate_holiday_events( countries, holidays_to_model_separately, year_start, year_end, pre_num, post_num, pre_post_num_dict=None, default_category="Other")` to solve the following problem:
Returns holidays within the countries between ``year_start`` and ``year_end``. Creates a separate key, value for each item in ``holidays_to_model_separately``. The rest are grouped together. Useful when multiple countries share the same holiday (e.g. New Year's Day), to model a single effect for that holiday. Parameters ---------- countries : `list` [`str`] Countries of interest. holidays_to_model_separately : `list` [`str`] Holidays to model. year_start: `int` Start year for holidays. year_end: `int` Ending year for holidays. pre_num: `int` Days to model a separate effect prior to each holiday post_num: `int` Days to model a separate effect after each holiday. pre_post_num_dict : `dict` [`str`, (`int`, `int`)] or None, default None Overrides ``pre_num`` and ``post_num`` for each holiday in ``holidays_to_model_separately``. For example, if ``holidays_to_model_separately`` contains "Thanksgiving" and "Labor Day", this parameter can be set to ``{"Thanksgiving": [1, 3], "Labor Day": [1, 2]}``, denoting that the "Thanksgiving" ``pre_num`` is 1 and ``post_num`` is 3, and "Labor Day" ``pre_num`` is 1 and ``post_num`` is 2. Holidays not specified use the default given by ``pre_num`` and ``post_num``. default_category: `str` Default category name, for holidays in countries not included in ``holidays_to_model_separately``. Returns ------- daily_event_df_dict : `dict` [`str`, `pandas.DataFrame` (EVENT_DF_DATE_COL, EVENT_DF_LABEL_COL)] suitable for use as ``daily_event_df_dict`` parameter in ``forecast_silverkite``
Here is the function:
def generate_holiday_events(
countries,
holidays_to_model_separately,
year_start,
year_end,
pre_num,
post_num,
pre_post_num_dict=None,
default_category="Other"):
"""Returns holidays within the countries between ``year_start`` and ``year_end``.
Creates a separate key, value for each item in ``holidays_to_model_separately``.
The rest are grouped together.
Useful when multiple countries share the same holiday (e.g. New Year's Day),
to model a single effect for that holiday.
Parameters
----------
countries : `list` [`str`]
Countries of interest.
holidays_to_model_separately : `list` [`str`]
Holidays to model.
year_start: `int`
Start year for holidays.
year_end: `int`
Ending year for holidays.
pre_num: `int`
Days to model a separate effect prior to each holiday
post_num: `int`
Days to model a separate effect after each holiday.
pre_post_num_dict : `dict` [`str`, (`int`, `int`)] or None, default None
Overrides ``pre_num`` and ``post_num`` for each holiday in
``holidays_to_model_separately``.
For example, if ``holidays_to_model_separately`` contains "Thanksgiving" and "Labor Day",
this parameter can be set to ``{"Thanksgiving": [1, 3], "Labor Day": [1, 2]}``,
denoting that the "Thanksgiving" ``pre_num`` is 1 and ``post_num`` is 3, and "Labor Day"
``pre_num`` is 1 and ``post_num`` is 2.
Holidays not specified use the default given by ``pre_num`` and ``post_num``.
default_category: `str`
Default category name, for holidays in countries not included
in ``holidays_to_model_separately``.
Returns
-------
daily_event_df_dict : `dict` [`str`, `pandas.DataFrame` (EVENT_DF_DATE_COL, EVENT_DF_LABEL_COL)]
suitable for use as ``daily_event_df_dict`` parameter in ``forecast_silverkite``
"""
# retrieves separate DataFrame for each country, with list of holidays
holidays_dict = get_holidays(
countries,
year_start=year_start,
year_end=year_end)
if len(holidays_dict) == 0: # requested holidays are not found the countries
daily_event_df_dict = None
else:
# merges country DataFrames, removes duplicate holidays
holiday_df = dedup_holiday_dict(holidays_dict)
# creates separate DataFrame for each holiday
daily_event_df_dict = split_events_into_dictionaries(
holiday_df,
holidays_to_model_separately,
default_category=default_category)
# Removes "'" from keys in `pre_post_num_dict` because they are
# removed from holiday names by ``split_events_into_dictionaries``.
if pre_post_num_dict:
# ``.copy()`` is used below to avoid altering the dictionary keys within iteration on same keys
keys = pre_post_num_dict.copy().keys()
for key in keys:
new_key = key.replace("'", "")
if key not in daily_event_df_dict:
pre_post_num_dict[new_key] = pre_post_num_dict.pop(key)
if new_key not in daily_event_df_dict:
warnings.warn(
f"Requested holiday '{new_key}' is not valid. Valid holidays are: "
f"{list(daily_event_df_dict.keys())}", UserWarning)
shifted_event_dict = add_event_window_multi(
event_df_dict=daily_event_df_dict,
time_col=EVENT_DF_DATE_COL,
label_col=EVENT_DF_LABEL_COL,
time_delta="1D",
pre_num=pre_num,
post_num=post_num,
pre_post_num_dict=pre_post_num_dict)
daily_event_df_dict.update(shifted_event_dict)
return daily_event_df_dict | Returns holidays within the countries between ``year_start`` and ``year_end``. Creates a separate key, value for each item in ``holidays_to_model_separately``. The rest are grouped together. Useful when multiple countries share the same holiday (e.g. New Year's Day), to model a single effect for that holiday. Parameters ---------- countries : `list` [`str`] Countries of interest. holidays_to_model_separately : `list` [`str`] Holidays to model. year_start: `int` Start year for holidays. year_end: `int` Ending year for holidays. pre_num: `int` Days to model a separate effect prior to each holiday post_num: `int` Days to model a separate effect after each holiday. pre_post_num_dict : `dict` [`str`, (`int`, `int`)] or None, default None Overrides ``pre_num`` and ``post_num`` for each holiday in ``holidays_to_model_separately``. For example, if ``holidays_to_model_separately`` contains "Thanksgiving" and "Labor Day", this parameter can be set to ``{"Thanksgiving": [1, 3], "Labor Day": [1, 2]}``, denoting that the "Thanksgiving" ``pre_num`` is 1 and ``post_num`` is 3, and "Labor Day" ``pre_num`` is 1 and ``post_num`` is 2. Holidays not specified use the default given by ``pre_num`` and ``post_num``. default_category: `str` Default category name, for holidays in countries not included in ``holidays_to_model_separately``. Returns ------- daily_event_df_dict : `dict` [`str`, `pandas.DataFrame` (EVENT_DF_DATE_COL, EVENT_DF_LABEL_COL)] suitable for use as ``daily_event_df_dict`` parameter in ``forecast_silverkite`` |
167,371 | import math
import warnings
from typing import List
from typing import Optional
import pandas as pd
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.enums import SimpleTimeFrequencyEnum
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
The provided code snippet includes necessary dependencies for implementing the `get_similar_lag` function. Write a Python function `def get_similar_lag(freq_in_days)` to solve the following problem:
For a given frequency, it returns a lag which is likely to be most correlated to the observation at current time. For daily data, this will return 7 and for hourly data it will return 24*7. In general for sub-weekly frequencies, it returns the lag which corresponds to the same time in the last week. For data which is weekly or with frequencies larger than a week, it returns None. Parameters ---------- freq_in_days : `float` The time frequency of the timeseries given in day units. Returns ------- similar_lag : `int` or None The returned lag or None.
Here is the function:
def get_similar_lag(freq_in_days):
"""For a given frequency, it returns a lag which is likely to be most correlated
to the observation at current time.
For daily data, this will return 7 and for hourly data it will return 24*7.
In general for sub-weekly frequencies, it returns the lag which corresponds to
the same time in the last week.
For data which is weekly or with frequencies larger than a week, it returns None.
Parameters
----------
freq_in_days : `float`
The time frequency of the timeseries given in day units.
Returns
-------
similar_lag : `int` or None
The returned lag or None.
"""
similar_lag = None
# Get the number of observations per week
obs_num_per_week = 7 / freq_in_days
if obs_num_per_week > 1:
similar_lag = math.ceil(obs_num_per_week)
return similar_lag | For a given frequency, it returns a lag which is likely to be most correlated to the observation at current time. For daily data, this will return 7 and for hourly data it will return 24*7. In general for sub-weekly frequencies, it returns the lag which corresponds to the same time in the last week. For data which is weekly or with frequencies larger than a week, it returns None. Parameters ---------- freq_in_days : `float` The time frequency of the timeseries given in day units. Returns ------- similar_lag : `int` or None The returned lag or None. |
167,372 | import math
import warnings
from typing import List
from typing import Optional
import pandas as pd
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.enums import SimpleTimeFrequencyEnum
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
class TimeFeaturesEnum(Enum):
"""Time features generated by
`~greykite.common.features.timeseries_features.build_time_features_df`.
The item names are lower-case letters (kept the same as the values) for easier check of existence.
To check if a string s is in this Enum,
use ``s in TimeFeaturesEnum.__dict__["_member_names_"]``.
Direct check of existence ``s in TimeFeaturesEnum`` is deprecated in python 3.8.
"""
# Absolute time features
datetime = "datetime"
date = "date"
year = "year"
year_length = "year_length"
quarter = "quarter"
quarter_start = "quarter_start"
quarter_length = "quarter_length"
month = "month"
month_length = "month_length"
hour = "hour"
minute = "minute"
second = "second"
year_quarter = "year_quarter"
year_month = "year_month"
woy = "woy"
doy = "doy"
doq = "doq"
dom = "dom"
dow = "dow"
str_dow = "str_dow"
str_doy = "str_doy"
is_weekend = "is_weekend"
# Relative time features
year_woy = "year_woy"
month_dom = "month_dom"
year_woy_dow = "year_woy_dow"
woy_dow = "woy_dow"
dow_hr = "dow_hr"
dow_hr_min = "dow_hr_min"
tod = "tod"
tow = "tow"
tom = "tom"
toq = "toq"
toy = "toy"
conti_year = "conti_year"
dow_grouped = "dow_grouped"
# ISO time features
year_iso = "year_iso"
year_woy_iso = "year_woy_iso"
year_woy_dow_iso = "year_woy_dow_iso"
# Continuous time features
ct1 = "ct1"
ct2 = "ct2"
ct3 = "ct3"
ct_sqrt = "ct_sqrt"
ct_root3 = "ct_root3"
us_dst = "us_dst"
eu_dst = "eu_dst"
The provided code snippet includes necessary dependencies for implementing the `get_default_changepoints_dict` function. Write a Python function `def get_default_changepoints_dict( changepoints_method, num_days, forecast_horizon_in_days)` to solve the following problem:
Get a changepoint dictionary based on the number of days in the observed timeseries and forecast horizon length in days to be provided as input to `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`. For the "uniform" method, we place the change points at a distance of ``max(28, forecast_horizon)``. For the "auto" method, we have used some defaults which seem to work for general applications:: changepoints_dict = { "method": "auto", "yearly_seasonality_order": 10, "resample_freq": "7D", "regularization_strength": 0.8, "actual_changepoint_min_distance": "14D", "potential_changepoint_distance": "7D", "no_changepoint_distance_from_end": "14D"} If the length of data is smaller than ``2*max(28, forecast_horizon)``, the function will return None for all methods. Parameters ---------- changepoints_method : `str` The method to locate changepoints. Valid options: - "uniform". Places changepoints evenly spaced changepoints to allow growth to change. The distance between the uniform change points is set to be ``max(28, forecast_horizon)`` - "auto". Automatically detects change points. For configuration, see `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_trend_changepoints` For more details for both methods, also check the documentation for `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`. num_days : `int` Number of days appearing in the observed timeseries. forecast_horizon_in_days : `float` The length of the forecast horizon in days. Returns ------- changepoints_dict : `dict` or None A dictionary with change points information to be used as input to `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`. See that function's documentation for more details.
Here is the function:
def get_default_changepoints_dict(
changepoints_method,
num_days,
forecast_horizon_in_days):
"""Get a changepoint dictionary based on the number of days in the observed
timeseries and forecast horizon length in days to be provided as input to
`~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`.
For the "uniform" method, we place the change points at a distance of
``max(28, forecast_horizon)``.
For the "auto" method, we have used some defaults which seem to work for general
applications::
changepoints_dict = {
"method": "auto",
"yearly_seasonality_order": 10,
"resample_freq": "7D",
"regularization_strength": 0.8,
"actual_changepoint_min_distance": "14D",
"potential_changepoint_distance": "7D",
"no_changepoint_distance_from_end": "14D"}
If the length of data is smaller than ``2*max(28, forecast_horizon)``,
the function will return None for all methods.
Parameters
----------
changepoints_method : `str`
The method to locate changepoints.
Valid options:
- "uniform". Places changepoints evenly spaced changepoints to allow
growth to change. The distance between the uniform change points is
set to be ``max(28, forecast_horizon)``
- "auto". Automatically detects change points.
For configuration, see
`~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_trend_changepoints`
For more details for both methods, also check the documentation for
`~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`.
num_days : `int`
Number of days appearing in the observed timeseries.
forecast_horizon_in_days : `float`
The length of the forecast horizon in days.
Returns
-------
changepoints_dict : `dict` or None
A dictionary with change points information to be used as input to
`~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`.
See that function's documentation for more details.
"""
changepoints_dict = None
# A reasonable distance defined based on ``forecast_horizon``
# Here the minimum is set at 28 days
uniform_distance = max(28, forecast_horizon_in_days)
# Number of change points for "uniform"
# Also if this number is zero both methods will return `None`
changepoint_num = num_days // uniform_distance - 1
if changepoint_num > 0:
if changepoints_method == "uniform":
changepoints_dict = {
"method": "uniform",
"n_changepoints": changepoint_num,
"continuous_time_col": TimeFeaturesEnum.ct1.value,
"growth_func": lambda x: x}
elif changepoints_method == "auto":
changepoints_dict = {
"method": "auto",
"yearly_seasonality_order": 10,
"resample_freq": "7D",
"regularization_strength": 0.8,
"actual_changepoint_min_distance": "14D",
"potential_changepoint_distance": "7D",
"no_changepoint_distance_from_end": "14D"}
return changepoints_dict | Get a changepoint dictionary based on the number of days in the observed timeseries and forecast horizon length in days to be provided as input to `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`. For the "uniform" method, we place the change points at a distance of ``max(28, forecast_horizon)``. For the "auto" method, we have used some defaults which seem to work for general applications:: changepoints_dict = { "method": "auto", "yearly_seasonality_order": 10, "resample_freq": "7D", "regularization_strength": 0.8, "actual_changepoint_min_distance": "14D", "potential_changepoint_distance": "7D", "no_changepoint_distance_from_end": "14D"} If the length of data is smaller than ``2*max(28, forecast_horizon)``, the function will return None for all methods. Parameters ---------- changepoints_method : `str` The method to locate changepoints. Valid options: - "uniform". Places changepoints evenly spaced changepoints to allow growth to change. The distance between the uniform change points is set to be ``max(28, forecast_horizon)`` - "auto". Automatically detects change points. For configuration, see `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_trend_changepoints` For more details for both methods, also check the documentation for `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`. num_days : `int` Number of days appearing in the observed timeseries. forecast_horizon_in_days : `float` The length of the forecast horizon in days. Returns ------- changepoints_dict : `dict` or None A dictionary with change points information to be used as input to `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`. See that function's documentation for more details. |
167,373 | import math
import warnings
from typing import List
from typing import Optional
import pandas as pd
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.enums import SimpleTimeFrequencyEnum
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
class TimeFeaturesEnum(Enum):
"""Time features generated by
`~greykite.common.features.timeseries_features.build_time_features_df`.
The item names are lower-case letters (kept the same as the values) for easier check of existence.
To check if a string s is in this Enum,
use ``s in TimeFeaturesEnum.__dict__["_member_names_"]``.
Direct check of existence ``s in TimeFeaturesEnum`` is deprecated in python 3.8.
"""
# Absolute time features
datetime = "datetime"
date = "date"
year = "year"
year_length = "year_length"
quarter = "quarter"
quarter_start = "quarter_start"
quarter_length = "quarter_length"
month = "month"
month_length = "month_length"
hour = "hour"
minute = "minute"
second = "second"
year_quarter = "year_quarter"
year_month = "year_month"
woy = "woy"
doy = "doy"
doq = "doq"
dom = "dom"
dow = "dow"
str_dow = "str_dow"
str_doy = "str_doy"
is_weekend = "is_weekend"
# Relative time features
year_woy = "year_woy"
month_dom = "month_dom"
year_woy_dow = "year_woy_dow"
woy_dow = "woy_dow"
dow_hr = "dow_hr"
dow_hr_min = "dow_hr_min"
tod = "tod"
tow = "tow"
tom = "tom"
toq = "toq"
toy = "toy"
conti_year = "conti_year"
dow_grouped = "dow_grouped"
# ISO time features
year_iso = "year_iso"
year_woy_iso = "year_woy_iso"
year_woy_dow_iso = "year_woy_dow_iso"
# Continuous time features
ct1 = "ct1"
ct2 = "ct2"
ct3 = "ct3"
ct_sqrt = "ct_sqrt"
ct_root3 = "ct_root3"
us_dst = "us_dst"
eu_dst = "eu_dst"
class SimpleTimeFrequencyEnum(Enum):
"""Provides default properties (horizon, seasonality) for various time frequencies.
Used to define default values based on the closest frequency to the input data.
"""
# default_horizon: how far ahead to forecast
# seconds_per_observation: approximation of the period of each observation (in seconds)
# valid_seas: valid seasonalities
Frequency = namedtuple("Frequency", "default_horizon, seconds_per_observation, valid_seas")
# minutely
MINUTE = Frequency(
default_horizon=60,
seconds_per_observation=TimeEnum.ONE_MINUTE_IN_SECONDS.value,
valid_seas={SeasonalityEnum.DAILY_SEASONALITY.name,
SeasonalityEnum.WEEKLY_SEASONALITY.name,
SeasonalityEnum.MONTHLY_SEASONALITY.name,
SeasonalityEnum.QUARTERLY_SEASONALITY.name,
SeasonalityEnum.YEARLY_SEASONALITY.name})
# hourly
HOUR = Frequency(
default_horizon=24,
seconds_per_observation=TimeEnum.ONE_HOUR_IN_SECONDS.value,
valid_seas={SeasonalityEnum.DAILY_SEASONALITY.name,
SeasonalityEnum.WEEKLY_SEASONALITY.name,
SeasonalityEnum.MONTHLY_SEASONALITY.name,
SeasonalityEnum.QUARTERLY_SEASONALITY.name,
SeasonalityEnum.YEARLY_SEASONALITY.name})
# daily
# monthly seasonality is not used for hourly/daily data to avoid over-specification
DAY = Frequency(
default_horizon=30,
seconds_per_observation=TimeEnum.ONE_DAY_IN_SECONDS.value,
valid_seas={SeasonalityEnum.WEEKLY_SEASONALITY.name,
SeasonalityEnum.MONTHLY_SEASONALITY.name,
SeasonalityEnum.QUARTERLY_SEASONALITY.name,
SeasonalityEnum.YEARLY_SEASONALITY.name})
# weekly
WEEK = Frequency(
default_horizon=12,
seconds_per_observation=TimeEnum.ONE_WEEK_IN_SECONDS.value,
valid_seas={SeasonalityEnum.MONTHLY_SEASONALITY.name,
SeasonalityEnum.QUARTERLY_SEASONALITY.name,
SeasonalityEnum.YEARLY_SEASONALITY.name})
# monthly
MONTH = Frequency(
default_horizon=12,
seconds_per_observation=TimeEnum.ONE_MONTH_IN_SECONDS.value,
valid_seas={SeasonalityEnum.QUARTERLY_SEASONALITY.name,
SeasonalityEnum.YEARLY_SEASONALITY.name})
# quarterly
QUARTER = Frequency(
default_horizon=12,
seconds_per_observation=TimeEnum.ONE_QUARTER_IN_SECONDS.value,
valid_seas={SeasonalityEnum.YEARLY_SEASONALITY.name})
# yearly
YEAR = Frequency(
default_horizon=2,
seconds_per_observation=TimeEnum.ONE_YEAR_IN_SECONDS.value,
valid_seas={})
# longer than yearly
MULTIYEAR = Frequency(
default_horizon=2,
seconds_per_observation=TimeEnum.ONE_YEAR_IN_SECONDS.value * 2, # not used anywhere, just a placeholder
valid_seas={})
The provided code snippet includes necessary dependencies for implementing the `get_silverkite_uncertainty_dict` function. Write a Python function `def get_silverkite_uncertainty_dict( uncertainty, simple_freq=SimpleTimeFrequencyEnum.DAY.name, coverage=None)` to solve the following problem:
Returns an uncertainty_dict for `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast` input parameter: uncertainty_dict. The logic is as follows: - If ``uncertainty`` is passed as dict: - If ``quantiles`` are not passed through ``uncertainty`` we fill them using `coverage`. - If ``coverage`` also missing or quantiles calculated in two ways (via ``uncertainty["params"]["quantiles"]`` and ``coverage``) do not match, we throw Exceptions - If ``uncertainty=="auto"``: - We provide defaults based on time frequency of data. - Specify ``uncertainty["params"]["quantiles"]`` based on ``coverage`` if provided, otherwise the default coverage is 0.95. Parameters ---------- uncertainty : `str` or `dict` or None It specifies what method should be used for uncertainty. If a dict is passed then it is directly returned to be passed to `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast` as `uncertainty_dict`. If "auto", it builds a generic dict depending on frequency. - For frequencies less than or equal to one day it sets `conditional_cols` to be ["dow_hr"]. - Otherwise it sets the conditional_cols to be `None` If None and `coverage` is None, the upper/lower predictions are not returned simple_freq : `str`, optional SimpleTimeFrequencyEnum member that best matches the input data frequency according to `get_simple_time_frequency_from_period` coverage : `float` or None, optional Intended coverage of the prediction bands (0.0 to 1.0) If None and `uncertainty` is None, the upper/lower predictions are not returned Returns ------- uncertainty : `dict` or None An uncertainty dict to be used as input to `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`. See that function's docstring for more details.
Here is the function:
def get_silverkite_uncertainty_dict(
uncertainty,
simple_freq=SimpleTimeFrequencyEnum.DAY.name,
coverage=None):
"""Returns an uncertainty_dict for
`~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`
input parameter: uncertainty_dict.
The logic is as follows:
- If ``uncertainty`` is passed as dict:
- If ``quantiles`` are not passed through ``uncertainty`` we fill them
using `coverage`.
- If ``coverage`` also missing or quantiles calculated
in two ways (via ``uncertainty["params"]["quantiles"]`` and ``coverage``)
do not match, we throw Exceptions
- If ``uncertainty=="auto"``:
- We provide defaults based on time frequency of data.
- Specify ``uncertainty["params"]["quantiles"]`` based on
``coverage`` if provided, otherwise the default coverage is 0.95.
Parameters
----------
uncertainty : `str` or `dict` or None
It specifies what method should be used for uncertainty.
If a dict is passed then it is directly returned to be passed to
`~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast` as `uncertainty_dict`.
If "auto", it builds a generic dict depending on frequency.
- For frequencies less than or equal to one day it sets
`conditional_cols` to be ["dow_hr"].
- Otherwise it sets the conditional_cols to be `None`
If None and `coverage` is None, the upper/lower predictions are not returned
simple_freq : `str`, optional
SimpleTimeFrequencyEnum member that best matches the input data frequency
according to `get_simple_time_frequency_from_period`
coverage : `float` or None, optional
Intended coverage of the prediction bands (0.0 to 1.0)
If None and `uncertainty` is None, the upper/lower predictions are not returned
Returns
-------
uncertainty : `dict` or None
An uncertainty dict to be used as input to
`~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`.
See that function's docstring for more details.
"""
frequency = SimpleTimeFrequencyEnum[simple_freq].value
# boolean to determine if freq is longer than one day
freq_is_longer_than_day = (
frequency.seconds_per_observation
> SimpleTimeFrequencyEnum.DAY.value.seconds_per_observation)
uncertainty_dict = None
# if both `uncertainty` and `coverage` are None, we return None
if uncertainty is None and coverage is None:
return None
# checking if coverage input is sensible
if coverage is not None and (coverage < 0 or coverage > 1):
raise ValueError("coverage must be between 0 and 1")
# if only coverage is provided, consider uncertainty to be "auto"
if coverage is not None and uncertainty is None:
uncertainty = "auto"
# The case where `uncertainty` is input as a dict
# We check if quantiles are passed through `uncertainty`
# If not, we use `coverage` to fill them in
# If quantiles are passed in `uncertainty` and inferrable from `coverage`:
# and they are inconsistent, we throw an Exception
if isinstance(uncertainty, dict):
uncertainty_dict = uncertainty
# boolean to check if quantiles are passed through uncertainty
try:
quantiles_specified = (uncertainty["params"]["quantiles"] is not None)
except KeyError:
quantiles_specified = False
if "params" not in uncertainty_dict:
uncertainty_dict["params"] = {}
if quantiles_specified:
quantiles = uncertainty["params"]["quantiles"]
# If quantiles are specified, we do some sanity checks on their values:
# We give warnings if more than two quantiles were passed
# or if they are not symmetric i.e. first quantiles distance to zero
# is not the same as last quantile distance to 1
# We throw exceptions if quantiles are not increasing
# or if `coverage` is also passed and inconsistent with `quantiles`
if len(quantiles) > 2:
warnings.warn(
"More than two quantiles are passed in `uncertainty`."
" Confidence intervals will be based on"
" the first (lower limit) and last (upper limit) quantile",
Warning)
coverage_via_uncertainty = quantiles[-1] - quantiles[0]
if coverage_via_uncertainty <= 0:
raise ValueError(
"`quantiles` is expected to be an increasing sequence"
" of at least two elements."
f"These quantiles were passed: quantiles = {quantiles}")
if round(quantiles[-1], 3) != round(1 - quantiles[0], 3):
warnings.warn(
"1 - (quantiles upper limit) is not equal to (quantiles lower limit)"
" (lack of symmetry)."
f" Asymmetric quantiles: {quantiles} were used.",
Warning)
if coverage is not None:
# The case where quantiles are both provided through `uncertainty`
# and inferrable using `coverage`
# We check for conflict in coverage specification
if round(coverage_via_uncertainty, 3) != round(coverage, 3):
raise ValueError(
"Coverage is specified/inferred both via `coverage` and via `uncertainty` input"
" and values do not match."
f" Coverage specified via `coverage`: {round(coverage, 3)}."
f" Coverage inferred via `uncertainty`: {round(coverage_via_uncertainty, 2)}.")
if not quantiles_specified:
if coverage is None:
raise ValueError(
"`quantiles` are not specified in `uncertainty`"
" and `coverage` is not provided to infer them")
else:
# The case where quantiles is not provided through `uncertainty`
# but coverage is passed
q1 = (1 - coverage)/2
q2 = 1 - q1
uncertainty_dict["params"]["quantiles"] = [q1, q2]
# The case where `uncertainty` is passed as "auto"
# The auto case conditions data on `dow_hr` which represents day of week and hour
# for data with frequency less than or equal to a day (e.g. hourly, daily)
# note that for daily case this works too as dow_hr will only depend on dow
if uncertainty == "auto":
if not freq_is_longer_than_day:
uncertainty_dict = {
"uncertainty_method": "simple_conditional_residuals",
"params": {
"conditional_cols": [TimeFeaturesEnum.dow_hr.value],
"quantiles": [0.025, 0.975],
"quantile_estimation_method": "normal_fit",
"sample_size_thresh": 5,
"small_sample_size_method": "std_quantiles",
"small_sample_size_quantile": 0.98}}
else:
uncertainty_dict = {
"uncertainty_method": "simple_conditional_residuals",
"params": {
"conditional_cols": None,
"quantiles": [0.025, 0.975],
"quantile_estimation_method": "normal_fit",
"sample_size_thresh": 5,
"small_sample_size_method": "std_quantiles",
"small_sample_size_quantile": 0.98}}
# if coverage is provided the quantiles are overridden in auto
# we do not give warnings as it is the auto case and
# user expects using the coverage provided
if coverage is not None:
q1 = (1 - coverage)/2
q2 = 1 - q1
uncertainty_dict["params"]["quantiles"] = [q1, q2]
return uncertainty_dict | Returns an uncertainty_dict for `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast` input parameter: uncertainty_dict. The logic is as follows: - If ``uncertainty`` is passed as dict: - If ``quantiles`` are not passed through ``uncertainty`` we fill them using `coverage`. - If ``coverage`` also missing or quantiles calculated in two ways (via ``uncertainty["params"]["quantiles"]`` and ``coverage``) do not match, we throw Exceptions - If ``uncertainty=="auto"``: - We provide defaults based on time frequency of data. - Specify ``uncertainty["params"]["quantiles"]`` based on ``coverage`` if provided, otherwise the default coverage is 0.95. Parameters ---------- uncertainty : `str` or `dict` or None It specifies what method should be used for uncertainty. If a dict is passed then it is directly returned to be passed to `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast` as `uncertainty_dict`. If "auto", it builds a generic dict depending on frequency. - For frequencies less than or equal to one day it sets `conditional_cols` to be ["dow_hr"]. - Otherwise it sets the conditional_cols to be `None` If None and `coverage` is None, the upper/lower predictions are not returned simple_freq : `str`, optional SimpleTimeFrequencyEnum member that best matches the input data frequency according to `get_simple_time_frequency_from_period` coverage : `float` or None, optional Intended coverage of the prediction bands (0.0 to 1.0) If None and `uncertainty` is None, the upper/lower predictions are not returned Returns ------- uncertainty : `dict` or None An uncertainty dict to be used as input to `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`. See that function's docstring for more details. |
167,374 | import math
import warnings
from typing import List
from typing import Optional
import pandas as pd
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.enums import SimpleTimeFrequencyEnum
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
def get_default_origin_for_time_vars(df, time_col):
"""Sets default value for origin_for_time_vars
Parameters
----------
df : `pandas.DataFrame`
Training data. A data frame which includes the timestamp and value columns
time_col : `str`
The column name in `df` representing time for the time series data.
Returns
-------
dt_continuous_time : `float`
The time origin used to create continuous variables for time
"""
date = pd.to_datetime(df[time_col].iloc[0])
return convert_date_to_continuous_time(date)
def build_time_features_df(
dt,
conti_year_origin,
add_dst_info=True):
"""This function gets a datetime-like vector and creates new columns containing temporal
features useful for time series analysis and forecasting e.g. year, week of year, etc.
Parameters
----------
dt : array-like (1-dimensional)
A vector of datetime-like values
conti_year_origin : `float`
The origin used for creating continuous time which is in years unit.
add_dst_info : `bool`, default True
Determines if daylight saving columns for US and Europe should be added.
Returns
-------
time_features_df : `pandas.DataFrame`
Dataframe with the following time features.
* "datetime": `datetime.datetime` object, a combination of date and a time
* "date": `datetime.date` object, date with the format (year, month, day)
* "year": integer, year of the date e.g. 2018
* "year_length": integer, number of days in the year e.g. 365 or 366
* "quarter": integer, quarter of the date, 1, 2, 3, 4
* "quarter_start": `pandas.DatetimeIndex`, date of beginning of the current quarter
* "quarter_length": integer, number of days in the quarter, 90/91 for Q1, 91 for Q2, 92 for Q3 and Q4
* "month": integer, month of the year, January=1, February=2, ..., December=12
* "month_length": integer, number of days in the month, 28/ 29/ 30/ 31
* "woy": integer, ISO 8601 week of the year where a week starts from Monday, 1, 2, ..., 53
* "doy": integer, ordinal day of the year, 1, 2, ..., year_length
* "doq": integer, ordinal day of the quarter, 1, 2, ..., quarter_length
* "dom": integer, ordinal day of the month, 1, 2, ..., month_length
* "dow": integer, day of the week, Monday=1, Tuesday=2, ..., Sunday=7
* "str_dow": string, day of the week as a string e.g. "1-Mon", "2-Tue", ..., "7-Sun"
* "str_doy": string, day of the year e.g. "2020-03-20" for March 20, 2020
* "hour": integer, discrete hours of the datetime, 0, 1, ..., 23
* "minute": integer, minutes of the datetime, 0, 1, ..., 59
* "second": integer, seconds of the datetime, 0, 1, ..., 3599
* "year_month": string, (year, month) e.g. "2020-03" for March 2020
* "year_woy": string, (year, week of year) e.g. "2020_42" for 42nd week of 2020
* "month_dom": string, (month, day of month) e.g. "02/20" for February 20th
* "year_woy_dow": string, (year, week of year, day of week) e.g. "2020_03_6" for Saturday of 3rd week in 2020
* "woy_dow": string, (week of year, day of week) e.g. "03_6" for Saturday of 3rd week
* "dow_hr": string, (day of week, hour) e.g. "4_09" for 9am on Thursday
* "dow_hr_min": string, (day of week, hour, minute) e.g. "4_09_10" for 9:10am on Thursday
* "tod": float, time of day, continuous, 0.0 to 24.0
* "tow": float, time of week, continuous, 0.0 to 7.0
* "tom": float, standardized time of month, continuous, 0.0 to 1.0
* "toq": float, time of quarter, continuous, 0.0 to 1.0
* "toy": float, standardized time of year, continuous, 0.0 to 1.0
* "conti_year": float, year in continuous time, eg 2018.5 means middle of the year 2018
* "is_weekend": boolean, weekend indicator, True for weekend, else False
* "dow_grouped": string, Monday-Thursday=1234-MTuWTh, Friday=5-Fri, Saturday=6-Sat, Sunday=7-Sun
* "ct1": float, linear growth based on conti_year_origin, -infinity to infinity
* "ct2": float, signed quadratic growth, -infinity to infinity
* "ct3": float, signed cubic growth, -infinity to infinity
* "ct_sqrt": float, signed square root growth, -infinity to infinity
* "ct_root3": float, signed cubic root growth, -infinity to infinity
* "us_dst": bool, determines if the time inside the daylight saving time of US
This column is only generated if ``add_dst_info=True``
* "eu_dst": bool, determines if the time inside the daylight saving time of Europe. This column is only generated if ``add_dst_info=True``
"""
dt = pd.DatetimeIndex(dt)
if len(dt) == 0:
raise ValueError("Length of dt cannot be zero.")
# basic time features
date = dt.date
year = dt.year
year_length = (365.0 + dt.is_leap_year)
quarter = dt.quarter
month = dt.month
month_length = dt.days_in_month
# finds first day of quarter
quarter_start = pd.DatetimeIndex(
dt.year.map(str) + "-" + (3 * quarter - 2).map(int).map(str) + "-01")
next_quarter_start = dt + pd.tseries.offsets.QuarterBegin(startingMonth=1)
quarter_length = (next_quarter_start - quarter_start).days
# finds offset from first day of quarter (rounds down to nearest day)
doq = ((dt - quarter_start) / pd.to_timedelta("1D") + 1).astype(int)
# week of year, "woy", follows ISO 8601:
# - Week 01 is the week with the year's first Thursday in it.
# - A week begins with Monday and ends with Sunday.
# So the week number of the week that overlaps both years, is 1, 52, or 53,
# depending on whether it has more days in the previous year or new year.
# - e.g. Jan 1st, 2018 is Monday. woy of first 8 days = [1, 1, 1, 1, 1, 1, 1, 2]
# - e.g. Jan 1st, 2019 is Tuesday. woy of first 8 days = [1, 1, 1, 1, 1, 1, 2, 2]
# - e.g. Jan 1st, 2020 is Wednesday. woy of first 8 days = [1, 1, 1, 1, 1, 2, 2, 2]
# - e.g. Jan 1st, 2015 is Thursday. woy of first 8 days = [1, 1, 1, 1, 2, 2, 2, 2]
# - e.g. Jan 1st, 2021 is Friday. woy of first 8 days = [53, 53, 53, 1, 1, 1, 1, 1]
# - e.g. Jan 1st, 2022 is Saturday. woy of first 8 days = [52, 52, 1, 1, 1, 1, 1, 1]
# - e.g. Jan 1st, 2023 is Sunday. woy of first 8 days = [52, 1, 1, 1, 1, 1, 1, 1]
woy = dt.strftime("%V").astype(int)
doy = dt.dayofyear
dom = dt.day
dow = dt.strftime("%u").astype(int)
str_dow = dt.strftime("%u-%a") # e.g. 1-Mon, 2-Tue, ..., 7-Sun
hour = dt.hour
minute = dt.minute
second = dt.second
# grouped time feature
year_quarter = dt.strftime("%Y-") + quarter.astype(str) # e.g. 2020-1 for March 2020
str_doy = dt.strftime("%Y-%m-%d") # e.g. 2020-03-20 for March 20, 2020
year_month = dt.strftime("%Y-%m") # e.g. 2020-03 for March 2020
month_dom = dt.strftime("%m/%d") # e.g. 02/20 for February 20th
year_woy = dt.strftime("%Y_%V") # e.g. 2020_42 for 42nd week of 2020
year_woy_dow = dt.strftime("%Y_%V_%u") # e.g. 2020_03_6 for Saturday of 3rd week in 2020
woy_dow = dt.strftime("%W_%u") # e.g. 03_6 for Saturday of 3rd week
dow_hr = dt.strftime("%u_%H") # e.g. 4_09 for 9am on Thursday
dow_hr_min = dt.strftime("%u_%H_%M") # e.g. 4_09_10 for 9:10am on Thursday
# iso features https://en.wikipedia.org/wiki/ISO_week_date
# Uses `pd.Index` to avoid overriding the indices in the output df.
year_iso = pd.Index(dt.isocalendar()["year"])
year_woy_iso = pd.Index(year_iso.astype(str) + "_" + dt.strftime("%V"))
year_woy_dow_iso = pd.Index(year_woy_iso + "_" + dt.isocalendar()["day"].astype(str))
# derived time features
tod = hour + (minute / 60.0) + (second / 3600.0)
tow = dow - 1 + (tod / 24.0)
tom = (dom - 1 + (tod / 24.0)) / month_length
toq = (doq - 1 + (tod / 24.0)) / quarter_length
# time of year, continuous, 0.0 to 1.0. e.g. Jan 1, 12 am = 0/365, Jan 2, 12 am = 1/365, ...
# To handle leap years, Feb 28 = 58/365 - 59/365, Feb 29 = 59/365, Mar 1 = 59/365 - 60/365
# offset term is nonzero only in leap years
# doy_offset reduces doy by 1 from from Mar 1st (doy > 60)
doy_offset = (year_length == 366) * 1.0 * (doy > 60)
# tod_offset sets tod to 0 on Feb 29th (doy == 60)
tod_offset = 1 - (year_length == 366) * 1.0 * (doy == 60)
toy = (doy - 1 - doy_offset + (tod / 24.0) * tod_offset) / 365.0
# year of date in continuous time, eg 2018.5 means middle of year 2018
# this is useful for modeling features that do not care about leap year e.g. environmental variables
conti_year = year + (doy - 1 + (tod / 24.0)) / year_length
is_weekend = pd.Series(dow).apply(lambda x: x in [6, 7]).values # weekend indicator
# categorical var with levels (Mon-Thu, Fri, Sat, Sun), could help when training data are sparse.
dow_grouped = pd.Series(str_dow).apply(
lambda x: "1234-MTuWTh" if (x in ["1-Mon", "2-Tue", "3-Wed", "4-Thu"]) else x).values
# growth terms
ct1 = conti_year - conti_year_origin
ct2 = signed_pow(ct1, 2)
ct3 = signed_pow(ct1, 3)
ct_sqrt = signed_pow(ct1, 1/2)
ct_root3 = signed_pow(ct1, 1/3)
# All keys must be added to constants.
features_dict = {
cst.TimeFeaturesEnum.datetime.value: dt,
cst.TimeFeaturesEnum.date.value: date,
cst.TimeFeaturesEnum.year.value: year,
cst.TimeFeaturesEnum.year_length.value: year_length,
cst.TimeFeaturesEnum.quarter.value: quarter,
cst.TimeFeaturesEnum.quarter_start.value: quarter_start,
cst.TimeFeaturesEnum.quarter_length.value: quarter_length,
cst.TimeFeaturesEnum.month.value: month,
cst.TimeFeaturesEnum.month_length.value: month_length,
cst.TimeFeaturesEnum.woy.value: woy,
cst.TimeFeaturesEnum.doy.value: doy,
cst.TimeFeaturesEnum.doq.value: doq,
cst.TimeFeaturesEnum.dom.value: dom,
cst.TimeFeaturesEnum.dow.value: dow,
cst.TimeFeaturesEnum.str_dow.value: str_dow,
cst.TimeFeaturesEnum.str_doy.value: str_doy,
cst.TimeFeaturesEnum.hour.value: hour,
cst.TimeFeaturesEnum.minute.value: minute,
cst.TimeFeaturesEnum.second.value: second,
cst.TimeFeaturesEnum.year_quarter.value: year_quarter,
cst.TimeFeaturesEnum.year_month.value: year_month,
cst.TimeFeaturesEnum.year_woy.value: year_woy,
cst.TimeFeaturesEnum.month_dom.value: month_dom,
cst.TimeFeaturesEnum.year_woy_dow.value: year_woy_dow,
cst.TimeFeaturesEnum.woy_dow.value: woy_dow,
cst.TimeFeaturesEnum.dow_hr.value: dow_hr,
cst.TimeFeaturesEnum.dow_hr_min.value: dow_hr_min,
cst.TimeFeaturesEnum.year_iso.value: year_iso,
cst.TimeFeaturesEnum.year_woy_iso.value: year_woy_iso,
cst.TimeFeaturesEnum.year_woy_dow_iso.value: year_woy_dow_iso,
cst.TimeFeaturesEnum.tod.value: tod,
cst.TimeFeaturesEnum.tow.value: tow,
cst.TimeFeaturesEnum.tom.value: tom,
cst.TimeFeaturesEnum.toq.value: toq,
cst.TimeFeaturesEnum.toy.value: toy,
cst.TimeFeaturesEnum.conti_year.value: conti_year,
cst.TimeFeaturesEnum.is_weekend.value: is_weekend,
cst.TimeFeaturesEnum.dow_grouped.value: dow_grouped,
cst.TimeFeaturesEnum.ct1.value: ct1,
cst.TimeFeaturesEnum.ct2.value: ct2,
cst.TimeFeaturesEnum.ct3.value: ct3,
cst.TimeFeaturesEnum.ct_sqrt.value: ct_sqrt,
cst.TimeFeaturesEnum.ct_root3.value: ct_root3,
}
df = pd.DataFrame(features_dict)
if add_dst_info:
df[cst.TimeFeaturesEnum.us_dst.value] = is_dst_fcn("US/Pacific")(
df[cst.TimeFeaturesEnum.datetime.value])
df[cst.TimeFeaturesEnum.eu_dst.value] = is_dst_fcn("Europe/London")(
df[cst.TimeFeaturesEnum.datetime.value])
return df
The provided code snippet includes necessary dependencies for implementing the `get_fourier_feature_col_names` function. Write a Python function `def get_fourier_feature_col_names( df: pd.DataFrame, time_col: str, fs_func: callable, conti_year_origin: Optional[int] = None) -> List[str]` to solve the following problem:
Gets the Fourier feature column names. Parameters ---------- df : `pandas.DataFrame` The input data. time_col : `str` The column name for timestamps in ``df``. fs_func : callable The function to generate Fourier features. conti_year_origin : `int` or None, default None The continuous year origin. If None, will be inferred from time column. The names do not depend on this parameter though. Returns ------- col_names : `list` [`str`] The list of Fourier feature column names.
Here is the function:
def get_fourier_feature_col_names(
df: pd.DataFrame,
time_col: str,
fs_func: callable,
conti_year_origin: Optional[int] = None) -> List[str]:
"""Gets the Fourier feature column names.
Parameters
----------
df : `pandas.DataFrame`
The input data.
time_col : `str`
The column name for timestamps in ``df``.
fs_func : callable
The function to generate Fourier features.
conti_year_origin : `int` or None, default None
The continuous year origin.
If None, will be inferred from time column.
The names do not depend on this parameter though.
Returns
-------
col_names : `list` [`str`]
The list of Fourier feature column names.
"""
if conti_year_origin is None:
conti_year_origin = get_default_origin_for_time_vars(
df=df,
time_col=time_col
)
time_features_example_df = build_time_features_df(
df[time_col][:2],
conti_year_origin=conti_year_origin)
fs = fs_func(time_features_example_df)
return fs["cols"] | Gets the Fourier feature column names. Parameters ---------- df : `pandas.DataFrame` The input data. time_col : `str` The column name for timestamps in ``df``. fs_func : callable The function to generate Fourier features. conti_year_origin : `int` or None, default None The continuous year origin. If None, will be inferred from time column. The names do not depend on this parameter though. Returns ------- col_names : `list` [`str`] The list of Fourier feature column names. |
167,375 | import inspect
from datetime import timedelta
from typing import Dict
from typing import List
from typing import Optional
import numpy as np
import pandas as pd
from greykite.algo.changepoint.adalasso.auto_changepoint_params import generate_trend_changepoint_detection_params
from greykite.algo.common.holiday_grouper import HolidayGrouper
from greykite.algo.common.seasonality_inferrer import SeasonalityInferConfig
from greykite.algo.common.seasonality_inferrer import SeasonalityInferrer
from greykite.algo.common.seasonality_inferrer import TrendAdjustMethodEnum
from greykite.algo.forecast.silverkite.forecast_simple_silverkite_helper import split_events_into_dictionaries
from greykite.common import constants as cst
from greykite.common.constants import GrowthColEnum
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import add_event_window_multi
from greykite.common.features.timeseries_features import get_holidays
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.common.python_utils import update_dictionary
from greykite.common.time_properties import describe_timeseries
class TrendAdjustMethodEnum(Enum):
"""The methods that are available for adjusting trend in
`~greykite.algo.common.seasonality_inferrer.SeasonalityInferrer.infer_fourier_series_order`.
"""
seasonal_average = "seasonal_average"
"""Calculates the average within each seasonal period and removes it."""
overall_average = "overall_average"
"""Calculates the average of the whole timeseries and removes it."""
spline_fit = "spline_fit"
"""Fits a spline with no knots (polynomial) with a certain degree and removes it."""
none = "none"
"""Does not adjust trend."""
class SeasonalityInferConfig:
"""A dataclass to pass the parameters for
`~greykite.algo.common.seasonality_inferrer.SeasonalityInferrer.infer_fourier_series_order`.
Attributes
----------
seas_name : `str`
Required.
The seasonality component name.
Will be used to distinguish the results.
col_name : `str`
Required.
The column name used to generate seasonality Fourier series.
Must be in ``df`` or can be generated by
`~greykite.common.features.timeseries_features.build_time_features_df`.
See `~greykite.common.features.timeseries_features.fourier_series_multi_func`.
period : `float`
Required.
The period corresponding to ``col_name``.
See `~greykite.common.features.timeseries_features.fourier_series_multi_func`.
max_order : `int`
Required.
The maximum Fourier series order to fit.
adjust_trend_method : `str` or None, default "seasonal_average"
The method used to adjust trend.
Supported methods are in `AdjustTrendMethodEnum`.
None values are default to "seasonal_average" with subtracting yearly average as the default.
adjust_trend_param : `dict` or None, default None
Additional parameters for adjusting the trend.
For valid options, see
`~greykite.algo.common.seasonality_inferrer.SeasonalityInferrer._adjust_trend`.
fit_algorithm : `str` or None, default "ridge"
The algorithm used to fit the seasonality.
Supported algorithms are "linear", "ridge" and "sgd".
None values are default to "ridge".
plotting : `bool` or None, default False
Whether to generate plots.
If True, the returned dictionary will have plot via the "fig" key.
Can turn this off to speed up the process.
None values are default to False.
tolerance : `float` or None, default 0.0
A tolerance on the criterion to allow a smaller order.
For example, if AIC's minimum is 100 and ``tolerance`` is 0.1,
then the function will find the smallest order that has AIC less than or equal to 110.
None values are default to 0.0.
aggregation_period : `str` or None, default None
The aggregation period before fitting the Fourier series.
Having aggregation to eliminate shorter seasonal periods may help get more accurate orders.
But also making sure the number of observations after aggregation is sufficient.
None corresponds to no aggregation.
offset : `int` or None, default 0
The offset order to be added to the inferred orders.
The order after adding offset can not be negative.
criterion : `str` or None, default "bic"
The criterion to pick the most appropriate orders.
Supported criteria are "aic" and "bic".
None values are default to "bic".
"""
seas_name: str
col_name: str
period: float
max_order: int
adjust_trend_method: str = TrendAdjustMethodEnum.seasonal_average.name
adjust_trend_param: Optional[dict] = None
fit_algorithm: str = "ridge"
tolerance: float = 0.0
plotting: bool = False
aggregation_period: Optional[str] = None
offset: int = 0
criterion: str = "bic"
class SeasonalityInferrer:
"""A class to infer appropriate Fourier series orders in different
seasonality components.
The method allows users to:
- optionally remove the trend with different methods.
Available methods are in `TrendAdjustMethodEnum`.
- optionally do an aggregation.
- fits the seasonality component with different Fourier series orders.
- calculates the AIC/BIC of the fits.
- choose the most appropriate order with AIC or BIC and an optional tolerance.
- plot the investigations.
Attributes
----------
df : `pandas.DataFrame` or None
The input timeseries.
time_col : `str` or None
The column name for timestamps in ``df``.
value_col : `str` or None
The column name for values in ``df``.
fourier_series_orders : `dict` or None
The inferred Fourier series orders.
The keys are the seasonality component names.
The values are the inferred best orders according to the config.
df_features : `pandas.DataFrame` or None
The cached dataframe with time features.
Building this df is slow for large dataset.
We cache it the first time we build it for subsequent uses.
"""
def __init__(self):
# Set by inputs and preprocessing.
self.df: Optional[pd.DataFrame] = None
self.time_col: Optional[str] = None
self.value_col: Optional[str] = None
# Set by inferrer.
self.fourier_series_orders: Optional[dict] = None
self.df_features: Optional[pd.DataFrame] = None
FITTED_TREND_COL = "FITTED_TREND"
def infer_fourier_series_order(
self,
df: pd.DataFrame,
configs: List[SeasonalityInferConfig],
time_col: str = TIME_COL,
value_col: str = VALUE_COL,
adjust_trend_method: Optional[str] = None,
adjust_trend_param: Optional[dict] = None,
fit_algorithm: Optional[str] = None,
tolerance: Optional[float] = None,
plotting: Optional[bool] = None,
aggregation_period: Optional[str] = None,
offset: Optional[int] = None,
criterion: Optional[str] = None) -> dict:
"""Infers the most appropriate Fourier series order.
Can infer multiple seasonality components with multiple configs at the same time.
The configurations for each component are passed as a list of
`~greykite.algo.common.seasonality_inferrer.SeasonalityInferConfig` object.
To override a parameter for all configs, pass it via this function's parameter.
For each seasonality component,
the method first does an optional trend removal via grouped average or spline fit.
For example, for yearly seasonality, one option is to remove the average of each year
from the time series.
The seasonality pattern is clearer and dominates after the trend removal.
Next it does an optional aggregation to emphasize the current seasonality.
For example, for yearly seasonality, it can do a weekly aggregation so that
the weekly seasonality won't be mixed when modeling yearly seasonality.
Then it fits seasonality model using Fourier series with orders up to a certain max_order,
and computes the AIC/BIC of the models.
The final order will be selected based on the criterion with a tolerance adjustment.
A pre-specified offset can also be added to the selected order for adjustment.
Parameters
----------
df : `pandas.DataFrame`
The input timeseries.
configs : `list` [`SeasonalityInferConfig`]
A list of `~greykite.algo.common.seasonality_inferrer.SeasonalityInferConfig`
objects. Each element corresponds to the config for a seasonality component.
For example, if you would like to infer seasonality orders for yearly seasonality and
weekly seasonality, you need to provide a list of two configs.
time_col : `str`
The column name for timestamps in ``df``.
value_col : `str`
The column name for values in ``df``.
adjust_trend_method : `str` or None, default None
The methods used to adjust trend.
Supported methods are in `AdjustTrendMethodEnum`.
If not None, value is used to override all configs.
adjust_trend_param : `dict` or None, default None
Additional parameters for adjusting trend.
For valid options, see
`~greykite.algo.common.seasonality_inferrer.SeasonalityInferrer._adjust_trend`.
If not None, value is used to override all configs.
fit_algorithm : `str` or None, default None
The algorithms used to fit the seasonality.
Supported algorithms are "linear", "ridge" and "sgd".
If not None, value is used to override all configs.
plotting : `bool` or None, default None
Whether to generate plots.
If True, the returned dictionary will have plot via the "fig" key.
Can turn this off to speed up the process.
If not None, value is used to override all configs.
tolerance : `float` or None, default None
A tolerance on the criterion to allow a smaller order.
For example, if AIC's minimum is 100 and ``tolerance`` is 0.1,
then the function will find the smallest order that has AIC less than or equal to 110.
If not None, value is used to override all configs.
aggregation_period : `str` or None, default None
The aggregation periods before fitting the Fourier series.
Having aggregation to eliminate shorter seasonal periods may help get more accurate orders.
But also make sure the number of observations after aggregation is sufficient.
(At least 2 * max_order + 1 to have a unique solution for the regression problem)
If not None, value is used to override all configs.
offset : `int` or None, default None
The offset order to be added to the inferred orders.
The orders after applying offsets can not be negative.
If not None, value is used to override all configs.
criterion : `str` or None, default None
The criteria to pick the most appropriate orders.
If not None, value is used to override all configs.
Returns
-------
result : `dict`
The result dictionary with the following keys:
- "result": a list of result dictionaries from the inferring methods.
The keys are:
- "seas_name": the seasonality name.
- "orders": the Fourier series orders fitted.
- "aics": the fitted AICs.
- "bics": the fitted BICs.
- "best_aic_order": the order corresponding to the best feasible AIC.
- "best_bic_order": the order corresponding to the best feasible BIC.
- "fig": the diagnostic figure.
- "best_orders": a dictionary of seasonality component names and their
inferred Fourier series orders.
"""
# Checks and processes the input parameters.
configs = self._process_params(
configs=configs,
adjust_trend_method=adjust_trend_method,
adjust_trend_param=adjust_trend_param,
fit_algorithm=fit_algorithm,
tolerance=tolerance,
plotting=plotting,
aggregation_period=aggregation_period,
offset=offset,
criterion=criterion
)
# Sets class attributes.
self.df = df.copy()
self.df[time_col] = pd.to_datetime(self.df[time_col])
self.time_col = time_col
self.value_col = value_col
self.df_features = None # resets ``df_features`` for every new call.
# Iteratively infer the Fourier series order for each component.
result = []
for config in configs:
# Adjusts the trend and does aggregation.
df_adj = self._process_df(
df=self.df,
time_col=time_col,
value_col=value_col,
adjust_trend_method=config.adjust_trend_method,
adjust_trend_params=config.adjust_trend_param,
aggregation_period=config.aggregation_period
)
# Infers the seasonality Fourier series order.
seasonality_result = self._gets_seasonality_fitting_metrics(
df=df_adj,
time_col=time_col,
value_col=value_col,
seas_name=config.seas_name,
col_name=config.col_name,
period=config.period,
max_order=config.max_order,
fit_algorithm=config.fit_algorithm,
plotting=config.plotting,
tolerance=config.tolerance,
offset=config.offset
)
result.append(seasonality_result)
# Calculates best orders according to the criteria.
best_orders = {
config.seas_name: result[i]["best_aic_order"]
if config.criterion == "aic"
else result[i]["best_bic_order"]
for i, config in enumerate(configs)
}
self.fourier_series_orders = best_orders
return {
"result": result,
"best_orders": best_orders
}
def _process_params(
self,
configs: List[SeasonalityInferConfig],
adjust_trend_method: Optional[str],
adjust_trend_param: Optional[dict],
fit_algorithm: Optional[str],
tolerance: Optional[float],
plotting: Optional[bool],
aggregation_period: Optional[str],
offset: Optional[int],
criterion: Optional[str]) -> List[SeasonalityInferConfig]:
"""Checks and overrides the input parameters, and makes sure the values are valid.
Parameters
----------
configs : `list` [`SeasonalityInferConfig`]
A list of `~greykite.algo.common.seasonality_inferrer.SeasonalityInferConfig`
objects. Each element corresponds to the config for a seasonality component.
For example, if you would like to infer seasonality orders for yearly seasonality and
weekly seasonality, you need to provide a list of two configs.
adjust_trend_method : `str` or None, default None
The methods used to adjust trend.
Supported methods are in `AdjustTrendMethodEnum`.
If not None, value is used to override all configs.
adjust_trend_param : `dict` or None, default None
Additional parameters for adjusting trend.
For valid options, see
`~greykite.algo.common.seasonality_inferrer.SeasonalityInferrer._adjust_trend`.
If not None, value is used to override all configs.
fit_algorithm : `str` or None, default None
The algorithms used to fit the seasonality.
Supported algorithms are "linear", "ridge" and "sgd".
If not None, value is used to override all configs.
plotting : `bool` or None, default None
Whether to generate plots.
If True, the returned dictionary will have plot via the "fig" key.
Can turn this off to speed up the process.
If not None, value is used to override all configs.
tolerance : `float` or None, default None
A tolerance on the criterion to allow a smaller order.
For example, if AIC's minimum is 100 and ``tolerance`` is 0.1,
then the function will find the smallest order that has AIC less than or equal to 110.
If not None, value is used to override all configs.
aggregation_period : `str` or None, default None
The aggregation periods before fitting the Fourier series.
Having aggregation to eliminate shorter seasonal periods may help get more accurate orders.
But also make sure the number of observations after aggregation is sufficient.
(At least 2 * max_order + 1 to have a unique solution for the regression problem)
If not None, value is used to override all configs.
offset : `int` or None, default None
The offset order to be added to the inferred orders.
The orders after applying offsets can not be negative.
If not None, value is used to override all configs.
criterion : `str` or None, default None
The criteria to pick the most appropriate orders.
If not None, value is used to override all configs.
Returns
-------
configs : `list` [`SeasonalityInferConfig`]
A list of `~greykite.algo.common.seasonality_inferrer.SeasonalityInferConfig`
objects. The values are checked and overridden if needed.
"""
# For each of the optional parameters,
# checks the value is valid,
# overrides the value is needed,
# and fills the None values with defaults.
for (param_name, override_value, default_value, allowed_values) in (
("adjust_trend_method", adjust_trend_method,
TrendAdjustMethodEnum.seasonal_average.name,
TrendAdjustMethodEnum.__dict__["_member_names_"]),
("adjust_trend_param", adjust_trend_param, None, None),
("fit_algorithm", fit_algorithm, "ridge", ["ridge", "linear", "sgd"]),
("tolerance", tolerance, 0.0, None),
("plotting", plotting, False, [True, False]),
("aggregation_period", aggregation_period, None, None),
("offset", offset, 0, None),
("criterion", criterion, "bic", ["aic", "bic"])):
configs = self._apply_default_value(
configs=configs,
param_name=param_name,
override_value=override_value,
default_value=default_value,
allowed_values=allowed_values
)
return configs
def _apply_default_value(
configs: List[SeasonalityInferConfig],
param_name: str,
override_value: any,
default_value: any,
allowed_values: Optional[List[any]] = None) -> List[SeasonalityInferConfig]:
"""For the corresponding parameter in each config in ``configs``,
replaces `None` with default values;
overrides all values if ``override_value`` is not `None`;
checks the final values are in ``allowed_values`` if the latter is not `None`.
Parameters
----------
configs : `list` [`SeasonalityInferConfig`]
A list of `~greykite.algo.common.seasonality_inferrer.SeasonalityInferConfig`
objects. Each element corresponds to the config for a seasonality component.
For example, if you would like to infer seasonality orders for yearly seasonality and
weekly seasonality, you need to provide a list of two configs.
param_name : `str`
The name of the parameter.
Will be used in error message.
default_value : `any`
The default value to replace None.
allowed_values : `any`, `list` [`any`] or None, default None
The list of valid values.
If any given value is not valid, an error will be raised.
Leave as None to skip checking.
Returns
-------
configs : `list` [`SeasonalityInferConfig`]
A list of `~greykite.algo.common.seasonality_inferrer.SeasonalityInferConfig`
objects. The values are checked and overridden if needed.
"""
# Checks if ``override_value`` is given but not valid.
if override_value is not None and allowed_values is not None and override_value not in allowed_values:
raise ValueError(f"The parameter '{param_name}' has value {override_value}, "
f"which is not valid. Valid values are '{allowed_values}'.")
# If the ``override_value`` is provided and valid,
# overrides the parameter in all configs.
if override_value is not None:
for config in configs:
setattr(config, param_name, override_value)
return configs
# If ``override_value`` is None,
# checks the validity of each config's parameter and
# fills None with default value.
for config in configs:
param = getattr(config, param_name)
if param is None:
setattr(config, param_name, default_value)
elif allowed_values is not None and param not in allowed_values:
raise ValueError(f"The parameter '{param_name}' in SeasonalityInferConfig has value {param}, "
f"which is not valid. Valid values are '{allowed_values}'.")
return configs
def _adjust_trend(
self,
df: pd.DataFrame,
time_col: str = TIME_COL,
value_col: str = VALUE_COL,
method: str = TrendAdjustMethodEnum.seasonal_average.name,
trend_average_col: str = "year",
spline_fit_degree: int = 1) -> pd.DataFrame:
"""Adjusts the time series by removing trend.
There methods to remove trend from time series are listed in
`~greykite.algo.common.seasonality_inferrer.TrendAdjustMethodEnum`.
The methods are:
- "seasonal_average" : subtracts the average from each seasonal period.
- "overall_average" : subtracts the overall average.
- "spline_fit" : fits the trend using a spline with no knots up to a certain degree (poly).
Parameters
----------
df : `pandas.DataFrame`
The input time series.
time_col : `str`, default ``TIME_COL``
The column name for timestamps in ``df``.
value_col : `str`, default ``VALUE_COL``
The column name for values in ``df``.
method : `str`, default `~greykite.algo.common.seasonality_inferrer.TrendAdjustMethodEnum.seasonal_average.name`
The adjustment method. Must be a method specified in
`~greykite.algo.common.seasonality_inferrer.TrendAdjustMethodEnum`.
trend_average_col : `str`, default "year"
The column name that specifies the categories of calculating seasonal mean.
Suggested columns are "year", "year_quarter", "year_month", etc.
Has no effect if ``method`` is not
`~greykite.algo.common.seasonality_inferrer.TrendAdjustMethodEnum.seasonal_average.name`.
Must be provided in ``df`` or be generated by
`~greykite.common.features.timeseries_features import build_time_features_df`.
spline_fit_degree : `int`, default 1
The degree of spline to fit the trend.
Has no effect if ``method`` is not
`~greykite.algo.common.seasonality_inferrer.TrendAdjustMethodEnum.spline_fit.name`.
Returns
-------
df : `pandas.DataFrame`
A copy of the original df but with the ``value_col`` subtracting trend
and an extra column indicating the fitted trend.
The ``value_col`` will have mean zero if trend is adjusted.
"""
# Checks if the method is valid.
if method not in TrendAdjustMethodEnum.__dict__["_member_names_"]:
raise ValueError(f"The trend adjust method '{method}' is not a valid name. "
f"Available methods are {TrendAdjustMethodEnum.__dict__['_member_names_']}.")
df = df.copy()
# Subtracts the overall time series average.
if method == TrendAdjustMethodEnum.overall_average.name:
df[self.FITTED_TREND_COL] = df[value_col].mean()
# Subtracts the seasonal average within each seasonal period.
if method == TrendAdjustMethodEnum.seasonal_average.name:
df_cols = list(df.columns)
if trend_average_col not in df.columns:
if trend_average_col in TimeFeaturesEnum.__dict__["_member_names_"]:
if self.df_features is None:
df = add_time_features_df(
df=df,
time_col=time_col,
conti_year_origin=get_default_origin_for_time_vars(
df=df,
time_col=time_col
)
)
self.df_features = df.copy()
else:
df = self.df_features.copy()
else:
raise ValueError(f"The trend_average_col '{trend_average_col}' is neither found in df "
f"'{list(df.columns)}' nor in the built time features "
f"'{TimeFeaturesEnum.__dict__['_member_names_']}'.")
df_seasonal_average = (df[[value_col, trend_average_col]]
.groupby(trend_average_col)
.mean()
.reset_index(drop=False)
.rename(columns={value_col: self.FITTED_TREND_COL}))
df = df.merge(df_seasonal_average, on=trend_average_col)
df = df[df_cols + [self.FITTED_TREND_COL]]
# Subtracts the fitted trend.
if method == TrendAdjustMethodEnum.spline_fit.name:
if spline_fit_degree < 1:
raise ValueError(f"Spline degree has be to a positive integer, "
f"but found {spline_fit_degree}.")
df_features = add_time_features_df(
df=df,
time_col=time_col,
conti_year_origin=get_default_origin_for_time_vars(
df=df,
time_col=time_col
)
)
df_fit = df_features[[value_col, TimeFeaturesEnum.ct1.name]]
fit_cols = [TimeFeaturesEnum.ct1.name]
for degree in range(2, int(spline_fit_degree) + 1):
df_fit[f"ct{degree}"] = df_fit[TimeFeaturesEnum.ct1.name] ** degree
fit_cols.append(f"ct{degree}")
model = SGDRegressor()
model.fit(df_fit[fit_cols], df_fit[value_col])
df[self.FITTED_TREND_COL] = model.predict(df_fit[fit_cols])
df[value_col] -= df[self.FITTED_TREND_COL]
return df
def _process_df(
self,
df: pd.DataFrame,
time_col: str,
value_col: str,
adjust_trend_method: Optional[str],
adjust_trend_params: Optional[dict],
aggregation_period: Optional[str]) -> pd.DataFrame:
"""Does pre-processing which includes:
- adjust trend (optional)
- aggregation (optional)
Parameters
----------
df : `pandas.DataFrame`
The input time series.
time_col : `str`
The column name for timestamps in ``df``.
value_col : `str`
The column name for values in ``df``.
adjust_trend_method : `str` or None
The adjustment method. Must be a method specified in
`~greykite.algo.common.seasonality_inferrer.TrendAdjustMethodEnum`.
adjust_trend_params : `dict` or None
Additional parameters for `self._adjust_trend`.
aggregation_period : `str` or None
The aggregation period after adjusting the trend.
Returns
-------
df_adj : `pandas.DataFrame`
The df with trend removed.
"""
if adjust_trend_method is not None:
if adjust_trend_params is None:
adjust_trend_params = {}
df_adj = self._adjust_trend(
df=df,
time_col=time_col,
value_col=value_col,
method=adjust_trend_method,
**adjust_trend_params
)
else:
df_adj = df.copy()
if aggregation_period is not None:
df_adj = df_adj.resample(aggregation_period, on=time_col).mean().reset_index(drop=False)
return df_adj
def _gets_seasonality_fitting_metrics(
self,
df: pd.DataFrame,
time_col: str,
value_col: str,
seas_name: str,
col_name: str,
period: float,
max_order: int,
fit_algorithm: str = "ridge",
plotting: bool = False,
tolerance: float = 0.0,
offset: int = 0) -> dict:
"""Fits the seasonality with Fourier series and find the best order according to a criterion.
Parameters
----------
df : `pandas.DataFrame`
The input time series after trend adjustment.
time_col : `str`
The column name for timestamps in ``df``.
value_col : `str`
The column name for values in ``df``.
seas_name : `str`
The name for the seasonality component.
col_name : `str`
The column name for the column used to build Fourier series.
Must be in ``df`` or can be generated by
`~greykite.common.features.timeseries_features.build_time_features_df`.
See `~greykite.common.features.timeseries_features.fourier_series_multi_func`.
period : `float`
The period corresponding to ``col_name``.
See `~greykite.common.features.timeseries_features.fourier_series_multi_func`.
max_order : `int`
The maximum Fourier series order to fit.
fit_algorithm : `str`, default "ridge"
The algorithm used to fit the seasonality.
Supported algorithms are "linear", "ridge" and "sgd".
plotting : `bool`, default False
Whether to generate plots.
If True, the returned dictionary will have plot via the "fig" key.
Can turn this off to speed up the process.
tolerance : `float`, default 0.0
A tolerance on the criterion to allow a smaller order.
For example, if AIC's minimum is 100 and ``tolerance`` is 0.1,
then the function will find the smallest order that has AIC less than or equal to 110.
offset : `int`, default 0
The offset to be added to the best orders.
Returns
-------
result : `dict`
A result dictionary with the following keys:
- "seas_name": the seasonality name.
- "orders": the Fourier series orders fitted.
- "aics": the fitted AICs.
- "bics": the fitted BICs.
- "best_aic_order": the order corresponding to the best feasible AIC.
- "best_bic_order": the order corresponding to the best feasible BIC.
- "fig": the diagnostic figure.
"""
# Checks inputs.
if col_name not in df.columns and col_name not in TimeFeaturesEnum.__dict__["_member_names_"]:
raise ValueError(f"The column name '{col_name}' is not found in ``df`` or time features.")
if max_order <= 0 or int(max_order) != max_order:
raise ValueError(f"The max order must be a positive integer, found {max_order}.")
models = {
"ridge": RidgeCV,
"linear": LinearRegression,
"sgd": SGDRegressor
}
if fit_algorithm not in models:
raise ValueError(f"The fit_algorithm '{fit_algorithm}' is not supported. "
f"Must be one of {list(models.keys())}.")
model_class = models[fit_algorithm]
if tolerance < 0:
raise ValueError(f"The tolerance percentage must be non-negative, found {tolerance}.")
# Generates Fourier series.
fourier_func = fourier_series_multi_fcn(
col_names=[col_name],
periods=[period],
orders=[max_order],
seas_names=[seas_name]
)
if col_name not in df.columns:
df = add_time_features_df(
df=df,
time_col=time_col,
conti_year_origin=get_default_origin_for_time_vars(
df=df,
time_col=time_col
)
)
seasonality_df = fourier_func(df)["df"]
df_features = pd.concat([
df[[value_col]].reset_index(drop=True),
seasonality_df.reset_index(drop=True)
], axis=1)
df_features.dropna(inplace=True) # In case ``df_features`` has NANs and fit fails.
# Fits the models and calculates the metrics.
# Defines a function to fit seasonality model for a single order.
# This is later used with the `map` method to fast calculate the AIC/BICs for
# all orders.
# See https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loops
def fit_seasonality_model(order: int) -> (float, float):
"""A function to take a single order and fit
the seasonality model. Then it calculates the AIC/BIC of the model.
Parameters
----------
order : `int`
The Fourier series order.
Returns
-------
result : `tuple`
(AIC, BIC) score for the model.
"""
model = model_class()
features = [
col for col in df_features.columns
if col != value_col
# After split, the 1st element is sin{order} or cos{order}.
# Takes the order to compare with the current order.
and int(col.split("_")[0][3:]) <= order
]
model.fit(df_features[features], df_features[value_col])
pred = model.predict(df_features[features])
mse = np.mean((df_features[value_col] - pred) ** 2)
# The number of features in the current model is "2 * order".
# In the i.i.d. Gaussian case, the -2 * loglikelihood reduces to n * log(MSE).
aic = 2 * 2 * order + len(df_features) * np.log(mse)
bic = np.log(len(df_features)) * 2 * order + len(df_features) * np.log(mse)
return aic, bic
# Uses `map` to fast calculate the AIC/BICs.
orders = list(range(1, max_order + 1))
abics = list(map(fit_seasonality_model, orders))
aics = [abic[0] for abic in abics]
bics = [abic[1] for abic in abics]
min_aic = min(aics)
min_bic = min(bics)
# If a tolerance is allowed, the search will sacrifice some criterion
# to use a smaller order of Fourier series.
if tolerance > 0:
aic_tol = min_aic + abs(min_aic) * tolerance
bic_tol = min_bic + abs(min_bic) * tolerance
# Eligible criteria are those that are less than or equal to the tolerance.
# The original minimums are guaranteed to be in the lists.
eligible_aics = [aic for aic in aics if aic <= aic_tol]
eligible_bics = [bic for bic in bics if bic <= bic_tol]
# The first element is guaranteed to have order no greater than the original minimum.
min_aic = eligible_aics[0]
min_bic = eligible_bics[0]
best_aic_order = max(orders[aics.index(min_aic)] + offset, 0)
best_bic_order = max(orders[bics.index(min_bic)] + offset, 0)
# Gets the optional plot.
fig = None
if plotting:
fig = self._make_plot(
df=df,
df_features=df_features,
model_class=model_class,
time_col=time_col,
value_col=value_col,
orders=orders,
aics=aics,
bics=bics,
best_aic_order=best_aic_order,
best_bic_order=best_bic_order
)
return {
"seas_name": seas_name,
"orders": orders,
"aics": aics,
"bics": bics,
"best_aic_order": best_aic_order,
"best_bic_order": best_bic_order,
"fig": fig
}
def _make_plot(
self,
df: pd.DataFrame,
df_features: pd.DataFrame,
model_class: any,
time_col: str,
value_col: str,
orders: List[int],
aics: List[float],
bics: List[float],
best_aic_order: int,
best_bic_order: int) -> go.Figure:
"""Makes a figure that contains 2-3 subplots.
The subplots are:
- AIC/BIC vs. Fourier series orders.
- De-trended and aggregated time series vs fitted curves with best AIC/BICs.
- (Optional) the original time series, the fitted trend and the de-trended and aggregated
time series.
Parameters
----------
df : `pandas.DataFrame`
The input time series after de-trend and aggregation.
df_features : `pandas.DataFrame`
The time series with seasonality features generated.
model_class : `any`
The class type for the model to fit the seasonality curve.
time_col : `str`
The column name for timestamps in ``df``.
value_col : `str`
The column name for values in ``df``.
orders : `list` [`int`]
The orders used in calculating ``aics`` and ``bics``.
aics : `list` [`float`]
The AICs corresponding to ``orders``.
bics : `list` [`float`]
The BICs corresponding to ``orders``.
best_aic_order : `int`
The best AIC order.
best_bic_order : `int
The best BIC order.
Returns
-------
fig : `plotly.graph_object.Figure`
The figure object.
"""
rows = 2
subtitles = (
"Criteria vs. Fourier series orders",
"Fitted seasonality on best orders"
)
# If both original df and trend adjusted df are available,
# we include the trend adjustment visualization, too.
if (self.df is not None and time_col in self.df
and value_col in self.df and self.FITTED_TREND_COL in df):
rows += 1
subtitles += (
"Original time series and detrended/aggregated time series",
)
fig = make_subplots(
rows=rows,
cols=1,
subplot_titles=subtitles,
vertical_spacing=0.1
)
# Adds metric plot.
metrics = {
"AIC": [aics, best_aic_order, "dash"],
"BIC": [bics, best_bic_order, None]
}
for i, (metric, value) in enumerate(metrics.items()):
fig.add_trace(
go.Scatter(
x=orders,
y=value[0],
name=metric,
mode="lines",
showlegend=True,
line=dict(color=DEFAULT_PLOTLY_COLORS[i], dash=value[2])
),
row=1,
col=1
)
fig.add_vline(
x=value[1],
name=f"best_{metric}_order",
line=dict(color=DEFAULT_PLOTLY_COLORS[i], dash=value[2])
)
# Adds fit plot.
fig.add_trace(
go.Scatter(
x=df[time_col],
y=df[value_col],
name="Timeseries",
showlegend=True,
line=dict(color="black")
),
row=2,
col=1
)
best_orders = {
"best_AIC_order_fit": best_aic_order,
"best_BIC_order_fit": best_bic_order
}
for i, (name, order) in enumerate(best_orders.items()):
model = model_class()
features = [
col for col in df_features.columns
if col != value_col
# After split, the 1st element is sin{order} or cos{order}.
# Takes the order to compare with the current order.
and int(col.split("_")[0][3:]) <= order
]
if order > 0:
model.fit(df_features[features], df_features[value_col])
pred = model.predict(df_features[features])
else:
pred = np.repeat([df_features[value_col].mean()], len(df_features))
fig.add_trace(
go.Scatter(
x=df[time_col],
y=pred,
name=name,
mode="lines",
showlegend=True,
line=dict(color=DEFAULT_PLOTLY_COLORS[2 + i])
),
row=2,
col=1
)
# Adds trend adjustment plot.
if rows == 3:
fig.add_trace(
go.Scatter(
x=self.df[time_col],
y=self.df[value_col],
name="Original time series",
mode="lines",
showlegend=True
),
row=3,
col=1
)
fig.add_trace(
go.Scatter(
x=df[time_col],
y=df[value_col],
name="Detrend/aggregated time series",
mode="lines",
showlegend=True,
line=dict(color="black")
),
row=3,
col=1
)
fig.add_trace(
go.Scatter(
x=df[time_col],
y=df[self.FITTED_TREND_COL],
name="Fitted trend",
mode="lines",
showlegend=True
),
row=3,
col=1
)
fig.update_xaxes(
title_text="Fourier series order",
row=1,
col=1
)
fig.update_xaxes(
title_text="Timestamp",
row=2,
col=1
)
fig.update_yaxes(
title_text="Criteria",
row=1,
col=1
)
fig.update_yaxes(
title_text="Timeseries",
row=2,
col=1
)
if rows == 3:
fig.update_xaxes(
title_text="Timestamp",
row=3,
col=1
)
fig.update_yaxes(
title_text="Timeseries",
row=3,
col=1
)
fig.update_layout(
title_text="Inferred seasonality Fourier series orders",
height=1000
)
return fig
class TimeFeaturesEnum(Enum):
"""Time features generated by
`~greykite.common.features.timeseries_features.build_time_features_df`.
The item names are lower-case letters (kept the same as the values) for easier check of existence.
To check if a string s is in this Enum,
use ``s in TimeFeaturesEnum.__dict__["_member_names_"]``.
Direct check of existence ``s in TimeFeaturesEnum`` is deprecated in python 3.8.
"""
# Absolute time features
datetime = "datetime"
date = "date"
year = "year"
year_length = "year_length"
quarter = "quarter"
quarter_start = "quarter_start"
quarter_length = "quarter_length"
month = "month"
month_length = "month_length"
hour = "hour"
minute = "minute"
second = "second"
year_quarter = "year_quarter"
year_month = "year_month"
woy = "woy"
doy = "doy"
doq = "doq"
dom = "dom"
dow = "dow"
str_dow = "str_dow"
str_doy = "str_doy"
is_weekend = "is_weekend"
# Relative time features
year_woy = "year_woy"
month_dom = "month_dom"
year_woy_dow = "year_woy_dow"
woy_dow = "woy_dow"
dow_hr = "dow_hr"
dow_hr_min = "dow_hr_min"
tod = "tod"
tow = "tow"
tom = "tom"
toq = "toq"
toy = "toy"
conti_year = "conti_year"
dow_grouped = "dow_grouped"
# ISO time features
year_iso = "year_iso"
year_woy_iso = "year_woy_iso"
year_woy_dow_iso = "year_woy_dow_iso"
# Continuous time features
ct1 = "ct1"
ct2 = "ct2"
ct3 = "ct3"
ct_sqrt = "ct_sqrt"
ct_root3 = "ct_root3"
us_dst = "us_dst"
eu_dst = "eu_dst"
The provided code snippet includes necessary dependencies for implementing the `get_auto_seasonality` function. Write a Python function `def get_auto_seasonality( df: pd.DataFrame, time_col: str, value_col: str, yearly_seasonality: bool = True, quarterly_seasonality: bool = True, monthly_seasonality: bool = True, weekly_seasonality: bool = True, daily_seasonality: bool = True)` to solve the following problem:
Automatically infers the following seasonality Fourier series orders: - yearly seasonality - quarterly seasonality - monthly seasonality - weekly seasonality - daily seasonality The inferring is done with `~greykite.algo.common.seasonality_inferrer.SeasonalityInferrer`. Parameters ---------- df : `pandas.DataFrame` The input time series. time_col : `str` The column name for timestamps in ``df``. value_col : `str` The column name for values in ``df``. yearly_seasonality : `bool`, default True If False, the yearly seasonality order will be forced to be zero regardless of the inferring result. quarterly_seasonality : `bool`, default True If False, the quarterly seasonality order will be forced to be zero regardless of the inferring result. monthly_seasonality : `bool`, default True If False, the monthly seasonality order will be forced to be zero regardless of the inferring result. weekly_seasonality : `bool`, default True If False, the weekly seasonality order will be forced to be zero regardless of the inferring result. daily_seasonality : `bool`, default True If False, the daily seasonality order will be forced to be zero regardless of the inferring result. Returns ------- result : `dict` A dictionary with the keys being: - "yearly_seasonality" - "quarterly_seasonality" - "monthly_seasonality" - "weekly_seasonality" - "daily_seasonality" and values being the corresponding inferred Fourier series orders.
Here is the function:
def get_auto_seasonality(
df: pd.DataFrame,
time_col: str,
value_col: str,
yearly_seasonality: bool = True,
quarterly_seasonality: bool = True,
monthly_seasonality: bool = True,
weekly_seasonality: bool = True,
daily_seasonality: bool = True):
"""Automatically infers the following seasonality Fourier series orders:
- yearly seasonality
- quarterly seasonality
- monthly seasonality
- weekly seasonality
- daily seasonality
The inferring is done with `~greykite.algo.common.seasonality_inferrer.SeasonalityInferrer`.
Parameters
----------
df : `pandas.DataFrame`
The input time series.
time_col : `str`
The column name for timestamps in ``df``.
value_col : `str`
The column name for values in ``df``.
yearly_seasonality : `bool`, default True
If False, the yearly seasonality order will be forced to be zero
regardless of the inferring result.
quarterly_seasonality : `bool`, default True
If False, the quarterly seasonality order will be forced to be zero
regardless of the inferring result.
monthly_seasonality : `bool`, default True
If False, the monthly seasonality order will be forced to be zero
regardless of the inferring result.
weekly_seasonality : `bool`, default True
If False, the weekly seasonality order will be forced to be zero
regardless of the inferring result.
daily_seasonality : `bool`, default True
If False, the daily seasonality order will be forced to be zero
regardless of the inferring result.
Returns
-------
result : `dict`
A dictionary with the keys being:
- "yearly_seasonality"
- "quarterly_seasonality"
- "monthly_seasonality"
- "weekly_seasonality"
- "daily_seasonality"
and values being the corresponding inferred Fourier series orders.
"""
result = dict()
seasonalities = ["yearly_seasonality", "quarterly_seasonality", "monthly_seasonality",
"weekly_seasonality", "daily_seasonality"]
seasonality_defaults = [yearly_seasonality, quarterly_seasonality, monthly_seasonality,
weekly_seasonality, daily_seasonality]
# Iterate through the five seasonality frequencies.
# Frequencies that are less than or equal to the data frequency will have order 0.
df = df.copy()
df[time_col] = pd.to_datetime(df[time_col])
min_increment = min((df[time_col] - df[time_col].shift(1)).dropna())
# Yearly seasonality/quarterly seasonality is activated when data is at most weekly.
# For monthly data, it will not return yearly seasonality but will try to use "C(month)".
configs = []
if min_increment <= timedelta(days=7):
yearly_config = SeasonalityInferConfig(
seas_name="yearly",
col_name=TimeFeaturesEnum.toy.name,
period=1.0,
max_order=30,
adjust_trend_param=dict(
trend_average_col=TimeFeaturesEnum.year.name
),
aggregation_period="W"
)
quarterly_config = SeasonalityInferConfig(
seas_name="quarterly",
col_name=TimeFeaturesEnum.toq.name,
period=1.0,
max_order=10,
adjust_trend_param=dict(
trend_average_col=TimeFeaturesEnum.year_quarter.name
),
aggregation_period="W"
)
configs += [yearly_config, quarterly_config]
# Monthly/weekly seasonality is activated when data is at most daily.
if min_increment <= timedelta(days=1):
monthly_config = SeasonalityInferConfig(
seas_name="monthly",
col_name=TimeFeaturesEnum.tom.name,
period=1.0,
max_order=10,
adjust_trend_param=dict(
trend_average_col=TimeFeaturesEnum.year_month.name
),
aggregation_period="D"
)
weekly_config = SeasonalityInferConfig(
seas_name="weekly",
col_name=TimeFeaturesEnum.tow.name,
period=7.0,
max_order=5,
adjust_trend_param=dict(
trend_average_col=TimeFeaturesEnum.year_woy_iso.name
),
aggregation_period=None
)
configs += [monthly_config, weekly_config]
# Daily seasonality is activated when data is at most hourly.
if min_increment <= timedelta(hours=1):
daily_config = SeasonalityInferConfig(
seas_name="daily",
col_name=TimeFeaturesEnum.tod.name,
period=24.0,
max_order=15,
adjust_trend_param=dict(
trend_average_col=TimeFeaturesEnum.year_woy_dow_iso.name
),
aggregation_period=None
)
configs += [daily_config]
# Infers seasonality orders.
seasonality_inferrer = SeasonalityInferrer()
seasonality_result = seasonality_inferrer.infer_fourier_series_order(
df=df,
time_col=time_col,
value_col=value_col,
configs=configs,
adjust_trend_method=TrendAdjustMethodEnum.seasonal_average.name,
fit_algorithm="ridge",
tolerance=0.0,
plotting=False,
offset=0,
criterion="bic"
)
# Transforms seasonality infer results to dictionary.
for seasonality, default in zip(seasonalities, seasonality_defaults):
# Seasonalities are named like "yearly_seasonality" while the keys in the result are like "yearly".
# If a seasonality is not found in the result, the default is 0.
if default is not False:
result[seasonality] = seasonality_result["best_orders"].get(seasonality.split("_")[0], 0)
else:
result[seasonality] = 0
return result | Automatically infers the following seasonality Fourier series orders: - yearly seasonality - quarterly seasonality - monthly seasonality - weekly seasonality - daily seasonality The inferring is done with `~greykite.algo.common.seasonality_inferrer.SeasonalityInferrer`. Parameters ---------- df : `pandas.DataFrame` The input time series. time_col : `str` The column name for timestamps in ``df``. value_col : `str` The column name for values in ``df``. yearly_seasonality : `bool`, default True If False, the yearly seasonality order will be forced to be zero regardless of the inferring result. quarterly_seasonality : `bool`, default True If False, the quarterly seasonality order will be forced to be zero regardless of the inferring result. monthly_seasonality : `bool`, default True If False, the monthly seasonality order will be forced to be zero regardless of the inferring result. weekly_seasonality : `bool`, default True If False, the weekly seasonality order will be forced to be zero regardless of the inferring result. daily_seasonality : `bool`, default True If False, the daily seasonality order will be forced to be zero regardless of the inferring result. Returns ------- result : `dict` A dictionary with the keys being: - "yearly_seasonality" - "quarterly_seasonality" - "monthly_seasonality" - "weekly_seasonality" - "daily_seasonality" and values being the corresponding inferred Fourier series orders. |
167,376 | import inspect
from datetime import timedelta
from typing import Dict
from typing import List
from typing import Optional
import numpy as np
import pandas as pd
from greykite.algo.changepoint.adalasso.auto_changepoint_params import generate_trend_changepoint_detection_params
from greykite.algo.common.holiday_grouper import HolidayGrouper
from greykite.algo.common.seasonality_inferrer import SeasonalityInferConfig
from greykite.algo.common.seasonality_inferrer import SeasonalityInferrer
from greykite.algo.common.seasonality_inferrer import TrendAdjustMethodEnum
from greykite.algo.forecast.silverkite.forecast_simple_silverkite_helper import split_events_into_dictionaries
from greykite.common import constants as cst
from greykite.common.constants import GrowthColEnum
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import add_event_window_multi
from greykite.common.features.timeseries_features import get_holidays
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.common.python_utils import update_dictionary
from greykite.common.time_properties import describe_timeseries
def generate_trend_changepoint_detection_params(
df: pd.DataFrame,
forecast_horizon: int,
time_col: str = TIME_COL,
value_col: str = VALUE_COL,
yearly_seasonality_order: Optional[int] = None) -> Optional[dict]:
"""Automatically generates trend changepoint detection parameters
based on the input data and forecast horizon.
Parameters
----------
df : `pandas.DataFrame`
The input time series.
forecast_horizon : `int`
The forecast horizon.
time_col : `str`, default TIME_COL
The column name for timestamps in ``df``.
value_col : `str`, default VALUE_COL`
The column name for time series values in ``df``.
yearly_seasonality_order : `int` or None, default None
The yearly seasonality Fourier order.
If a known good order is given, it will be used.
Otherwise, it will be inferred from the algorithm.
Returns
-------
params : `dict` [`str`, any]
The generated trend changepoint detection parameters.
"""
df = df.copy()
df[time_col] = pd.to_datetime(df[time_col])
total_increment = df[time_col].max() - df[time_col].min()
# Auto changepoints is not active if training data is too short.
# In such cases, autoregression should be used.
if total_increment < timedelta(days=90):
return None
n_points = len(df)
min_increment = min((df[time_col] - df[time_col].shift(1)).dropna())
# Infers ``resample_freq``.
resample_freq = get_changepoint_resample_freq(
n_points=n_points,
min_increment=min_increment
)
# Infers ``yearly_seasonality_order``.
if yearly_seasonality_order is None:
yearly_seasonality_order = get_yearly_seasonality_order(
df=df,
time_col=time_col,
value_col=value_col,
resample_freq=resample_freq
)
elif yearly_seasonality_order < 0:
raise ValueError(f"Yearly seasonality order must be a non-negative integer, "
f"found {yearly_seasonality_order}.")
# Infers ``potential_changepoint_n``.
potential_changepoint_n = get_potential_changepoint_n(
n_points=n_points,
total_increment=total_increment,
resample_freq=resample_freq,
yearly_seasonality_order=yearly_seasonality_order,
cap=100
)
# Infers ``no_changepoint_distance_from_end``.
no_changepoint_distance_from_end = get_no_changepoint_distance_from_end(
min_increment=min_increment,
forecast_horizon=forecast_horizon,
min_num_points_after_last_changepoint=4
)
# Infers ``actual_changepoint_min_distance``.
actual_changepoint_min_distance = get_actual_changepoint_min_distance(
min_increment=min_increment
)
# Infers ``regularization_strength``.
regularization_strength = get_regularization_strength()
return dict(
yearly_seasonality_order=yearly_seasonality_order,
resample_freq=resample_freq,
regularization_strength=regularization_strength,
actual_changepoint_min_distance=actual_changepoint_min_distance,
potential_changepoint_n=potential_changepoint_n,
no_changepoint_distance_from_end=no_changepoint_distance_from_end
)
class GrowthColEnum(Enum):
"""Human-readable names for the growth columns generated by
`~greykite.common.features.timeseries_features.build_time_features_df`.
The names are the human-readable names, and the values are the corresponding
column names generated by `~greykite.common.features.timeseries_features.build_time_features_df`.
"""
linear = TimeFeaturesEnum.ct1.value
quadratic = TimeFeaturesEnum.ct2.value
cubic = TimeFeaturesEnum.ct3.value
sqrt = TimeFeaturesEnum.ct_sqrt.value
cuberoot = TimeFeaturesEnum.ct_root3.value
The provided code snippet includes necessary dependencies for implementing the `get_auto_growth` function. Write a Python function `def get_auto_growth( df: pd.DataFrame, time_col: str, value_col: str, forecast_horizon: int, changepoints_dict_override: Optional[dict] = None)` to solve the following problem:
Automatically gets the parameters for growth. Parameters ---------- df : `pandas.DataFrame` The input time series. time_col : `str` The column name for timestamps in ``df``. value_col : `str` The column name for values in ``df``. forecast_horizon : `int` The forecast horizon. changepoints_dict_override : `dict` or None, default None The changepoints configuration. If the following customized dates related keys are given, they will be copied to the final configuration: - "dates" - "combine_changepoint_min_distance" - "keep_detected" Returns ------- result : `dict` A dictionary with the following keys: - "growth_term": `str` The growth term. - "changepoints_dict": `dict` The changepoints configuration used for automatic changepoint detection.
Here is the function:
def get_auto_growth(
df: pd.DataFrame,
time_col: str,
value_col: str,
forecast_horizon: int,
changepoints_dict_override: Optional[dict] = None):
"""Automatically gets the parameters for growth.
Parameters
----------
df : `pandas.DataFrame`
The input time series.
time_col : `str`
The column name for timestamps in ``df``.
value_col : `str`
The column name for values in ``df``.
forecast_horizon : `int`
The forecast horizon.
changepoints_dict_override : `dict` or None, default None
The changepoints configuration.
If the following customized dates related keys are given,
they will be copied to the final configuration:
- "dates"
- "combine_changepoint_min_distance"
- "keep_detected"
Returns
-------
result : `dict`
A dictionary with the following keys:
- "growth_term": `str`
The growth term.
- "changepoints_dict": `dict`
The changepoints configuration used for automatic changepoint detection.
"""
# Gets the growth and changepoints configurations.
growth_term = GrowthColEnum.linear.name
trend_changepoints_param = generate_trend_changepoint_detection_params(
df=df,
forecast_horizon=forecast_horizon,
time_col=time_col,
value_col=value_col
)
trend_changepoints_param["method"] = "auto"
# Inherits the user specified dates.
if changepoints_dict_override is not None and changepoints_dict_override.get("method", None) != "custom":
for key in ["dates", "combine_changepoint_min_distance", "keep_detected"]:
if key in changepoints_dict_override:
trend_changepoints_param[key] = changepoints_dict_override[key]
return dict(
growth_term=growth_term,
changepoints_dict=trend_changepoints_param
) | Automatically gets the parameters for growth. Parameters ---------- df : `pandas.DataFrame` The input time series. time_col : `str` The column name for timestamps in ``df``. value_col : `str` The column name for values in ``df``. forecast_horizon : `int` The forecast horizon. changepoints_dict_override : `dict` or None, default None The changepoints configuration. If the following customized dates related keys are given, they will be copied to the final configuration: - "dates" - "combine_changepoint_min_distance" - "keep_detected" Returns ------- result : `dict` A dictionary with the following keys: - "growth_term": `str` The growth term. - "changepoints_dict": `dict` The changepoints configuration used for automatic changepoint detection. |
167,377 | import inspect
from datetime import timedelta
from typing import Dict
from typing import List
from typing import Optional
import numpy as np
import pandas as pd
from greykite.algo.changepoint.adalasso.auto_changepoint_params import generate_trend_changepoint_detection_params
from greykite.algo.common.holiday_grouper import HolidayGrouper
from greykite.algo.common.seasonality_inferrer import SeasonalityInferConfig
from greykite.algo.common.seasonality_inferrer import SeasonalityInferrer
from greykite.algo.common.seasonality_inferrer import TrendAdjustMethodEnum
from greykite.algo.forecast.silverkite.forecast_simple_silverkite_helper import split_events_into_dictionaries
from greykite.common import constants as cst
from greykite.common.constants import GrowthColEnum
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import add_event_window_multi
from greykite.common.features.timeseries_features import get_holidays
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.common.python_utils import update_dictionary
from greykite.common.time_properties import describe_timeseries
class HolidayGrouper:
"""This module estimates the impact of holidays and their neighboring days
given a raw holiday dataframe ``holiday_df``, and a time series containing
the observed values to construct the baselines.
It groups events with similar effects to several groups using kernel density estimation (KDE)
and generates the grouped events in a dictionary of dataframes that is recognizable by
`~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast`.
Parameters
----------
df : `pandas.DataFrame`
Input time series that contains ``time_col`` and ``value_col``.
The values will be used to construct baselines to estimate the holiday impact.
time_col : `str`
Name of the time column in ``df``.
value_col : `str`
Name of the value column in ``df``.
holiday_df : `pandas.DataFrame`
Input holiday dataframe that contains the dates and names of the holidays.
holiday_date_col : `str`
Name of the holiday date column in ``holiday_df``.
holiday_name_col : `str`
Name of the holiday name column in ``holiday_df``.
holiday_impact_pre_num_days: `int`, default 0
Default number of days before the holiday that will be modeled for holiday effect if the given holiday
is not specified in ``holiday_impact_dict``.
holiday_impact_post_num_days: `int`, default 0
Default number of days after the holiday that will be modeled for holiday effect if the given holiday
is not specified in ``holiday_impact_dict``.
holiday_impact_dict : `Dict` [`str`, Any] or None, default None
A dictionary containing the neighboring impacting days of a certain holiday. This overrides the
default ``pre_num`` and ``post_num`` for each holiday specified here.
The key is the name of the holiday matching those in the provided ``holiday_df``.
The value is a tuple of two values indicating the number of neighboring days
before and after the holiday. For example, a valid dictionary may look like:
.. code-block:: python
holiday_impact_dict = {
"Christmas Day": [3, 3],
"Memorial Day": [0, 0]
}
get_suffix_func : Callable or `str` or None, default "wd_we"
A function that generates a suffix (usually a time feature e.g. "_WD" for weekday,
"_WE" for weekend) given an input date.
This can be used to estimate the interaction between floating holidays
and on which day they are getting observed.
We currently support two defaults:
- "wd_we" to generate suffixes based on whether the day falls on weekday or weekend.
- "dow_grouped" to generate three categories: ["_WD", "_Sat", "_Sun"].
If None, no suffix is added.
Attributes
----------
expanded_holiday_df : `pandas.DataFrame`
An expansion of ``holiday_df`` after adding the neighboring dates provided in
``holiday_impact_dict`` and the suffix generated by ``get_suffix_func``.
For example, if ``"Christmas Day": [3, 3]`` and "wd_we" are used, events
such as "Christmas Day_WD_plus_1_WE" or "Christmas Day_WD_minus_3_WD" will be generated
for a Christmas that falls on Friday.
baseline_offsets : `Tuple`[`int`] or None
The offsets in days to calculate baselines for a given holiday.
By default, the same days of the week before and after are used.
use_relative_score : `bool` or None
Whether to use relative or absolute score when estimating the holiday impact.
clustering_method : `str` or None
Clustering method used to group the holidays.
Since we are doing 1-D clustering, current supported methods include
(1) "kde" for kernel density estimation, and (2) "kmeans" for k-means clustering.
bandwidth : `float` or None
The bandwidth used in the kernel density estimation.
Higher bandwidth results in less clusters.
If None, it is automatically inferred with the ``bandwidth_multiplier`` factor.
bandwidth_multiplier : `float` or None
Multiplier to be multiplied to the kernel density estimation's default parameter calculated from
`here<https://en.wikipedia.org/wiki/Kernel_density_estimation#A_rule-of-thumb_bandwidth_estimator>_`.
This multiplier has been found useful in adjusting the default bandwidth parameter in many cases.
Only used when ``bandwidth`` is not specified.
kde : `KernelDensity` or None
The `KernelDensity` object if ``clustering_method == "kde"``.
n_clusters : `int` or None
Number of clusters in the k-means algorithm.
kmeans : `KMeans` or None
The `KMeans` object if ``clustering_method == "kmeans"``.
include_diagnostics : `bool` or None
Whether to include ``kmeans_diagnostics`` and ``kmeans_plot`` in the output ``result_dict``.
result_dict : `Dict`[`str`, Any] or None
A dictionary that stores the scores and clustering results, with the following keys.
- "holiday_inferrer": the `~greykite.algo.common.holiday_inferrer.HolidayInferrer`
instance used for calculating the scores.
- "score_result_original": a dictionary with keys being the names of all holiday events
after expansion (i.e. the keys in ``expanded_holiday_df``), values being a list of scores
of all dates corresponding to this event.
- "score_result_avg_original": a dictionary with the same key as in
``result_dict["score_result_original"]``.
But the values are the average scores of each event across all occurrences.
- "score_result": same as ``result_dict["score_result_original"]``, but after removing
holidays with inconsistent / negligible scores.
- "score_result_avg": same as ``result_dict["score_result_original"]``, but after removing
holidays with inconsistent / negligible scores.
- "daily_event_df_dict_with_score": a dictionary of dataframes.
Key is the group name ``"holiday_group_{k}"``.
Value is a dataframe of all holiday events in this group, containing 4 columns:
"date" (``EVENT_DF_DATE_COL``), "event_name" (``EVENT_DF_LABEL_COL``), "original_name", "avg_score".
- "daily_event_df_dict": a dictionary of dataframes that is ready to use in `SilverkiteForecast`.
Contains 2 keys: ``EVENT_DF_DATE_COL`` and ``EVENT_DF_LABEL_COL``.
- "kde_cutoffs": a list of `float`, the cutoffs returned by the kernel density clustering.
- "kde_res": a dataframe that contains "score" and "density" from the kernel density estimation.
- "kde_plot": a plot of the kernel density estimation.
- "kmeans_diagnostics": a dataframe containing metrics for different number of clusters.
Columns are:
- "k": number of clusters;
- "wsse": within-cluster sum of squared error (lower is better);
- "sil_score": Silhouette coefficient, a value between [-1, 1] that describes
the separation of clusters (higher is better).
Only generated when ``include_diagnostics`` is True. See `group_holidays` for details.
- "kmeans_plot": a plot visualizing how the diagnostic metrics change over K.
Only generated when ``include_diagnostics`` is True. See `group_holidays` for details.
"""
def __init__(
self,
df: pd.DataFrame,
time_col: str,
value_col: str,
holiday_df: pd.DataFrame,
holiday_date_col: str,
holiday_name_col: str,
holiday_impact_pre_num_days: int = 0,
holiday_impact_post_num_days: int = 0,
holiday_impact_dict: Optional[Dict[str, Tuple[int, int]]] = None,
get_suffix_func: Optional[Union[Callable, str]] = "wd_we"):
self.df = df.copy()
self.time_col = time_col
self.value_col = value_col
self.holiday_df = holiday_df.copy()
self.holiday_date_col = holiday_date_col
self.holiday_name_col = holiday_name_col
self.holiday_impact_pre_num_days = holiday_impact_pre_num_days
self.holiday_impact_post_num_days = holiday_impact_post_num_days
if holiday_impact_dict is None:
holiday_impact_dict = {}
self.holiday_impact_dict = holiday_impact_dict.copy()
self.get_suffix_func = get_suffix_func
# Derived attributes.
# Casts time columns to `datetime`.
self.df[time_col] = pd.to_datetime(self.df[time_col])
self.holiday_df[holiday_date_col] = pd.to_datetime(self.holiday_df[holiday_date_col])
# Creates `HOLIDAY_DATE_COL` and `HOLIDAY_NAME_COL` (if not exists) to be recognized by `HolidayInferrer`.
self.holiday_df[HOLIDAY_DATE_COL] = self.holiday_df[self.holiday_date_col]
self.holiday_df[HOLIDAY_NAME_COL] = self.holiday_df[self.holiday_name_col]
# Other attributes that are not needed for initialization.
self.baseline_offsets: Optional[Tuple[int, int]] = None
self.use_relative_score: Optional[bool] = None
self.clustering_method: Optional[str] = None
self.bandwidth: Optional[float] = None
self.bandwidth_multiplier: Optional[float] = None
self.kde: Optional[KernelDensity] = None
self.n_clusters: Optional[int] = None
self.kmeans: Optional[KMeans] = None
self.include_diagnostics: Optional[bool] = None
# Result dictionary will be populated after the scoring and grouping functions are run.
self.result_dict: Optional[Dict[str, Any]] = None
# Expands `holiday_df` to include neighboring days
# and suffixes (e.g. "_WD" for weekdays, "_Sat" for Saturdays).
self.expanded_holiday_df = self.expand_holiday_df_with_suffix(
holiday_df=self.holiday_df,
holiday_date_col=HOLIDAY_DATE_COL,
holiday_name_col=HOLIDAY_NAME_COL,
holiday_impact_pre_num_days=self.holiday_impact_pre_num_days,
holiday_impact_post_num_days=self.holiday_impact_post_num_days,
holiday_impact_dict=self.holiday_impact_dict,
get_suffix_func=self.get_suffix_func
)
def group_holidays(
self,
baseline_offsets: Tuple[int, int] = (-7, 7),
use_relative_score: bool = True,
min_n_days: int = 1,
min_same_sign_ratio: float = 0.66,
min_abs_avg_score: float = 0.03,
clustering_method: str = "kmeans",
bandwidth: Optional[float] = None,
bandwidth_multiplier: Optional[float] = 0.2,
n_clusters: Optional[int] = 5,
include_diagnostics: bool = False) -> None:
"""Estimates the impact of holidays and their neighboring days and
groups events with similar effects to several groups using kernel density estimation (KDE).
Then generates the grouped events and stores the results in ``self.result_dict``.
Parameters
----------
baseline_offsets : `Tuple`[`int`], default (-7, 7)
The offsets in days to calculate baselines for a given holiday.
By default, the same days of the week before and after are used.
use_relative_score : `bool`, default True
Whether to use relative or absolute score when estimating the holiday impact.
min_n_days : `int`, default 1
Minimal number of occurrences for a holiday event to be kept before grouping.
min_same_sign_ratio : `float`, default 0.66
Threshold of the ratio of the same-sign scores for an event's occurrences.
For example, if an event has two occurrences, they both need to have positive or negative
scores for the ratio to achieve 0.66.
Similarly, if an event has 3 occurrences, at least 2 of them must have the same directional impact.
This parameter is intended to rule out holidays that have indefinite effects.
min_abs_avg_score : `float`, default 0.03
The minimal average score of an event (across all its occurrences) to be kept
before grouping.
When ``use_relative_score = True``, 0.03 means the effect must be greater than 3%.
clustering_method : `str`, default "kmeans"
Clustering method used to group the holidays.
Since we are doing 1-D clustering, current supported methods include
(1) "kde" for kernel density estimation, and (2) "kmeans" for k-means clustering.
bandwidth : `float` or None, default None
The bandwidth used in the kernel density estimation.
Higher bandwidth results in less clusters.
If None, it is automatically inferred with the ``bandwidth_multiplier`` factor.
Only used when ``clustering_method == "kde"``.
bandwidth_multiplier : `float` or None, default 0.2
Multiplier to be multiplied to the kernel density estimation's default parameter calculated from
`here<https://en.wikipedia.org/wiki/Kernel_density_estimation#A_rule-of-thumb_bandwidth_estimator>_`.
This multiplier has been found useful in adjusting the default bandwidth parameter in many cases.
Only used when ``bandwidth`` is not specified and ``clustering_method == "kde"``.
n_clusters : `int` or None, default 5
Number of clusters in the k-means algorithm.
Only used when ``clustering_method == "kmeans"``.
include_diagnostics : `bool`, default False
Whether to include ``kmeans_diagnostics`` and ``kmeans_plot`` in the output ``result_dict``.
Returns
-------
Saves the results in the ``result_dict`` attribute.
"""
# Parameters should have already been set during initialization.
# If new values are provided, they will override the original values.
self.baseline_offsets = baseline_offsets
self.use_relative_score = use_relative_score
self.clustering_method = clustering_method
# Runs baselines to get scores on holiday events.
self.result_dict = self.get_holiday_scores(
baseline_offsets=baseline_offsets,
use_relative_score=use_relative_score,
min_n_days=min_n_days,
min_same_sign_ratio=min_same_sign_ratio,
min_abs_avg_score=min_abs_avg_score
)
# Extracts results and prepares data for kernel density estimation.
score_result_avg = self.result_dict["score_result_avg"]
scores_df_original = (
pd.DataFrame(score_result_avg, index=["avg_score"])
.transpose()
.reset_index(drop=False)
.rename(columns={"index": "event_name"})
)
# In rare cases some holiday events may fall on exactly the same day, hence the same score.
# We drop duplicated average scores before clustering, for example,
# Halloween (10/31) plus 1 always has the same scores as All Saints Day (11/1).
scores_df = scores_df_original.drop_duplicates("avg_score").sort_values("avg_score").reset_index(drop=True)
scores_x = np.array(scores_df["avg_score"]).reshape(-1, 1)
# The following parameters are set to None unless the clustering method is called to populate them.
kde_res = None
kde_plot = None
kde_cutoffs = None
kmeans_diagnostics = None
kmeans_plot = None
if clustering_method.lower() == "kde":
if bandwidth is None and bandwidth_multiplier is None:
raise ValueError(f"At least one of `bandwidth` or `bandwidth_multiplier` must be provided!")
if bandwidth is None:
# Automatically infers the best `bandwidth`.
std = scores_x.std()
iqr = np.percentile(scores_x, 75) - np.percentile(scores_x, 25)
sigma = min(std, iqr / 1.34)
bandwidth = 0.9 * sigma * (len(scores_x) ** (-1 / 5)) * bandwidth_multiplier
kde = KernelDensity(kernel="gaussian", bandwidth=bandwidth).fit(scores_x)
y = np.exp(kde.score_samples(scores_x))
kde_res = pd.DataFrame({"score": scores_df["avg_score"], "density": y.tolist()})
kde_res = kde_res.sort_values("score").reset_index(drop=True)
kde_plot = plot_multivariate(
df=kde_res,
x_col="score",
title="Kernel density of the holiday scores",
xlabel="Holiday impact",
ylabel="Kernel density"
)
# Performs holiday clustering based on the kernel densities.
scores = kde_res["score"].to_list()
densities = kde_res["density"].to_list()
# Find the cutoffs such that scores <= each cutoff are grouped together.
kde_cutoffs = []
for i, x in enumerate(densities):
if 0 < i < len(densities) - 1 and x < densities[i - 1] and x < densities[i + 1]:
kde_cutoffs.append(scores[i])
# The group around 0 may contain mixed signs, hence we manually add 0 as a cutoff.
# This might introduce an extra group with no scores - we will remove it later.
# Note that there are no scores smaller than `min_abs_avg_score`.
kde_cutoffs = sorted(kde_cutoffs + [0])
# Constructs `daily_event_df_dict` for all groups.
daily_event_df_dict_raw = {
f"holiday_group_{i}": pd.DataFrame({
EVENT_DF_DATE_COL: [],
EVENT_DF_LABEL_COL: [],
"original_name": [],
"avg_score": []
}) for i in range(len(kde_cutoffs) + 1)}
for key, value in score_result_avg.items():
# Gets group assignment.
for i, cutoff in enumerate(sorted(kde_cutoffs)):
if value <= cutoff:
break
else: # If `value` > the largest cutoff, assigns it to the last group.
i += 1
# Now, `i` is the group this holiday belongs to.
# Gets the dates for each event.
# Since holiday inferrer automatically adds "+0" to all events, here we remove it.
key_without_plus_minus = "_".join(key.split("_")[:-1])
idx = self.expanded_holiday_df[HOLIDAY_NAME_COL] == key_without_plus_minus
dates = self.expanded_holiday_df.loc[idx, HOLIDAY_DATE_COL]
# Creates `event_df`.
group_name = f"holiday_group_{i}"
event_df = pd.DataFrame({
EVENT_DF_DATE_COL: dates,
EVENT_DF_LABEL_COL: group_name,
"original_name": key_without_plus_minus,
"avg_score": value
})
daily_event_df_dict_raw[group_name] = daily_event_df_dict_raw[group_name].append(
event_df, ignore_index=True)
# Removes potential empty groups.
daily_event_df_dict = {}
new_idx = 0
for i in range(len(daily_event_df_dict_raw)):
event_df = daily_event_df_dict_raw[f"holiday_group_{i}"]
if len(event_df) > 0:
daily_event_df_dict[f"holiday_group_{new_idx}"] = (
event_df
.sort_values(by=["avg_score", EVENT_DF_DATE_COL])
.reset_index(drop=True)
)
new_idx += 1
del daily_event_df_dict_raw
# Overrides the attributes in the end.
self.bandwidth = bandwidth
self.bandwidth_multiplier = bandwidth_multiplier
self.kde = kde
elif clustering_method.lower() == "kmeans":
# Runs K-means ++ to generate group assignments.
kmeans = KMeans(n_clusters=n_clusters, random_state=0, init="k-means++").fit(scores_x)
# Predicts on the original `scores_df` since two different events may fall on the
# same dates where the score was calculated, but they may have different dates in the future.
predicted_labels = kmeans.predict(np.array(scores_df_original["avg_score"]).reshape(-1, 1))
scores_df_with_label = scores_df_original.copy()
scores_df_with_label["labels"] = list(predicted_labels)
# Since `predicted_labels` is not ordered, we sort the groups according to the average score.
group_rank_df = scores_df_with_label.groupby(by="labels")["avg_score"].agg(np.nanmean).reset_index()
group_rank_df["group_id"] = (
group_rank_df["avg_score"]
.rank(method="dense", ascending=True)
.astype(int)
) - 1 # Group indices start from 0.
# Merges back to the original scores dataframe.
scores_df_with_label = scores_df_with_label.merge(
group_rank_df[["labels", "group_id"]],
on="labels", how="left")
daily_event_df_dict = {
f"holiday_group_{i}": pd.DataFrame({
EVENT_DF_DATE_COL: [],
EVENT_DF_LABEL_COL: [],
"original_name": [],
"avg_score": []
}) for i in range(n_clusters)}
for key, value in score_result_avg.items():
# Gets group assignment.
group_id = scores_df_with_label.loc[scores_df_with_label["event_name"] == key, "group_id"].values[0]
group_name = f"holiday_group_{group_id}"
# Gets the dates for each event.
# Since holiday inferrer automatically adds "+0" to all events, here we remove it.
key_without_plus_minus = "_".join(key.split("_")[:-1])
idx = self.expanded_holiday_df[HOLIDAY_NAME_COL] == key_without_plus_minus
dates = self.expanded_holiday_df.loc[idx, HOLIDAY_DATE_COL]
# Creates `event_df`.
event_df = pd.DataFrame({
EVENT_DF_DATE_COL: dates,
EVENT_DF_LABEL_COL: group_name,
"original_name": key_without_plus_minus,
"avg_score": value
})
daily_event_df_dict[group_name] = pd.concat([daily_event_df_dict[group_name], event_df])
# Sorts the output dataframes.
for i in range(len(daily_event_df_dict)):
event_df = daily_event_df_dict[f"holiday_group_{i}"]
daily_event_df_dict[f"holiday_group_{i}"] = (
event_df
.sort_values(by=["avg_score", EVENT_DF_DATE_COL])
.reset_index(drop=True)
)
# Generates diagnostics for K means to help choose the optimal K (`n_clusters`).
if include_diagnostics:
kmeans_diagnostics = {"k": [], "wsse": [], "sil_score": []}
for candidate_k in range(2, min(len(scores_df) // 2, 20) + 1):
tmp_model = KMeans(n_clusters=candidate_k).fit(scores_x)
# Gets Silhouette score.
kmeans_diagnostics["k"].append(candidate_k)
kmeans_diagnostics["sil_score"].append(silhouette_score(
X=scores_x,
labels=tmp_model.labels_,
metric="euclidean"
))
# Gets within-cluster sum of squared errors.
centroids = tmp_model.cluster_centers_
pred_clusters = tmp_model.predict(scores_x)
curr_sse = 0
for i in range(len(scores_x)):
curr_center = centroids[pred_clusters[i]]
curr_sse += (scores_x[i, 0] - curr_center[0]) ** 2
kmeans_diagnostics["wsse"].append(curr_sse)
kmeans_diagnostics = pd.DataFrame(kmeans_diagnostics)
kmeans_plot = plot_multivariate(
df=kmeans_diagnostics,
x_col="k",
xlabel="n_clusters",
title="K-means diagnostics<br>"
"(1) Within-cluster SSE: lower is better<br>"
"(2) Silhouette scores: higher is better"
)
# Overrides the attributes in the end.
self.n_clusters = n_clusters
self.kmeans = kmeans
self.include_diagnostics = include_diagnostics
else:
raise NotImplementedError(f"`clustering_method` {clustering_method} is not supported! "
f"Must be one of \"kde\" (kernel density estimation) or "
f"\"kmeans\" (k-means).")
# Cleans up and removes duplicate dates.
new_daily_event_df_dict = {
key: (df[[EVENT_DF_DATE_COL, EVENT_DF_LABEL_COL]]
.drop_duplicates(EVENT_DF_DATE_COL)
.reset_index(drop=True)) for key, df in daily_event_df_dict.items()
}
self.result_dict.update({
"daily_event_df_dict_with_score": daily_event_df_dict,
"daily_event_df_dict": new_daily_event_df_dict,
"kde_cutoffs": kde_cutoffs,
"kde_res": kde_res,
"kde_plot": kde_plot,
"kmeans_diagnostics": kmeans_diagnostics,
"kmeans_plot": kmeans_plot
})
def get_holiday_scores(
self,
baseline_offsets: Tuple[int, int] = (-7, 7),
use_relative_score: bool = True,
min_n_days: int = 1,
min_same_sign_ratio: float = 0.66,
min_abs_avg_score: float = 0.05) -> Dict[str, Any]:
"""Computes the score of all holiday events and their neighboring days
in ``self.expanded_holiday_df``, by comparing their observed values with a baseline
value that is an average of the values on the days specified in ``baseline_offsets``.
If a baseline date falls on another holiday, the algorithm looks for the next
value with the same step size as the given offset, up to 3 extra iterations.
Please see more details in
`~greykite.algo.common.holiday_inferrer.HolidayInferrer._get_scores_for_holidays`.
An additional pruning step is done to remove holidays with inconsistent / negligible scores.
Both the results before and after the pruning are returned.
Parameters
----------
baseline_offsets : `Tuple`[`int`], default (-7, 7)
The offsets in days to calculate baselines for a given holiday.
By default, the same days of the week before and after are used.
use_relative_score : `bool`, default True
Whether to use relative or absolute score when estimating the holiday impact.
min_n_days : `int`, default 1
Minimal number of occurrences for a holiday event to be kept before grouping.
min_same_sign_ratio : `float`, default 0.66
Threshold of the ratio of the same-sign scores for an event's occurrences.
For example, if an event has two occurrences, they both need to have positive or negative
scores for the ratio to achieve 0.66.
Similarly, if an event has 3 occurrences, at least 2 of them must have the same directional impact.
This parameter is intended to rule out holidays that have indefinite effects.
min_abs_avg_score : `float`, default 0.05
The minimal average score of an event (across all its occurrences) to be kept
before grouping.
When ``use_relative_score = True``, 0.05 means the effect must be greater than 5%.
Returns
-------
result_dict : `Dict` [`str`, Any]
A dictionary containing the scoring results.
In particular the following keys are set: "holiday_inferrer", "score_result_original",
"score_result_avg_original", "score_result", and "score_result_avg".
Please refer to the docstring of the ``self.result_dict`` attribute of `HolidayGrouper`.
"""
# Initializes `HolidayInferrer` and sets the parameters.
hi = HolidayInferrer()
hi.df = self.df.copy()
# In `HolidayInferrer._get_scores_for_holidays`, `time_col` must be of `datetime.date` or `str` type.
hi.df[self.time_col] = pd.to_datetime(hi.df[self.time_col]).dt.date
hi.ts = set(hi.df[self.time_col])
hi.time_col = self.time_col
hi.value_col = self.value_col
hi.baseline_offsets = baseline_offsets
hi.use_relative_score = use_relative_score
hi.pre_search_days = 0
hi.post_search_days = 0
hi.country_holiday_df = self.expanded_holiday_df.copy()
hi.all_holiday_dates = self.expanded_holiday_df[HOLIDAY_DATE_COL].tolist()
hi.holidays = self.expanded_holiday_df[HOLIDAY_NAME_COL].unique().tolist()
# Gets the scores for each single date in `self.expanded_holiday_df`.
hi.score_result = hi._get_scores_for_holidays()
# Gets the average scores over multiple occurrences for each holiday in `self.expanded_holiday_df`.
hi.score_result_avg = hi._get_averaged_scores()
# Prunes holiday that has too few datapoints or inconsistent / negligible scores.
pruned_result = self._prune_holiday_by_score(
score_result=hi.score_result,
score_result_avg=hi.score_result_avg,
min_n_days=min_n_days,
min_same_sign_ratio=min_same_sign_ratio,
min_abs_avg_score=min_abs_avg_score
)
# Returns result both before and after pruning.
self.result_dict = {
"holiday_inferrer": hi,
"score_result_original": hi.score_result,
"score_result_avg_original": hi.score_result_avg,
"score_result": pruned_result["score_result"],
"score_result_avg": pruned_result["score_result_avg"]
}
return self.result_dict
def check_scores(
self,
holiday_name_pattern: str,
show_pruned: bool = True) -> None:
"""Spot checks the score of certain holidays containing pattern ``holiday_name_pattern``.
Prints out the dates, individual day scores of all occurrences,
and the average scores of all matching holiday events.
Note that it only checks the keys in ``self.expanded_holiday_df``,
and it assumes `get_holiday_scores` is already run.
Parameters
----------
holiday_name_pattern : `str`
Any substring of the holiday event names (``self.expanded_holiday_df[self.holiday_name_col]``).
show_pruned : `bool`, default True
Whether to show pruned holidays along with the remaining holidays.
Returns
-------
Prints out the dates, individual day scores of all occurrences,
and the average scores of all matching holiday events.
"""
result_dict = self.result_dict
if result_dict is None:
return
if show_pruned:
score_result = result_dict["score_result_original"]
score_result_avg = result_dict["score_result_avg_original"]
else:
score_result = result_dict["score_result"]
score_result_avg = result_dict["score_result_avg"]
res_dict = {}
for key, value in score_result_avg.items():
if holiday_name_pattern in key:
# `HolidayInferrer` automatically adds "+" and "-" to the end, we remove them.
key_without_plus_minus = "_".join(key.split("_")[:-1])
dates = self.expanded_holiday_df.loc[
self.expanded_holiday_df[HOLIDAY_NAME_COL] == key_without_plus_minus, # Uses exact matching.
HOLIDAY_DATE_COL
]
dates = dates.dt.strftime("%Y-%m-%d").to_list()
dates = [date for date in dates if date in self.df[self.time_col].dt.strftime("%Y-%m-%d").tolist()]
# Prints out the date and impact of each day.
impacts = score_result[key]
print(f"{key_without_plus_minus}:\n"
f"Dates: {dates}\n"
f"Scores: {impacts}\n")
# Extracts average score.
res_dict[key_without_plus_minus] = value
print("Average impact:")
display(res_dict)
def check_holiday_group(
self,
holiday_name_pattern: str = "",
holiday_groups: Optional[Union[List[int], int]] = None) -> None:
"""Prints out the holiday groups that contain holidays matching ``holiday_name_pattern`` and their scores.
The searching is limited to the given ``holiday_groups``.
Note that it assumes `group_holidays` has already been run.
Parameters
----------
holiday_name_pattern : `str`
Any substring of the holiday event names (``self.expanded_holiday_df[self.holiday_name_col]``).
holiday_groups : `List`[`int`] or `int`, default None
The indices of holiday groups that the searching is limited in.
If None, all groups are available to search.
Returns
-------
Prints out all qualifying holiday groups and their scores.
"""
result_dict = self.result_dict
if result_dict is None or "daily_event_df_dict_with_score" not in result_dict.keys():
raise Exception(f"Method `group_holidays` must be run before using the `check_holiday_group` method.")
daily_event_df_dict_with_score = result_dict["daily_event_df_dict_with_score"]
if holiday_groups is None:
holiday_groups = list(range(len(daily_event_df_dict_with_score)))
if isinstance(holiday_groups, int):
holiday_groups = [holiday_groups]
is_found = False
for group_id in holiday_groups:
group_name = f"holiday_group_{group_id}"
event_df = daily_event_df_dict_with_score.get(group_name)
if event_df is not None and event_df["original_name"].str.contains(holiday_name_pattern).sum() > 0:
is_found = True
print(f"`{group_name}` contains events matching the provided pattern.\n"
f"This group includes {event_df['original_name'].nunique()} distinct events.\n")
with pd.option_context("display.max_rows", None):
display(event_df)
if not is_found:
print(f"No matching records found given pattern {holiday_name_pattern.__repr__()} "
f"and holiday groups {holiday_groups}.")
def _prune_holiday_by_score(
self,
score_result: Dict[str, List[float]],
score_result_avg: Dict[str, float],
min_n_days: int = 1,
min_same_sign_ratio: float = 0.66,
min_abs_avg_score: float = 0.05) -> Dict[str, Any]:
"""Removes events that have too few datapoints or inconsistent / negligible scores
given ``score_result`` and ``score_result_avg``.
Parameters
----------
score_result : `Dict`[`str`, `List`[`float`]]
A dictionary with keys being the names of all holiday events,
values being a list of scores of all dates corresponding to this event.
score_result_avg : `Dict`[`str`, `float`]
A dictionary with the same key as in ``result_dict["score_result_original"]``.
But the values are the average scores of each event across all occurrences.
min_n_days : `int`, default 1
Minimal number of occurrences for a holiday event to be kept before grouping.
min_same_sign_ratio : `float`, default 0.66
Threshold of the ratio of the same-sign scores for an event's occurrences.
For example, if an event has two occurrences, they both need to have positive or negative
scores for the ratio to achieve 0.66.
Similarly, if an event has 3 occurrences, at least 2 of them must have the same directional impact.
This parameter is intended to rule out holidays that have indefinite effects.
min_abs_avg_score : `float`, default 0.05
The minimal average score of an event (across all its occurrences) to be kept
before grouping.
When ``use_relative_score = True``, 0.05 means the effect must be greater than 5%.
Returns
-------
result : `Dict`[`str`, Any]
A dictionary with two keys: "score_result", "score_result_avg", values being
the same dictionary as the input ``score_result``, ``score_result_avg``,
but only with the remaining events after pruning.
"""
res_score = {}
res_score_avg = {}
for key, value in score_result.items():
# `key` is the name of the event.
# `value` is a list of scores, we need to check the following.
# First removes NAs before the following filtering.
value_non_na = [val for val in value if not np.isnan(val)]
# (1) It has minimum length `min_n_days`.
if len(value_non_na) < min_n_days:
continue
# (2) The ratio of same-sign scores is at least `min_same_sign_ratio`.
signs = [(score > 0) * 1 for score in value_non_na]
n_pos, n_neg = sum(signs), len(signs) - sum(signs)
if max(n_pos, n_neg) < min_same_sign_ratio * (n_pos + n_neg):
continue
# (3) The average score needs to meet `min_abs_avg_score` to be included.
if abs(score_result_avg[key]) < min_abs_avg_score:
continue
# (4) The average score is not NaN.
if np.isnan(score_result_avg[key]):
continue
res_score[key] = value
res_score_avg[key] = score_result_avg[key]
log_message(
message=f"Holidays before pruning: {len(score_result)}; after pruning: {len(res_score)}.",
level=LoggingLevelEnum.INFO
)
return {
"score_result": res_score,
"score_result_avg": res_score_avg
}
def expand_holiday_df_with_suffix(
holiday_df: pd.DataFrame,
holiday_date_col: str,
holiday_name_col: str,
holiday_impact_pre_num_days: int = 0,
holiday_impact_post_num_days: int = 0,
holiday_impact_dict: Optional[Dict[str, Tuple[int, int]]] = None,
get_suffix_func: Optional[Union[Callable, str]] = "wd_we") -> pd.DataFrame:
"""Expands an input holiday dataframe ``holiday_df`` to include the neighboring days
specified in ``holiday_impact_dict`` or through ``holiday_impact_pre_num_days`` and
`holiday_impact_post_num_days`.
Also adds suffixes generated by ``get_suffix_func`` to better model the effects
of events falling on different days of week.
Parameters
----------
holiday_df : `pandas.DataFrame`
Input holiday dataframe that contains the dates and names of the holidays.
holiday_date_col : `str`
Name of the holiday date column in ``holiday_df``.
holiday_name_col : `str`
Name of the holiday name column in ``holiday_df``.
holiday_impact_pre_num_days: `int`, default 0
Default number of days before the holiday that will be modeled for holiday effect if the given holiday
is not specified in ``holiday_impact_dict``.
holiday_impact_post_num_days: `int`, default 0
Default number of days after the holiday that will be modeled for holiday effect if the given holiday
is not specified in ``holiday_impact_dict``.
holiday_impact_dict : `Dict` [`str`, Any] or None, default None
A dictionary containing the neighboring impacting days of a certain holiday. This overrides the
default ``pre_num`` and ``post_num`` for each holiday specified here.
The key is the name of the holiday matching those in the provided ``holiday_df``.
The value is a tuple of two values indicating the number of neighboring days
before and after the holiday. For example, a valid dictionary may look like:
.. code-block:: python
holiday_impact_dict = {
"Christmas Day": [3, 3],
"Memorial Day": [0, 0]
}
get_suffix_func : Callable or `str` or None, default "wd_we"
A function that generates a suffix (usually a time feature e.g. "_WD" for weekday,
"_WE" for weekend) given an input date.
This can be used to estimate the interaction between floating holidays
and on which day they are getting observed.
We currently support two defaults:
- "wd_we" to generate suffixes based on whether the day falls on weekday or weekend.
- "dow_grouped" to generate three categories: ["_WD", "_Sat", "_Sun"].
If None, no suffix is added.
Returns
-------
expanded_holiday_df : `pandas.DataFrame`
An expansion of ``holiday_df`` after adding the neighboring dates provided in
``holiday_impact_dict`` and the suffix generated by ``get_suffix_func``.
For example, if ``"Christmas Day": [3, 3]`` and "wd_we" are used, events
such as "Christmas Day_WD_plus_1_WE" or "Christmas Day_WD_minus_3_WD" will be generated
for a Christmas that falls on Friday.
"""
error_message = f"`get_suffix_func` {get_suffix_func.__repr__()} is not supported! " \
f"Only supports None, Callable, \"dow_grouped\" or \"wd_we\"."
if get_suffix_func is None:
def get_suffix_func(x): return ""
elif get_suffix_func == "wd_we":
get_suffix_func = get_weekday_weekend_suffix
elif get_suffix_func == "dow_grouped":
get_suffix_func = get_dow_grouped_suffix
elif isinstance(get_suffix_func, Callable):
get_suffix_func = get_suffix_func
else:
raise NotImplementedError(error_message)
if holiday_impact_dict is None:
holiday_impact_dict = {}
expanded_holiday_df = pd.DataFrame()
for _, row in holiday_df.iterrows():
# Handles different holidays differently.
if row[holiday_name_col] in holiday_impact_dict.keys():
pre_search_days, post_search_days = holiday_impact_dict[row[holiday_name_col]]
else:
pre_search_days, post_search_days = holiday_impact_pre_num_days, holiday_impact_post_num_days
for i in range(-pre_search_days, post_search_days + 1):
original_dow_flag = get_suffix_func(row[holiday_date_col])
new_ts = (row[holiday_date_col] + timedelta(days=1) * i)
new_dow_flag = get_suffix_func(new_ts)
if i < 0:
suffix = f"{original_dow_flag}_minus_{-i}{new_dow_flag}"
elif i > 0:
suffix = f"{original_dow_flag}_plus_{i}{new_dow_flag}"
else:
suffix = f"{original_dow_flag}"
new_row = {
holiday_date_col: new_ts,
holiday_name_col: f"{row[holiday_name_col]}{suffix}",
}
expanded_holiday_df = pd.concat([
expanded_holiday_df,
pd.DataFrame.from_dict({k: [v] for k, v in new_row.items()})
], ignore_index=True)
return expanded_holiday_df.sort_values(holiday_date_col).reset_index(drop=True)
def split_events_into_dictionaries(
events_df,
events,
date_col=EVENT_DF_DATE_COL,
name_col=EVENT_DF_LABEL_COL,
default_category="Other"):
"""Splits pd.Dataframe(date, holiday) into separate dataframes, one per event
Can be used to create the `daily_event_df_dict` parameter for `forecast_silverkite`.
Each event specified in `events` gets its own effect in the model.
Other events are grouped together and modeled with the same effect
:param events_df: pd.DataFrame with date_col and name_col columns
contains events
:param events: list(str)
names of events in events_df.name_col.unique() to split into separate
dataframes
:param date_col: str, default "date"
column in event_df containing the date
:param name_col: str, default EVENT_DF_LABEL_COL
column in event_df containing the event name
:param default_category: str
name of default event
:return: dict(label: pd.Dataframe(date_col, name_col))
with keys = events + [default_category]
name_col column has a constant value = EVENT_INDICATOR
"""
result = {}
# separates rows corresponding to each event into their own dataframe
for event_name in events:
event_df = events_df[events_df[name_col] == event_name].copy()
if event_df.shape[0] > 0:
event_df[name_col] = EVENT_INDICATOR # All dates in this df are for the event
event_key = event_name.replace("'", "") # ensures patsy module can parse column name in formula
result[event_key] = event_df.drop_duplicates().reset_index(drop=True)
else:
warnings.warn(
f"Requested holiday '{event_name}' does not occur in the provided countries")
# groups other events into the same bucket
other_df = events_df[~events_df[name_col].isin(events)].copy()
if other_df.shape[0] > 0:
other_df[name_col] = EVENT_INDICATOR
default_category = default_category.replace("'", "")
result[default_category] = other_df.drop_duplicates().reset_index(drop=True)
# there must be no duplicated dates in each DataFrame
for k, df in result.items():
assert not any(df[date_col].duplicated())
return result
def get_holidays(countries, year_start, year_end):
"""This function extracts a holiday data frame for the period of interest
[year_start to year_end] for the given countries.
This is done using the holidays libraries in pypi:holidays-ext
Parameters
----------
countries : `list` [`str`]
countries for which we need holidays
year_start : `int`
first year of interest, inclusive
year_end : `int`
last year of interest, inclusive
Returns
-------
holiday_df_dict : `dict` [`str`, `pandas.DataFrame`]
- key: country name
- value: data frame with holidays for that country
Each data frame has two columns: EVENT_DF_DATE_COL, EVENT_DF_LABEL_COL
"""
country_holiday_dict = {}
year_list = list(range(year_start, year_end + 1))
country_holidays = get_hdays.get_holiday(
country_list=countries,
years=year_list
)
for country, holidays in country_holidays.items():
country_df = pd.DataFrame({
cst.EVENT_DF_DATE_COL: list(holidays.keys()),
cst.EVENT_DF_LABEL_COL: list(holidays.values())})
# Replaces any occurrence of "/" with ", " in order to avoid saving / loading error in
# `~greykite.framework.templates.pickle_utils` because a holiday name can be the key
# of a dictionary that will be used as directory name.
# For example, "Easter Monday [England/Wales/Northern Ireland]" will be casted to
# "Easter Monday [England, Wales, Northern Ireland]".
country_df[cst.EVENT_DF_LABEL_COL] = country_df[cst.EVENT_DF_LABEL_COL].str.replace("/", ", ")
country_df[cst.EVENT_DF_DATE_COL] = pd.to_datetime(country_df[cst.EVENT_DF_DATE_COL])
country_holiday_dict[country] = country_df
return country_holiday_dict
def add_event_window_multi(
event_df_dict,
time_col,
label_col,
time_delta="1D",
pre_num=1,
post_num=1,
pre_post_num_dict=None):
"""For a given dictionary of events data frames with a time_col and label_col
it adds shifted events prior and after the given events
For example if the event data frame includes the row '2019-12-25, Christmas' as a row
the function will produce dataframes with the events '2019-12-24, Christmas' and '2019-12-26, Christmas' if
pre_num and post_num are 1 or more.
Parameters
----------
event_df_dict: `dict` [`str`, `pandas.DataFrame`]
A dictionary of events data frames
with each having two columns: ``time_col`` and ``label_col``.
time_col: `str`
The column with the timestamp of the events.
This can be daily but does not have to be.
label_col : `str`
The column with labels for the events.
time_delta : `str`, default "1D"
The amount of the shift for each unit specified by a string
e.g. '1D' stands for one day delta
pre_num : `int`, default 1
The number of events to be added prior to the given event for each event in df.
post_num: `int`, default 1
The number of events to be added after to the given event for each event in df.
pre_post_num_dict : `dict` [`str`, (`int`, `int`)] or None, default None
Optionally override ``pre_num`` and ``post_num`` for each key in ``event_df_dict``.
For example, if ``event_df_dict`` has keys "US" and "India", this parameter
can be set to ``pre_post_num_dict = {"US": [1, 3], "India": [1, 2]}``,
denoting that the "US" ``pre_num`` is 1 and ``post_num`` is 3, and "India" ``pre_num`` is 1
and ``post_num`` is 2. Keys not specified by ``pre_post_num_dict`` use the default given by
``pre_num`` and ``post_num``.
Returns
-------
df : `dict` [`str`, `pandas.DataFrame`]
A dictionary of dataframes for each needed shift. For example if pre_num=2 and post_num=3.
2 + 3 = 5 data frames will be stored in the return dictionary.
"""
if pre_post_num_dict is None:
pre_post_num_dict = {}
shifted_df_dict = {}
for event_df_key, event_df in event_df_dict.items():
if event_df_key in pre_post_num_dict.keys():
pre_num0 = pre_post_num_dict[event_df_key][0]
post_num0 = pre_post_num_dict[event_df_key][1]
else:
pre_num0 = pre_num
post_num0 = post_num
df_dict0 = add_event_window(
df=event_df,
time_col=time_col,
label_col=label_col,
time_delta=time_delta,
pre_num=pre_num0,
post_num=post_num0,
events_name=event_df_key)
shifted_df_dict.update(df_dict0)
return shifted_df_dict
class LoggingLevelEnum(Enum):
"""Valid types of logging levels available to use."""
CRITICAL = 50
ERROR = 40
WARNING = 30
INFO = 20
DEBUG = 10
NOTSET = 0
def log_message(message, level=LoggingLevelEnum.INFO):
"""Adds a message to logger.
Parameters
----------
message : `any`
The message to be added to logger.
level : `Enum`
One of the levels in the `~greykite.common.enums.LoggingLevelEnum`.
"""
if level.name not in list(LoggingLevelEnum.__members__):
raise ValueError(f"{level} not found, it must be a member of the LoggingLevelEnum class.")
logger.log(level.value, message)
def update_dictionary(default_dict, overwrite_dict=None, allow_unknown_keys=True):
"""Adds default key-value pairs to items in ``overwrite_dict``.
Merges the items in ``default_dict`` and ``overwrite_dict``,
preferring ``overwrite_dict`` if there are conflicts.
Parameters
----------
default_dict: `dict`
Dictionary of default values.
overwrite_dict: `dict` or None, optional, default None
User-provided dictionary that overrides the defaults.
allow_unknown_keys: `bool`, optional, default True
If false, raises an error if ``overwrite_dict`` contains a key that is
not in ``default_dict``.
Raises
------
ValueError
if ``allow_unknown_keys`` is False and ``overwrite_dict``
has keys that are not in ``default_dict``.
Returns
-------
updated_dict : `dict`
Updated dictionary.
Returns ``overwrite_dicts``, with default values added
based on ``default_dict``.
"""
if overwrite_dict is None:
overwrite_dict = {}
if not allow_unknown_keys:
extra_keys = overwrite_dict.keys() - default_dict.keys()
if extra_keys:
raise ValueError(f"Unexpected key(s) found: {extra_keys}. "
f"The valid keys are: {default_dict.keys()}")
return dict(default_dict, **overwrite_dict)
def describe_timeseries(df, time_col):
"""Checks if a time series consists of equal time increments
and if it is in increasing order.
:param df: data.frame which includes the time column in datetime format
:param time_col: time column
:return: a dictionary with following items
- dataframe ("df") with added delta columns
- "regular_increments" booleans to see if time deltas as the same
- "increasing" a boolean to denote if the time increments are increasing
- "min_timestamp": minimum timestamp in data
- "max_timestamp": maximum timestamp in data
- "mean_increment_secs": mean of increments in seconds
- "min_increment_secs": minimum of increments in seconds
- "median_increment_secs": median of increments in seconds
- "mean_delta": mean of time increments
- "min_delta": min of the time increments
- "max_delta": max of the time increments
- "median_delta": median of the time increments
- "freq_in_secs": the frequency of the timeseries in seconds which is defined to be the median time-gap
- "freq_in_days": the frequency of the timeseries in days which is defined to be the median time-gap
- "freq_in_timedelta": the frequency of the timeseries in `datetime.timedelta` which is defined to be the median time-gap
"""
df = df.copy(deep=True)
df[time_col] = pd.to_datetime(df[time_col])
if df.shape[0] < 2:
raise Exception("dataframe needs to have at least two rows")
df["delta"] = (
df[time_col] - df[time_col].shift()).fillna(pd.Timedelta(seconds=0))
df["delta_sec"] = df["delta"].values / np.timedelta64(1, "s")
delta_sec = df["delta_sec"][1:]
mean_increment_secs = np.mean(delta_sec)
min_increment_secs = min(delta_sec)
median_increment_secs = np.median(delta_sec)
regular_increments = (max(delta_sec) == min(delta_sec))
increasing = min(delta_sec > 0)
min_timestamp = df[time_col].min()
max_timestamp = df[time_col].max()
delta = df["delta"][1:]
min_delta = min(delta)
max_delta = max(delta)
mean_delta = np.mean(delta)
median_delta = np.median(delta)
# The frequency is defined by the median time-gap
freq_in_secs = median_increment_secs
freq_in_days = freq_in_secs / (24 * 3600)
freq_in_timedelta = datetime.timedelta(days=freq_in_days)
return {
"df": df,
"regular_increments": regular_increments,
"increasing": increasing,
"min_timestamp": min_timestamp,
"max_timestamp": max_timestamp,
"mean_increment_secs": mean_increment_secs,
"min_increment_secs": min_increment_secs,
"median_increment_secs": median_increment_secs,
"mean_delta": mean_delta,
"median_delta": median_delta,
"min_delta": min_delta,
"max_delta": max_delta,
"freq_in_secs": freq_in_secs,
"freq_in_days": freq_in_days,
"freq_in_timedelta": freq_in_timedelta
}
The provided code snippet includes necessary dependencies for implementing the `get_auto_holidays` function. Write a Python function `def get_auto_holidays( df: pd.DataFrame, time_col: str, value_col: str, start_year: int, end_year: int, pre_num: int = 2, post_num: int = 2, pre_post_num_dict: Optional[Dict[str, pd.DataFrame]] = None, holiday_lookup_countries: List[str] = ("UnitedStates", "India", "UnitedKingdom"), holidays_to_model_separately: Optional[List[str]] = None, daily_event_df_dict: Optional[Dict] = None, auto_holiday_params: Optional[Dict] = None)` to solve the following problem:
Automatically group holidays and their neighboring days based on estimated holiday impact. Parameters ---------- df : `pandas.DataFrame` The timeseries data used to infer holiday impact if no ``df`` is passed through ``auto_holiday_params``. time_col : `str` The column name for timestamps in ``df`` that will be used for holiday impact estimation in ``HolidayGrouper``. If ``time_col`` is passed in through ``auto_holiday_params``, this will be ignored. value_col : `str` The column name for values in ``df`` that will be used for holiday impact estimation in ``HolidayGrouper``. If ``value_col`` is passed in through ``auto_holiday_params``, this will be ignored. start_year : `int` Year of first training data point, used to generate holiday events based on ``holiday_lookup_countries``. This will not be used if `holiday_df` is passed in through ``auto_holiday_params``. end_year : `int` Year of last forecast data point, used to generate holiday events based on ``holiday_lookup_countries``. This will not be used if `holiday_df` is passed in through ``auto_holiday_params``. pre_num : `int`, default 2 Model holiday effects for ``pre_num`` days before the holiday. This will be used as ``holiday_impact_pre_num_days`` when constructing ``HolidayGrouper`` if ``holiday_impact_pre_num_days`` is not passed in though ``auto_holiday_params``. post_num : `int`, default 2 Model holiday effects for ``post_num`` days before the holiday. This will be used as ``holiday_impact_post_num_days`` when constructing ``HolidayGrouper`` if ``holiday_impact_post_num_days`` is not passed in though ``auto_holiday_params``. pre_post_num_dict : `dict` [`str`, (`int`, `int`)] or None, default None Overrides ``pre_num`` and ``post_num`` for each holiday in ``holidays_to_model_separately`` and in ``HolidayGrouper`` (as ``holiday_impact_dict``) if ``holiday_impact_dict`` is not passed in though ``auto_holiday_params``. For example, if ``holidays_to_model_separately`` contains "Thanksgiving" and "Labor Day", this parameter can be set to ``{"Thanksgiving": [1, 3], "Labor Day": [1, 2]}``, denoting that the "Thanksgiving" ``pre_num`` is 1 and ``post_num`` is 3, and "Labor Day" ``pre_num`` is 1 and ``post_num`` is 2. Holidays not specified use the default given by ``pre_num`` and ``post_num``. holiday_lookup_countries : `list` [`str`], default ("UnitedStates", "India", "UnitedKingdom") A list of countries to look up holidays. This will be used with `daily_event_df_dict` to generate `holiday_df` that contains holidays that will be modeled when ``holiday_df`` is not passed in through ``auto_holiday_params``. Otherwise, ``auto_holiday_params["holiday_df"]`` will be used and this will be ignored. holidays_to_model_separately : `list` [`str`] or None Which holidays to include in the model by themselves. These holidays will not be passed into the ``HolidayGrouper``. The model creates a separate key, value for each item in ``holidays_to_model_separately`` and their neighboring days. Generally, this is recommended to be kept as `None` unless some specific assumptions on holidays need to be applied. daily_event_df_dict : `dict` [`str`, `pandas.DataFrame`] or None, default None A dictionary of holidays to be used in ``HolidayGrouper``to generate `holiday_df` which contains holidays that will be modeled when ``holiday_df`` is not passed in through ``auto_holiday_params``. Each key presents a holiday name, and the values are data frames, with a date column that records all dates for the corresponding holiday. Otherwise, ``auto_holiday_params["holiday_df"]`` will be used and this will be ignored. auto_holiday_params: `dict` or None, default None This dictionary takes in parameters that can be passed in and used by holiday grouper when ``auto_holiday`` is set to `True`. It overwrites all configurations passed in or generated by other inputs. Examples of arguments that can be included here include: ``"df"`` : `str` Data Frame used by `HolidayGrouper` to infer holiday impact. If this exists, ``df`` will be ignored. ``"holiday_df"`` : `str` Input holiday dataframe that contains the dates and names of the holidays. If this exists, the following parameters used to generate holiday list will be ignored: * "start_year" * "end_year" * "holiday_lookup_countries" * "daily_event_df_dict" ``"holiday_date_col"`` : `str` This will be used as the date column when ``holiday_df`` is passed in through ``auto_holiday_params`` ``"holiday_name_col"`` : `str` This will be used as the holiday name column when ``holiday_df`` is passed in through ``auto_holiday_params`` Please refer to `~greykite.algo.common.holiday_grouper.HolidayGrouper` for more details. Returns ------- daily_event_df_dict : `dict` [`str`, `pandas.DataFrame` [cst.EVENT_DF_DATE_COL, cst.EVENT_DF_LABEL_COL]] A dictionary with the keys being the holiday group names and values being the dataframes including 2 columns: - EVENT_DF_DATE_COL : the events' occurrence dates. - EVENT_DF_LABEL_COL : the events' names. Suitable for use as ``daily_event_df_dict`` parameter in `forecast_silverkite`.
Here is the function:
def get_auto_holidays(
df: pd.DataFrame,
time_col: str,
value_col: str,
start_year: int,
end_year: int,
pre_num: int = 2,
post_num: int = 2,
pre_post_num_dict: Optional[Dict[str, pd.DataFrame]] = None,
holiday_lookup_countries: List[str] = ("UnitedStates", "India", "UnitedKingdom"),
holidays_to_model_separately: Optional[List[str]] = None,
daily_event_df_dict: Optional[Dict] = None,
auto_holiday_params: Optional[Dict] = None):
"""Automatically group holidays and their neighboring days based on estimated holiday impact.
Parameters
----------
df : `pandas.DataFrame`
The timeseries data used to infer holiday impact if no ``df`` is passed through ``auto_holiday_params``.
time_col : `str`
The column name for timestamps in ``df`` that will be used for holiday impact estimation in ``HolidayGrouper``.
If ``time_col`` is passed in through ``auto_holiday_params``, this will be ignored.
value_col : `str`
The column name for values in ``df`` that will be used for holiday impact estimation in ``HolidayGrouper``.
If ``value_col`` is passed in through ``auto_holiday_params``, this will be ignored.
start_year : `int`
Year of first training data point, used to generate holiday events based on ``holiday_lookup_countries``.
This will not be used if `holiday_df` is passed in through ``auto_holiday_params``.
end_year : `int`
Year of last forecast data point, used to generate holiday events based on ``holiday_lookup_countries``.
This will not be used if `holiday_df` is passed in through ``auto_holiday_params``.
pre_num : `int`, default 2
Model holiday effects for ``pre_num`` days before the holiday. This will be used as
``holiday_impact_pre_num_days`` when constructing ``HolidayGrouper`` if ``holiday_impact_pre_num_days``
is not passed in though ``auto_holiday_params``.
post_num : `int`, default 2
Model holiday effects for ``post_num`` days before the holiday. This will be used as
``holiday_impact_post_num_days`` when constructing ``HolidayGrouper`` if ``holiday_impact_post_num_days``
is not passed in though ``auto_holiday_params``.
pre_post_num_dict : `dict` [`str`, (`int`, `int`)] or None, default None
Overrides ``pre_num`` and ``post_num`` for each holiday in
``holidays_to_model_separately`` and in ``HolidayGrouper`` (as ``holiday_impact_dict``)
if ``holiday_impact_dict`` is not passed in though ``auto_holiday_params``.
For example, if ``holidays_to_model_separately`` contains "Thanksgiving" and "Labor Day",
this parameter can be set to ``{"Thanksgiving": [1, 3], "Labor Day": [1, 2]}``,
denoting that the "Thanksgiving" ``pre_num`` is 1 and ``post_num`` is 3, and "Labor Day"
``pre_num`` is 1 and ``post_num`` is 2.
Holidays not specified use the default given by ``pre_num`` and ``post_num``.
holiday_lookup_countries : `list` [`str`], default ("UnitedStates", "India", "UnitedKingdom")
A list of countries to look up holidays. This will be used with `daily_event_df_dict` to
generate `holiday_df` that contains holidays that will be modeled when ``holiday_df`` is
not passed in through ``auto_holiday_params``. Otherwise, ``auto_holiday_params["holiday_df"]``
will be used and this will be ignored.
holidays_to_model_separately : `list` [`str`] or None
Which holidays to include in the model by themselves. These holidays will not be passed into the
``HolidayGrouper``. The model creates a separate key, value for each item in ``holidays_to_model_separately``
and their neighboring days. Generally, this is recommended to be kept as `None` unless some specific
assumptions on holidays need to be applied.
daily_event_df_dict : `dict` [`str`, `pandas.DataFrame`] or None, default None
A dictionary of holidays to be used in ``HolidayGrouper``to generate `holiday_df` which contains holidays
that will be modeled when ``holiday_df`` is not passed in through ``auto_holiday_params``.
Each key presents a holiday name, and the values are data frames, with a date column that records all dates
for the corresponding holiday.
Otherwise, ``auto_holiday_params["holiday_df"]`` will be used and this will be ignored.
auto_holiday_params: `dict` or None, default None
This dictionary takes in parameters that can be passed in and used by holiday grouper when
``auto_holiday`` is set to `True`. It overwrites all configurations passed in or generated by
other inputs.
Examples of arguments that can be included here include:
``"df"`` : `str`
Data Frame used by `HolidayGrouper` to infer holiday impact. If this exists,
``df`` will be ignored.
``"holiday_df"`` : `str`
Input holiday dataframe that contains the dates and names of the holidays.
If this exists, the following parameters used to generate holiday list will be ignored:
* "start_year"
* "end_year"
* "holiday_lookup_countries"
* "daily_event_df_dict"
``"holiday_date_col"`` : `str`
This will be used as the date column when ``holiday_df`` is passed in through
``auto_holiday_params``
``"holiday_name_col"`` : `str`
This will be used as the holiday name column when ``holiday_df`` is passed in through
``auto_holiday_params``
Please refer to
`~greykite.algo.common.holiday_grouper.HolidayGrouper` for more details.
Returns
-------
daily_event_df_dict : `dict` [`str`, `pandas.DataFrame` [cst.EVENT_DF_DATE_COL, cst.EVENT_DF_LABEL_COL]]
A dictionary with the keys being the holiday group names and values being the dataframes including 2 columns:
- EVENT_DF_DATE_COL : the events' occurrence dates.
- EVENT_DF_LABEL_COL : the events' names.
Suitable for use as ``daily_event_df_dict`` parameter in `forecast_silverkite`.
"""
# Initializes `group_holiday_params`, the parameters to pass in for function `group_holidays`.
if auto_holiday_params is None:
group_holiday_params = dict()
else:
group_holiday_params = auto_holiday_params.copy()
# Initializes `grouper_init_params`, the parameters for `HolidayGrouper`. Anything passed through
# `auto_holiday_params`, which are stored in `group_holiday_params`, will be used for initializations.
# Uses `pop` to remove these parameters from `group_holiday_params` if existed at the same time.
# Handles `group_holiday_params["df"]` separately to avoid an ambiguity error on using `or` to check if it is empty.
if group_holiday_params.get("df") is None:
group_holiday_params["df"] = df
grouper_init_params = dict(
df=group_holiday_params.pop("df"), # This will be standardized and updated later.
time_col=group_holiday_params.pop("time_col", None) or time_col,
value_col=group_holiday_params.pop("value_col", None) or value_col,
holiday_df=group_holiday_params.pop("holiday_df", None), # This will be updated later.
holiday_date_col=group_holiday_params.pop("holiday_date_col", None) or cst.EVENT_DF_DATE_COL,
# This will be standardized and updated later.
holiday_name_col=group_holiday_params.pop("holiday_name_col", None) or cst.EVENT_DF_LABEL_COL,
# This will be standardized and updated later.
holiday_impact_pre_num_days=group_holiday_params.pop("holiday_impact_pre_num_days", None) or pre_num,
holiday_impact_post_num_days=group_holiday_params.pop("holiday_impact_post_num_days", None) or post_num,
holiday_impact_dict=group_holiday_params.pop("holiday_impact_dict", None) or pre_post_num_dict)
# Checks and updates if any other parameter for `HolidayGrouper` exists in `group_holiday_params` that has not
# been initialized through `grouper_init_params`.
# ``.copy()`` is used below to avoid altering the dictionary keys within iteration on same keys
group_holiday_params_key_copy = group_holiday_params.copy().keys()
for key in group_holiday_params_key_copy:
if key in inspect.signature(HolidayGrouper).parameters:
grouper_init_params[key] = group_holiday_params.pop(key)
# constructs initial `holiday_df`. If `holiday_df` is passed through `auto_holiday_params`, use it. Otherwise,
# constructs it based on input country list and/or user input holidays through `daily_event_df_dict`.
if grouper_init_params["holiday_df"] is not None:
holiday_df = grouper_init_params["holiday_df"].copy()
holiday_date_col = grouper_init_params["holiday_date_col"]
holiday_name_col = grouper_init_params["holiday_name_col"]
if not {holiday_date_col, holiday_name_col}.issubset(holiday_df.columns):
raise ValueError(f"Columns `{holiday_date_col}` and/or "
f"`{holiday_name_col}` not found in input `holiday_df`.")
# Standardizes `holiday_name_col` and `holiday_name_col` in `holiday_df`.
holiday_df = holiday_df.rename(columns={
holiday_date_col: cst.EVENT_DF_DATE_COL,
holiday_name_col: cst.EVENT_DF_LABEL_COL
})
else:
# Constructs `holiday_df` based on input country list and/or user input holidays through `daily_event_df_dict`.
# When `holiday_lookup_countries` is not empty, the corresponding `holiday_df_from_countries` is constructed.
holiday_df_from_countries = None
if len(holiday_lookup_countries) > 0:
holiday_df_from_countries_dict = get_holidays(
countries=holiday_lookup_countries,
year_start=start_year - 1,
year_end=end_year + 1)
holiday_df_from_countries_list = [holidays for _, holidays in holiday_df_from_countries_dict.items()]
holiday_df_from_countries = pd.concat(holiday_df_from_countries_list)
# Removes the observed holidays and only keeps the original holidays. This assumes that the original
# holidays are consistently present in the output of `get_holidays` when their observed counterparts are
# included. This assumption has been verified for all available countries within the date range of
# 2015 to 2030.
cond_observed_holiday = holiday_df_from_countries[cst.EVENT_DF_LABEL_COL].apply(
lambda x: True if any(i in x for i in ["(Observed)", "(observed)"]) else False)
holiday_df_from_countries = holiday_df_from_countries.loc[~cond_observed_holiday, [cst.EVENT_DF_DATE_COL, cst.EVENT_DF_LABEL_COL]]
# When `daily_event_df_dict` is not empty, its format gets converted to dataframe `holiday_df_from_dict`.
holiday_df_from_dict = None
if daily_event_df_dict:
holiday_df_from_dict_list = []
for holiday_name, holiday_dates in daily_event_df_dict.items():
holiday_dates[cst.EVENT_DF_LABEL_COL] = holiday_name
# Checks and finds the first column where values can be recognized by `pd.to_datetime`, uses it as
# the date column and cast it as `cst.EVENT_DF_DATE_COL`.
flag = False
for col in holiday_dates.columns:
try:
holiday_dates[cst.EVENT_DF_DATE_COL] = pd.to_datetime(holiday_dates[col])
flag = True
except ValueError:
continue
# When a valid date column is found, breaks the loop.
if flag:
break
if flag is False:
raise ValueError(f"No valid date column is found in data frames in `daily_event_df_dict` to use "
f"as {cst.EVENT_DF_DATE_COL}.")
holiday_df_from_dict_list.append(holiday_dates[[cst.EVENT_DF_DATE_COL, cst.EVENT_DF_LABEL_COL]])
holiday_df_from_dict = pd.concat(holiday_df_from_dict_list)
if (holiday_df_from_countries is None) & (holiday_df_from_dict is None):
raise ValueError("Automatic holiday grouping is enabled. Holiday list needs to be specified through"
"`holiday_lookup_countries` or `daily_event_df_dict`. Currently, None is found.")
holiday_df = (
pd.concat([holiday_df_from_countries, holiday_df_from_dict])
.drop_duplicates()
.reset_index(drop=True)
)
# Makes sure the `holiday_date_col` and `holiday_name_col` in `grouper_init_params` are standardized values.
grouper_init_params["holiday_date_col"] = cst.EVENT_DF_DATE_COL
grouper_init_params["holiday_name_col"] = cst.EVENT_DF_LABEL_COL
# Separates holidays specified in `holidays_to_model_separately` from `holiday_df`, so that they will not be passed
# into `HolidayGrouper`. When `holidays_to_model_separately` is not empty, a dictionary is constructed with
# each key presents one holiday or a specific neighboring day for all holidays in `holidays_to_model_separately`.
if holidays_to_model_separately is None:
holidays_to_model_separately = []
elif holidays_to_model_separately == "auto":
holidays_to_model_separately = []
log_message("Automatic holiday grouping is enabled. The `holidays_to_model_separately` parameter should be "
"`None` or a list. Since the current input is 'auto', it is set to an empty list and no"
"holiday will be modeled separately.",
LoggingLevelEnum.WARNING)
if not isinstance(holidays_to_model_separately, (list, tuple)):
raise ValueError(
f"Automatic holiday grouping is enabled. The `holidays_to_model_separately` parameter should be `None` or "
f"a list, found {holidays_to_model_separately}")
elif len(holidays_to_model_separately) == 0:
holiday_df_exclude_separate = holiday_df.copy()
holiday_df_dict_separate_with_effect = dict()
else:
holiday_to_separate_condition = holiday_df[cst.EVENT_DF_LABEL_COL].isin(holidays_to_model_separately)
holiday_df_exclude_separate = holiday_df[~holiday_to_separate_condition]
holiday_df_separate = holiday_df[holiday_to_separate_condition]
# Initializes the holiday dictionary for holidays modeled separately. Each key corresponds to
# a holiday.
holiday_df_dict_separate_with_effect = split_events_into_dictionaries(
events_df=holiday_df_separate,
events=holidays_to_model_separately)
# Removes "'" from keys in `pre_post_num_dict_processed` because they are
# removed from holiday names by `split_events_into_dictionaries`.
if grouper_init_params["holiday_impact_dict"]:
pre_post_num_dict_processed = grouper_init_params["holiday_impact_dict"].copy()
for key in pre_post_num_dict.keys():
new_key = key.replace("'", "")
pre_post_num_dict_processed[new_key] = pre_post_num_dict_processed.pop(key)
else:
pre_post_num_dict_processed = dict()
# Adds shifted events.
shifted_event_dict = add_event_window_multi(
event_df_dict=holiday_df_dict_separate_with_effect,
time_col=cst.EVENT_DF_DATE_COL,
label_col=cst.EVENT_DF_LABEL_COL,
time_delta="1D",
pre_num=grouper_init_params["holiday_impact_pre_num_days"],
post_num=grouper_init_params["holiday_impact_post_num_days"],
pre_post_num_dict=pre_post_num_dict_processed)
holiday_df_dict_separate_with_effect.update(shifted_event_dict)
# Raises warning if `holiday_df_exclude_separate` becomes empty, as there will be no holidays for grouping.
# Returns `holiday_df_dict_separate_with_effect` in this case.
if holiday_df_exclude_separate.empty:
log_message(f"All input holidays are modeled separately and no remaining holidays can be used by the "
f"holiday grouper. A dictionary of all holidays with effects modeled separately is returned.",
LoggingLevelEnum.WARNING)
return holiday_df_dict_separate_with_effect
# Reassigns `grouper_init_params["holiday_df"]` with `holiday_df_exclude_separate` that excludes holidays that are
# modeled separately.
grouper_init_params["holiday_df"] = holiday_df_exclude_separate.copy()
# Checks if `df` in `grouper_init_params` is None or empty.
if (grouper_init_params["df"] is None) or grouper_init_params["df"].empty:
raise ValueError("Automatic holiday grouping is enabled. Dataframe cannot be `None` or empty.")
# Checks if `df`, `time_col`, `value_col` in `grouper_init_params` are valid.
# Reassigns the values as they can potentially be overriden by `auto_holiday_params`.
df = grouper_init_params["df"].copy()
time_col = grouper_init_params["time_col"]
value_col = grouper_init_params["value_col"]
if not {time_col, value_col}.issubset(df.columns):
raise ValueError("Input `df` for holiday grouper does not contain `time_col` or `value_col`.")
# First pre-processes `df` to determine if it is appropriate for holiday effects inference.
# If the data is sub-daily, aggregates it to daily before grouping.
# If the data is less granular than daily, raise ValueError.
# Converts time column.
df[time_col] = pd.to_datetime(df[time_col])
df = df.sort_values(time_col).reset_index(drop=True)
# First infers frequency, if more granular than daily, aggregates it to daily.
# If less granular than daily, raise ValueError.
time_stats = describe_timeseries(df=df, time_col=time_col)
if time_stats["freq_in_days"] > 1.0:
raise ValueError("Input holiday df for holiday grouper has frequency less than daily. "
"Holiday effect cannot be inferred.")
elif time_stats["freq_in_days"] < 1.0:
df_tmp = df.resample("D", on=time_col).agg({value_col: np.nanmean})
df = (df_tmp.drop(columns=time_col).reset_index() if time_col in df_tmp.columns
else df_tmp.reset_index())
# Reassigns back processed `df`.
grouper_init_params["df"] = df
# Calls holiday grouper.
hg = HolidayGrouper(
**grouper_init_params)
hg.group_holidays(
**group_holiday_params)
daily_event_df_dict_exclude_separate = hg.result_dict["daily_event_df_dict"]
# Adds back holidays that are modeled separately with their neighboring days.
daily_event_df_dict_final = update_dictionary(
daily_event_df_dict_exclude_separate,
overwrite_dict=holiday_df_dict_separate_with_effect)
return daily_event_df_dict_final | Automatically group holidays and their neighboring days based on estimated holiday impact. Parameters ---------- df : `pandas.DataFrame` The timeseries data used to infer holiday impact if no ``df`` is passed through ``auto_holiday_params``. time_col : `str` The column name for timestamps in ``df`` that will be used for holiday impact estimation in ``HolidayGrouper``. If ``time_col`` is passed in through ``auto_holiday_params``, this will be ignored. value_col : `str` The column name for values in ``df`` that will be used for holiday impact estimation in ``HolidayGrouper``. If ``value_col`` is passed in through ``auto_holiday_params``, this will be ignored. start_year : `int` Year of first training data point, used to generate holiday events based on ``holiday_lookup_countries``. This will not be used if `holiday_df` is passed in through ``auto_holiday_params``. end_year : `int` Year of last forecast data point, used to generate holiday events based on ``holiday_lookup_countries``. This will not be used if `holiday_df` is passed in through ``auto_holiday_params``. pre_num : `int`, default 2 Model holiday effects for ``pre_num`` days before the holiday. This will be used as ``holiday_impact_pre_num_days`` when constructing ``HolidayGrouper`` if ``holiday_impact_pre_num_days`` is not passed in though ``auto_holiday_params``. post_num : `int`, default 2 Model holiday effects for ``post_num`` days before the holiday. This will be used as ``holiday_impact_post_num_days`` when constructing ``HolidayGrouper`` if ``holiday_impact_post_num_days`` is not passed in though ``auto_holiday_params``. pre_post_num_dict : `dict` [`str`, (`int`, `int`)] or None, default None Overrides ``pre_num`` and ``post_num`` for each holiday in ``holidays_to_model_separately`` and in ``HolidayGrouper`` (as ``holiday_impact_dict``) if ``holiday_impact_dict`` is not passed in though ``auto_holiday_params``. For example, if ``holidays_to_model_separately`` contains "Thanksgiving" and "Labor Day", this parameter can be set to ``{"Thanksgiving": [1, 3], "Labor Day": [1, 2]}``, denoting that the "Thanksgiving" ``pre_num`` is 1 and ``post_num`` is 3, and "Labor Day" ``pre_num`` is 1 and ``post_num`` is 2. Holidays not specified use the default given by ``pre_num`` and ``post_num``. holiday_lookup_countries : `list` [`str`], default ("UnitedStates", "India", "UnitedKingdom") A list of countries to look up holidays. This will be used with `daily_event_df_dict` to generate `holiday_df` that contains holidays that will be modeled when ``holiday_df`` is not passed in through ``auto_holiday_params``. Otherwise, ``auto_holiday_params["holiday_df"]`` will be used and this will be ignored. holidays_to_model_separately : `list` [`str`] or None Which holidays to include in the model by themselves. These holidays will not be passed into the ``HolidayGrouper``. The model creates a separate key, value for each item in ``holidays_to_model_separately`` and their neighboring days. Generally, this is recommended to be kept as `None` unless some specific assumptions on holidays need to be applied. daily_event_df_dict : `dict` [`str`, `pandas.DataFrame`] or None, default None A dictionary of holidays to be used in ``HolidayGrouper``to generate `holiday_df` which contains holidays that will be modeled when ``holiday_df`` is not passed in through ``auto_holiday_params``. Each key presents a holiday name, and the values are data frames, with a date column that records all dates for the corresponding holiday. Otherwise, ``auto_holiday_params["holiday_df"]`` will be used and this will be ignored. auto_holiday_params: `dict` or None, default None This dictionary takes in parameters that can be passed in and used by holiday grouper when ``auto_holiday`` is set to `True`. It overwrites all configurations passed in or generated by other inputs. Examples of arguments that can be included here include: ``"df"`` : `str` Data Frame used by `HolidayGrouper` to infer holiday impact. If this exists, ``df`` will be ignored. ``"holiday_df"`` : `str` Input holiday dataframe that contains the dates and names of the holidays. If this exists, the following parameters used to generate holiday list will be ignored: * "start_year" * "end_year" * "holiday_lookup_countries" * "daily_event_df_dict" ``"holiday_date_col"`` : `str` This will be used as the date column when ``holiday_df`` is passed in through ``auto_holiday_params`` ``"holiday_name_col"`` : `str` This will be used as the holiday name column when ``holiday_df`` is passed in through ``auto_holiday_params`` Please refer to `~greykite.algo.common.holiday_grouper.HolidayGrouper` for more details. Returns ------- daily_event_df_dict : `dict` [`str`, `pandas.DataFrame` [cst.EVENT_DF_DATE_COL, cst.EVENT_DF_LABEL_COL]] A dictionary with the keys being the holiday group names and values being the dataframes including 2 columns: - EVENT_DF_DATE_COL : the events' occurrence dates. - EVENT_DF_LABEL_COL : the events' names. Suitable for use as ``daily_event_df_dict`` parameter in `forecast_silverkite`. |
167,378 | import functools
import logging
import math
import sys
import warnings
from dataclasses import dataclass
from typing import Optional
import cvxpy as cp
import numpy as np
import pandas as pd
import plotly
import plotly.express as px
from plotly import graph_objects as go
from plotly.subplots import make_subplots
from scipy.linalg import sqrtm
from sklearn.exceptions import NotFittedError
from greykite.algo.reconcile.hierarchical_relationship import HierarchicalRelationship
from greykite.common.python_utils import reorder_columns
The provided code snippet includes necessary dependencies for implementing the `get_weight_matrix` function. Write a Python function `def get_weight_matrix(weights, n_forecasts, name, default_weights)` to solve the following problem:
Returns a diagonal weight matrix with shape (``n_forecasts``, ``n_forecasts``) and Frobenius norm sqrt(`n_forecasts`). Parameters ---------- weights : `list` [`float`] or `str` or None What weights to use. - If a list, returns a diagonal matrix with the list values on the diagonal. These values specify the weight for each timeseries. In ``ReconcileAdditiveForecasts``, weights are applied to the matrix whose rows are reordered to canonical form (transposed output of ``reorder_columns``) - If a string, determined by ``default_weights``. - If None, the identity matrix (equal weights). The specified weights are normalized in the output. n_forecasts : `int` The number of forecasts (shape of the output). name : `str` The name of the weight matrix. default_weights : `dict` [`str`, `numpy.array`] Default weights to use if ``weights`` is a string. Values should be square matrices with shape (``n_forecasts``, ``n_forecasts``). Returns ------- weight_matrix : `numpy.array` Weights to apply to the errors. Diagonal matrix with shape (``n_forecasts``, ``n_forecasts``) and Frobenius norm sqrt(`n_forecasts`).
Here is the function:
def get_weight_matrix(weights, n_forecasts, name, default_weights):
"""Returns a diagonal weight matrix with shape (``n_forecasts``, ``n_forecasts``)
and Frobenius norm sqrt(`n_forecasts`).
Parameters
----------
weights : `list` [`float`] or `str` or None
What weights to use.
- If a list, returns a diagonal matrix with the list values on the diagonal.
These values specify the weight for each timeseries.
In ``ReconcileAdditiveForecasts``, weights are applied to the matrix
whose rows are reordered to canonical form (transposed output of ``reorder_columns``)
- If a string, determined by ``default_weights``.
- If None, the identity matrix (equal weights).
The specified weights are normalized in the output.
n_forecasts : `int`
The number of forecasts (shape of the output).
name : `str`
The name of the weight matrix.
default_weights : `dict` [`str`, `numpy.array`]
Default weights to use if ``weights`` is a string.
Values should be square matrices with shape (``n_forecasts``, ``n_forecasts``).
Returns
-------
weight_matrix : `numpy.array`
Weights to apply to the errors.
Diagonal matrix with shape (``n_forecasts``, ``n_forecasts``)
and Frobenius norm sqrt(`n_forecasts`).
"""
if weights is None:
weight_matrix = np.eye(n_forecasts)
elif isinstance(weights, str):
if weights in default_weights:
weight_matrix = default_weights[weights]
logging.info(f"weight for {name} is {weight_matrix}")
else:
raise ValueError(
f"The requested weight '{weights}' for `{name}` is not found. "
f"Must be one of {list(default_weights.keys())}")
else:
weight_matrix = np.diag(weights)
if not isinstance(weight_matrix, np.ndarray) or weight_matrix.shape != (n_forecasts, n_forecasts):
raise ValueError(
f"Expected square matrix with size {n_forecasts}, but `{name}` has "
f"weight matrix with shape {weight_matrix.shape}")
target_norm = np.linalg.norm(np.eye(n_forecasts))
weight_matrix = weight_matrix * target_norm / np.linalg.norm(weight_matrix)
return weight_matrix | Returns a diagonal weight matrix with shape (``n_forecasts``, ``n_forecasts``) and Frobenius norm sqrt(`n_forecasts`). Parameters ---------- weights : `list` [`float`] or `str` or None What weights to use. - If a list, returns a diagonal matrix with the list values on the diagonal. These values specify the weight for each timeseries. In ``ReconcileAdditiveForecasts``, weights are applied to the matrix whose rows are reordered to canonical form (transposed output of ``reorder_columns``) - If a string, determined by ``default_weights``. - If None, the identity matrix (equal weights). The specified weights are normalized in the output. n_forecasts : `int` The number of forecasts (shape of the output). name : `str` The name of the weight matrix. default_weights : `dict` [`str`, `numpy.array`] Default weights to use if ``weights`` is a string. Values should be square matrices with shape (``n_forecasts``, ``n_forecasts``). Returns ------- weight_matrix : `numpy.array` Weights to apply to the errors. Diagonal matrix with shape (``n_forecasts``, ``n_forecasts``) and Frobenius norm sqrt(`n_forecasts`). |
167,379 | import functools
import logging
import math
import sys
import warnings
from dataclasses import dataclass
from typing import Optional
import cvxpy as cp
import numpy as np
import pandas as pd
import plotly
import plotly.express as px
from plotly import graph_objects as go
from plotly.subplots import make_subplots
from scipy.linalg import sqrtm
from sklearn.exceptions import NotFittedError
from greykite.algo.reconcile.hierarchical_relationship import HierarchicalRelationship
from greykite.common.python_utils import reorder_columns
DEFAULT_METHOD = "custom"
def get_fit_params(method=DEFAULT_METHOD):
"""Returns parameters for
`greykite.algo.reconcile.convex.reconcile_forecasts.ReconcileAdditiveForecasts.fit`
corresponding to recognized hierarchical reconciliation method.
Parameters
----------
method : `str`, default `~greykite.algo.reconcile.convex.reconcile_forecasts.DEFAULT_METHOD`
Which reconciliation method to use.
Valid values are "bottom_up", "ols", "mint_sample", "custom":
- "bottom_up" : Sums leaf nodes. Unbiased transform that uses only the values of the leaf nodes
to propagate up the tree. Each node's value is the sum of its
corresponding leaf nodes' values (a leaf node corresponds to a node T if it is
a leaf node of the subtree with T as its root, i.e. a descendant of T or T itself).
See Dangerfield and Morris 1992 "Top-down or bottom-up: Aggregate versus disaggregate
extrapolations" for one discussion of this method.
Depends only on the structure of the hierarchy, not on the data itself.
- "ols" : OLS estimate proposed by https://robjhyndman.com/papers/Hierarchical6.pdf
(Hyndman et al. 2010, "Optimal combination forecasts for hierarchical time series")
Also see https://robjhyndman.com/papers/mint.pdf section 2.4.1.
(Wickramasuriya et al. 2019 "Optimal forecast reconciliation for
hierarchical and grouped time series through trace minimization".)
Unbiased transform that minimizes variance of adjusted residuals,
using "identity" estimate of original residual variance.
Optimal if original forecast errors are uncorrelated with equal variance (unlikely).
Depends only on the structure of the hierarchy, not on the data itself.
- "mint_sample" : Unbiased transform that minimizes variance of adjusted residuals,
using "sample" estimate of original residual variance.
Assumes base forecasts are unbiased.
See Wickramasuriya et al. 2019 section 2.4.4.
Depends on the structure of the hierarchy and forecast error covariances.
- "custom" : Optimization parameters can be set by the user. See
`greykite.algo.reconcile.convex.reconcile_forecasts.ReconcileAdditiveForecasts.fit`
method for parameters and their default values.
Depends on the structure of the hierarchy, base forecasts, and actuals, if all terms
are included in the objective.
If "custom", uses the parameters passed to
`greykite.algo.reconcile.convex.reconcile_forecasts.ReconcileAdditiveForecasts.fit`
to formulate the convex optimization problem.
If "bottom_up", "ols", or "mint_sample", the other fit parameters are ignored.
Returns
-------
estimator_fit_params : `dict` [`str`, Any]
Parameters to use when calling ``ReconcileAdditiveForecasts.fit()``.
"""
if method == "custom":
estimator_fit_params = {} # uses default values of ``fit`` and those passed by user
elif method == "bottom_up":
logging.info("Using bottom_up estimator")
estimator_fit_params = {} # already passed to ``fit`` via ``method``
elif method == "ols":
logging.info("Using ols estimator")
estimator_fit_params = dict(
lower_bound=None,
upper_bound=None,
unbiased=True, # unbiased
lam_adj=0.0,
lam_bias=0.0,
lam_train=0.0,
lam_var=1.0, # minimizes variance
covariance="identity", # assumes equal uncorrelated variance
weight_adj=None,
weight_bias=None,
weight_train=None,
weight_var=None,
)
elif method == "mint_sample":
logging.info("Using mint_sample estimator")
estimator_fit_params = dict(
lower_bound=None,
upper_bound=None,
unbiased=True, # unbiased
lam_adj=0.0,
lam_bias=0.0,
lam_train=0.0,
lam_var=1.0, # minimizes variance
covariance="sample", # in-sample variance estimate
weight_adj=None,
weight_bias=None,
weight_train=None,
weight_var=None,
)
else:
raise ValueError(f"`method` '{method}' is not recognized. "
f"Must be one of 'bottom_up', 'ols', 'mint_sample', 'custom'")
return estimator_fit_params
The provided code snippet includes necessary dependencies for implementing the `apply_method_defaults` function. Write a Python function `def apply_method_defaults(fit_func)` to solve the following problem:
Decorator for `greykite.algo.reconcile.convex.reconcile_forecasts.ReconcileAdditiveForecasts.fit`. Fetches parameters based on ``method`` and calls ``fit_func`` with the result. Parameters ---------- fit_func : `callable` Should be `greykite.algo.reconcile.convex.reconcile_forecasts.ReconcileAdditiveForecasts.fit`. Returns ------- apply_defaults_and_fit : callable Function that overwrites ``fit_params`` with those specified by ``method`` and calls ``fit_func`` with those params.
Here is the function:
def apply_method_defaults(fit_func):
"""Decorator for `greykite.algo.reconcile.convex.reconcile_forecasts.ReconcileAdditiveForecasts.fit`.
Fetches parameters based on ``method`` and calls ``fit_func`` with the result.
Parameters
----------
fit_func : `callable`
Should be `greykite.algo.reconcile.convex.reconcile_forecasts.ReconcileAdditiveForecasts.fit`.
Returns
-------
apply_defaults_and_fit : callable
Function that overwrites ``fit_params`` with those specified by ``method``
and calls ``fit_func`` with those params.
"""
@functools.wraps(fit_func)
def apply_defaults_and_fit(
self,
forecasts,
actuals,
**fit_params):
"""Overwrites ``fit_params`` with those specified by ``fit_params["method"]``.
Calls ``fit_func`` with those params.
Parameters
----------
self : `ReconcileAdditiveForecasts`
Self. Decorator should be applied to ``ReconcileAdditiveForecasts.fit()``.
forecasts : `pandas.DataFrame`
Forecasted values to pass to ``fit_func``.
actuals : `pandas.DataFrame`
Actual values to pass to ``fit_func``.
fit_params : `dict`
Original parameters used to call ``fit_func``.
These are overridden by the ones corresponding to ``method``.
Returns
-------
output : Any
Same as the output of ``fit_func``.
"""
method = fit_params.get("method", DEFAULT_METHOD)
method_fit_params = get_fit_params(method)
params = dict(fit_params, **method_fit_params)
return fit_func(
self,
forecasts,
actuals,
**params)
return apply_defaults_and_fit | Decorator for `greykite.algo.reconcile.convex.reconcile_forecasts.ReconcileAdditiveForecasts.fit`. Fetches parameters based on ``method`` and calls ``fit_func`` with the result. Parameters ---------- fit_func : `callable` Should be `greykite.algo.reconcile.convex.reconcile_forecasts.ReconcileAdditiveForecasts.fit`. Returns ------- apply_defaults_and_fit : callable Function that overwrites ``fit_params`` with those specified by ``method`` and calls ``fit_func`` with those params. |
167,380 | import functools
import logging
import math
import sys
import warnings
from dataclasses import dataclass
from typing import Optional
import cvxpy as cp
import numpy as np
import pandas as pd
import plotly
import plotly.express as px
from plotly import graph_objects as go
from plotly.subplots import make_subplots
from scipy.linalg import sqrtm
from sklearn.exceptions import NotFittedError
from greykite.algo.reconcile.hierarchical_relationship import HierarchicalRelationship
from greykite.common.python_utils import reorder_columns
The provided code snippet includes necessary dependencies for implementing the `evaluation_plot` function. Write a Python function `def evaluation_plot(x, traces, num_cols=3, ylabel=None, title=None, hline=False)` to solve the following problem:
Helper function to create evaluation plots from traces. Creates a figure with subplots. Every dataframe in ``traces`` has the same columns. There is one subplot for each column, plotting the values of that column from all the traces against ``x``. For example, there can be two traces, forecasts and actuals, each containing timeseries for multiple variables (nodes), represented as columns in ``df``. ``x`` can be the time index of the timeseries. This function returns a figure with a subplot for each variable, plotting forecasts against actuals. x : `numpy.array` x-axis values for the lines to plot. traces : `list` [`greykite.algo.reconcile.convex.reconcile_forecasts.TraceInfo`] y-axis values for the lines to plot, along with styling info. The columns for each dataframe in ``traces`` must be identical. The number of rows in each dataframe must match the length of ``x``. num_cols : `int`, default 3 Number of columns in the plot. Controls the number of subplots to show in each row, before wrapping to the next row. Rows are filled in the order of the columns in the dataframes, from left to right. ylabel : `str` or None, default None y-axis label for each subplot. If None, no y-axis label is shown. title : `str` or None, default None Title for the entire plot. If None, no title is shown. hline : `bool`, default False Whether to show a horizontal line at y=0. Returns ------- fig : `plotly.graph_objects.Figure` The plot object.
Here is the function:
def evaluation_plot(x, traces, num_cols=3, ylabel=None, title=None, hline=False):
"""Helper function to create evaluation plots from traces.
Creates a figure with subplots.
Every dataframe in ``traces`` has the same columns.
There is one subplot for each column, plotting the values of
that column from all the traces against ``x``.
For example, there can be two traces, forecasts and actuals,
each containing timeseries for multiple variables (nodes),
represented as columns in ``df``. ``x`` can be the time
index of the timeseries. This function returns a figure with
a subplot for each variable, plotting forecasts against actuals.
x : `numpy.array`
x-axis values for the lines to plot.
traces : `list` [`greykite.algo.reconcile.convex.reconcile_forecasts.TraceInfo`]
y-axis values for the lines to plot, along with styling info.
The columns for each dataframe in ``traces`` must be identical.
The number of rows in each dataframe must match the length of ``x``.
num_cols : `int`, default 3
Number of columns in the plot.
Controls the number of subplots to show in each row,
before wrapping to the next row.
Rows are filled in the order of the columns
in the dataframes, from left to right.
ylabel : `str` or None, default None
y-axis label for each subplot.
If None, no y-axis label is shown.
title : `str` or None, default None
Title for the entire plot.
If None, no title is shown.
hline : `bool`, default False
Whether to show a horizontal line at y=0.
Returns
-------
fig : `plotly.graph_objects.Figure`
The plot object.
"""
if len(traces) == 0:
raise ValueError("There must be at least one trace to plot.")
df_col_names = [trace.df.columns for trace in traces]
col_names = df_col_names[0]
if not all([cols.equals(col_names) for cols in df_col_names]):
raise ValueError("Column names must be identical in all traces.")
if not all([len(x) == trace.df.shape[0] for trace in traces]):
raise ValueError("``x`` length must match ``df`` length for all traces.")
if num_cols <= 0 or num_cols > len(col_names):
raise ValueError(f"`num_cols` should be between 1 and {len(col_names)} "
f"(the number of columns), found {num_cols}.")
# The number of rows depends on the number of
# subplots and the subplots per row.
num_rows = math.ceil(traces[0].df.shape[1] / num_cols)
fig = make_subplots(
rows=num_rows,
cols=num_cols,
start_cell="top-left",
subplot_titles=list(col_names))
# Creates a subplot for each column
for i, node in enumerate(col_names):
# Subplot position (1-indexed)
# Fills rows from left to right,
# top to bottom.
row = i//num_cols + 1
col = (i % num_cols) + 1
# Adds y=0 line
if hline:
fig.add_trace(
go.Scatter(
x=x,
y=np.zeros_like(x),
name="zero",
line=dict(color="black", width=1),
legendgroup="zero",
showlegend=False
),
row=row,
col=col)
# Adds each trace's column
for i, trace in enumerate(traces):
name = f"{node}-{trace.name}" if trace.name is not None else node
opacity = 1 if i == 0 else 0.8 # adds opacity to traces after the first one
fig.add_trace(
go.Scatter(
x=x,
y=np.array(trace.df[node]),
name=name,
legendgroup=trace.legendgroup,
line=dict(color=trace.color),
opacity=opacity,
),
row=row,
col=col)
# Adds y-axis titles
ytitle = go.layout.yaxis.Title(font={"size": 10}, text=ylabel)
fig.update_yaxes(row=row, col=col, title=ytitle)
# Adds title for the entire plot
fig.update_layout(dict(title_text=title, title_x=0.5, title_font_size=20))
return fig | Helper function to create evaluation plots from traces. Creates a figure with subplots. Every dataframe in ``traces`` has the same columns. There is one subplot for each column, plotting the values of that column from all the traces against ``x``. For example, there can be two traces, forecasts and actuals, each containing timeseries for multiple variables (nodes), represented as columns in ``df``. ``x`` can be the time index of the timeseries. This function returns a figure with a subplot for each variable, plotting forecasts against actuals. x : `numpy.array` x-axis values for the lines to plot. traces : `list` [`greykite.algo.reconcile.convex.reconcile_forecasts.TraceInfo`] y-axis values for the lines to plot, along with styling info. The columns for each dataframe in ``traces`` must be identical. The number of rows in each dataframe must match the length of ``x``. num_cols : `int`, default 3 Number of columns in the plot. Controls the number of subplots to show in each row, before wrapping to the next row. Rows are filled in the order of the columns in the dataframes, from left to right. ylabel : `str` or None, default None y-axis label for each subplot. If None, no y-axis label is shown. title : `str` or None, default None Title for the entire plot. If None, no title is shown. hline : `bool`, default False Whether to show a horizontal line at y=0. Returns ------- fig : `plotly.graph_objects.Figure` The plot object. |
167,381 | from functools import partial
import pandas as pd
The provided code snippet includes necessary dependencies for implementing the `forecast_one_by_one_fcn` function. Write a Python function `def forecast_one_by_one_fcn( train_forecast_func, **model_params)` to solve the following problem:
A function which turns a train-forecast function to a function which forecast each horizon by fitting its own corresponding model with the goal of providing the best accuracy for each horizon. Parameters ---------- train_forecast_func : `callable` A train forecast function, which gets inputs data (``df``) and produces forecast for given horizon for the whole period: 1 to ``forecast_horizon``. The input function ``train_forecast_func`` has the following expected signature and expected output:: train_forecast_func( df, time_col, value_col, forecast_horizon, **model_params) -> { "fut_df": fut_df, "trained_model": trained_model, ...} # potential extra outputs depending on the model where - fut_df : `pandas.DataFrame` A dataframe with forecast values - trained_model : `dict` A dictionary with information for the trained model This function then can be composed with ``train_forecast_func`` from left as follows:: forecast_one_by_one_fcn(train_forecast_func) to generate a new function with the same inputs as ``train_forecast_func`` and same outputs with an extra dict which has all trained models per horizon (see the Return Section for more details). model_params : additional arguments Extra parameters passed to ``trained_forecast_func`` if desired as keyed parameters. Returns ------- func : `callable` A function to compose with the input function ``train_forecast_func`` from left and return another function with the same inputs and outputs as ``train_forecast_func``:: func = forecast_one_by_one_fcn(train_forecast_func) Note that ``func`` will utilize ``train_forecast_func`` to produce forecasts one by one by training one model per horizon. As discussed, ``func`` has the same inputs as ``train_forecast_func`` and same outputs with an extra dict which has all trained models per horizon: - fut_df : `pandas.DataFrame` With same columns and structure as ``fut_df`` returned by ``train_forecast_func`` - trained_model : `dict` The trained model on the longest horizon passed. This is simply application of ``trained_forecast_func`` on the full horizon - trained_models_per_horizon: `dict` A dictionary with trained models per horizon - key : ``forecasts_horizon`` : `int` - value : trained_model This is the trained_model for that horizon
Here is the function:
def forecast_one_by_one_fcn(
train_forecast_func,
**model_params):
"""A function which turns a train-forecast function to a function which
forecast each horizon by fitting its own corresponding model with the goal
of providing the best accuracy for each horizon.
Parameters
----------
train_forecast_func : `callable`
A train forecast function, which gets inputs data (``df``) and produces
forecast for given horizon for the whole period: 1 to ``forecast_horizon``.
The input function ``train_forecast_func`` has the following expected signature
and expected output::
train_forecast_func(
df,
time_col,
value_col,
forecast_horizon,
**model_params)
->
{
"fut_df": fut_df,
"trained_model": trained_model,
...} # potential extra outputs depending on the model
where
- fut_df : `pandas.DataFrame`
A dataframe with forecast values
- trained_model : `dict`
A dictionary with information for the trained model
This function then can be composed with ``train_forecast_func`` from
left as follows::
forecast_one_by_one_fcn(train_forecast_func)
to generate a new function with the same inputs as
``train_forecast_func`` and same outputs with an extra dict which has
all trained models per horizon (see the Return Section for more details).
model_params : additional arguments
Extra parameters passed to ``trained_forecast_func`` if desired as
keyed parameters.
Returns
-------
func : `callable`
A function to compose with the input function ``train_forecast_func`` from
left and return another function with the same inputs and outputs as
``train_forecast_func``::
func = forecast_one_by_one_fcn(train_forecast_func)
Note that ``func`` will utilize ``train_forecast_func`` to produce forecasts
one by one by training one model per horizon.
As discussed, ``func`` has the same inputs as ``train_forecast_func``
and same outputs with an extra dict which has all trained models per horizon:
- fut_df : `pandas.DataFrame`
With same columns and structure as ``fut_df`` returned by ``train_forecast_func``
- trained_model : `dict`
The trained model on the longest horizon passed.
This is simply application of ``trained_forecast_func`` on the full horizon
- trained_models_per_horizon: `dict`
A dictionary with trained models per horizon
- key : ``forecasts_horizon`` : `int`
- value : trained_model
This is the trained_model for that horizon
"""
def train_forecast_func_one_by_one(
df,
time_col,
value_col,
forecast_horizon,
**model_parameters):
def forecast_kth_time(k):
"""Returns the kth time period forecast.
Parameters
----------
k : `int`
The time period for which we require forecast.
Returns
-------
result : `dict`
A dictionary with following items:
- fut_df_one_row : `pd.DataFrame`
A dataframe with one row with the same format as ``fut_df``
which includes the forecast for time ``k``.
- forecast : `dict`
A dictionary which is the forecast result for ``forecast_horizon=k``.
"""
forecast = train_forecast_func(
df=df,
time_col=time_col,
value_col=value_col,
forecast_horizon=k,
**model_parameters)
fut_df = forecast["fut_df"]
fut_df_one_row = fut_df.iloc[[k-1]].reset_index(drop=True)
return {
"forecast": forecast,
"fut_df_one_row": fut_df_one_row}
# Runs the model and stores the results for all horizons
forecast_per_horizon = {
k: forecast_kth_time(k) for k in range(1, forecast_horizon+1)}
# Extracts a forecast as usual for all times in the horizon
# This is the same as the function called on the whole horizon
# Note ``"trained_model"`` and ``"fut_df"`` are expected to be contained in "forecast"
# as they are expected outputs of ``train_forecast_func``
forecast = forecast_per_horizon[forecast_horizon]["forecast"]
forecast["trained_models_per_horizon"] = {
k: forecast_per_horizon[k]["forecast"]["trained_model"] for k in range(1, forecast_horizon+1)}
# If the forecast horizon is 1, we are done
# Otherwise, we need to update the returned ``"fut_df"``
if forecast_horizon > 1:
fut_df_list = [
forecast_per_horizon[k]["fut_df_one_row"] for k in range(1, forecast_horizon+1)]
fut_df = pd.concat(
fut_df_list,
axis=0,
sort=False)
# Replaces ``fut_df`` with the updated one
forecast["fut_df"] = fut_df
return forecast
return partial(train_forecast_func_one_by_one, **model_params) | A function which turns a train-forecast function to a function which forecast each horizon by fitting its own corresponding model with the goal of providing the best accuracy for each horizon. Parameters ---------- train_forecast_func : `callable` A train forecast function, which gets inputs data (``df``) and produces forecast for given horizon for the whole period: 1 to ``forecast_horizon``. The input function ``train_forecast_func`` has the following expected signature and expected output:: train_forecast_func( df, time_col, value_col, forecast_horizon, **model_params) -> { "fut_df": fut_df, "trained_model": trained_model, ...} # potential extra outputs depending on the model where - fut_df : `pandas.DataFrame` A dataframe with forecast values - trained_model : `dict` A dictionary with information for the trained model This function then can be composed with ``train_forecast_func`` from left as follows:: forecast_one_by_one_fcn(train_forecast_func) to generate a new function with the same inputs as ``train_forecast_func`` and same outputs with an extra dict which has all trained models per horizon (see the Return Section for more details). model_params : additional arguments Extra parameters passed to ``trained_forecast_func`` if desired as keyed parameters. Returns ------- func : `callable` A function to compose with the input function ``train_forecast_func`` from left and return another function with the same inputs and outputs as ``train_forecast_func``:: func = forecast_one_by_one_fcn(train_forecast_func) Note that ``func`` will utilize ``train_forecast_func`` to produce forecasts one by one by training one model per horizon. As discussed, ``func`` has the same inputs as ``train_forecast_func`` and same outputs with an extra dict which has all trained models per horizon: - fut_df : `pandas.DataFrame` With same columns and structure as ``fut_df`` returned by ``train_forecast_func`` - trained_model : `dict` The trained model on the longest horizon passed. This is simply application of ``trained_forecast_func`` on the full horizon - trained_models_per_horizon: `dict` A dictionary with trained models per horizon - key : ``forecasts_horizon`` : `int` - value : trained_model This is the trained_model for that horizon |
167,382 | import re
from greykite.common import constants as cst
INTERCEPT = "Intercept"
The provided code snippet includes necessary dependencies for implementing the `create_pred_category` function. Write a Python function `def create_pred_category(pred_cols, extra_pred_cols, df_cols)` to solve the following problem:
Creates a dictionary of predictor categories. The keys are categories, and the values are the corresponding predictor names. For detail, see `~greykite.sklearn.estimator.base_silverkite_estimator.BaseSilverkiteEstimator.pred_category` Parameters ---------- pred_cols : `list` [ `str` ] A full list of predictor names used in the model, including extra predictor names. extra_pred_cols : `list` [ `str` ] A list of extra predictors what are manually provided for the estimator class. In ``SilverkiteEstimator``, this is the ``extra_pred_cols``. In ``SimpleSilverkiteEstimator``, this is the combination of ``regressor_cols`` and ``extra_pred_cols``. df_cols : `list` [ `str` ] The extra columns that are present in the input df. Columns that are in ``df_cols`` are not considered for categories other than regressors. Columns are considered as regressors only if they are in ``df_cols``. Returns ------- pred_category : `dict` A dictionary of categories and predictors. For details, see `~greykite.sklearn.estimator.base_silverkite_estimator.BaseSilverkiteEstimator.pred_category`
Here is the function:
def create_pred_category(pred_cols, extra_pred_cols, df_cols):
"""Creates a dictionary of predictor categories.
The keys are categories, and the values are the corresponding
predictor names. For detail, see
`~greykite.sklearn.estimator.base_silverkite_estimator.BaseSilverkiteEstimator.pred_category`
Parameters
----------
pred_cols : `list` [ `str` ]
A full list of predictor names used in the model, including extra predictor names.
extra_pred_cols : `list` [ `str` ]
A list of extra predictors what are manually provided for the estimator class.
In ``SilverkiteEstimator``, this is the ``extra_pred_cols``.
In ``SimpleSilverkiteEstimator``, this is the combination of ``regressor_cols``
and ``extra_pred_cols``.
df_cols : `list` [ `str` ]
The extra columns that are present in the input df.
Columns that are in ``df_cols`` are not considered for categories other than regressors.
Columns are considered as regressors only if they are in ``df_cols``.
Returns
-------
pred_category : `dict`
A dictionary of categories and predictors. For details, see
`~greykite.sklearn.estimator.base_silverkite_estimator.BaseSilverkiteEstimator.pred_category`
"""
if extra_pred_cols is None:
extra_pred_cols = []
extra_pred_cols = list(set(extra_pred_cols)) # might have duplicates
# SimpleSilverkiteEstimator and SilverkiteEstimator have different ways to specify
# regressors and lagged regressors. The ``extra_pred_cols`` in this function
# should have a super set of such columns.
# Regressor columns are defined as columns that are in
# ``df_cols`` and that are present either in ``extra_pred_cols`` directly
# or via interaction terms.
# Because all columns in ``regressor_cols`` are present in ``df_cols``,
# these columns are not categorized to any other category.
regressor_cols = [
col for col in df_cols
if col in [c for term in extra_pred_cols for c in term.split(":")]
]
pred_category = {
"intercept": [col for col in pred_cols if re.search(INTERCEPT, col)],
# Time feature names could be included in seasonality features.
# We do not want to include pure seasonality features.
# If a term does not include interaction, it need to include
# time feature name but not seasonality regex.
# This keeps "ct1" and excludes "cos1_ct1_yearly"
# If a term includes interaction, then at least one of the
# two sub-terms need to satisfy the condition above.
# This keeps "ct1:is_weekend" and "ct1:cos1_ct1_yearly"
# and excludes "is_weekend:cos1_ct1_yearly".
"time_features": [col for col in pred_cols
if ((re.search(":", col) is None
and
re.search("|".join(cst.TimeFeaturesEnum.__dict__["_member_names_"]), col)
and
re.search(cst.SEASONALITY_REGEX, col) is None)
or
(re.search(":", col)
and
any([re.search("|".join(cst.TimeFeaturesEnum.__dict__["_member_names_"]), subcol)
and
re.search(cst.SEASONALITY_REGEX, subcol) is None
for subcol in col.split(":")])))
and col not in regressor_cols
],
"event_features": [col for col in pred_cols if cst.EVENT_PREFIX in col
and col not in regressor_cols],
# the same logic as time features for trend features
"trend_features": [col for col in pred_cols
if ((re.search(":", col) is None
and
re.search(cst.TREND_REGEX, col)
and
re.search(cst.SEASONALITY_REGEX, col) is None)
or
(re.search(":", col)
and
any([re.search(cst.TREND_REGEX, subcol)
and
re.search(cst.SEASONALITY_REGEX, subcol) is None
for subcol in col.split(":")])))
and col not in regressor_cols
],
"seasonality_features": [col for col in pred_cols if re.search(cst.SEASONALITY_REGEX, col)
and col not in regressor_cols],
"lag_features": [col for col in pred_cols if re.search(cst.LAG_REGEX, col)
and col not in regressor_cols],
# only the supplied extra_pred_col that are also in pred_cols
"regressor_features": [col for col in pred_cols if col in regressor_cols
or any([x in regressor_cols for x in col.split(":")])],
"interaction_features": [col for col in pred_cols if re.search(":", col)]
}
return pred_category | Creates a dictionary of predictor categories. The keys are categories, and the values are the corresponding predictor names. For detail, see `~greykite.sklearn.estimator.base_silverkite_estimator.BaseSilverkiteEstimator.pred_category` Parameters ---------- pred_cols : `list` [ `str` ] A full list of predictor names used in the model, including extra predictor names. extra_pred_cols : `list` [ `str` ] A list of extra predictors what are manually provided for the estimator class. In ``SilverkiteEstimator``, this is the ``extra_pred_cols``. In ``SimpleSilverkiteEstimator``, this is the combination of ``regressor_cols`` and ``extra_pred_cols``. df_cols : `list` [ `str` ] The extra columns that are present in the input df. Columns that are in ``df_cols`` are not considered for categories other than regressors. Columns are considered as regressors only if they are in ``df_cols``. Returns ------- pred_category : `dict` A dictionary of categories and predictors. For details, see `~greykite.sklearn.estimator.base_silverkite_estimator.BaseSilverkiteEstimator.pred_category` |
167,383 | import re
from greykite.common import constants as cst
def simplify_pred_cols(pred_cols):
"""Simplifies predictor names in a list.
Parameters
----------
pred_cols : `list` [ `str` ]
A list of predictor names to be simplified.
Names in ``pred_cols`` could contain interactions.
Returns
-------
new_pred_cols : `list` [ `str` ]
A simplified list of predictor names by applying element-wisely
`~greykite.algo.common.col_name_utils.simplify_name`
"""
pred_cols_extract = [[col] if ":" not in col else col.split(":") for col in pred_cols]
pred_cols_extract = [[simplify_name(name) for name in col] for col in pred_cols_extract]
new_pred_cols = [col[0] if len(col) == 1 else ":".join(col) for col in pred_cols_extract]
return new_pred_cols
def add_category_cols(coef_summary, pred_category):
"""Adds indicators columns to coefficient summary df for categaries.
Parameters
----------
coef_summary : `pandas.DataFrame`
The coefficient summary df.
This is typically generated by
`~greykite.algo.common.model_summary_utils.add_model_coef_df`
or
`~greykite.algo.common.model_summary_utils.add_model_coef_df`.
pred_category : `dict`
The predictor category dictionary by
`~greykite.algo.common.col_name_utils.create_pred_category`.
Returns
-------
coef_summary_with_new_columns : `pandas.DataFrame
New df with the following columns added:
"is_intercept" : 0 or 1
Intercept or not.
"is_time_feature" : 0 or 1
Time features or not.
Time features belong to `~greykite.common.constants.TimeFeaturesEnum`.
"is_event" : 0 or 1
Event features or not.
Event features have `~greykite.common.constants.EVENT_PREFIX`.
"is_trend" : 0 or 1
Trend features or not.
Trend features have `~greykite.common.constants.CHANGEPOINT_COL_PREFIX` or "cp\\d".
"is_seasonality" : 0 or 1
Seasonality feature or not.
Seasonality features have `~greykite.common.constants.SEASONALITY_REGEX`.
"is_lag" : 0 or 1
Lagged features or not.
Lagged features have "lag_".
"is_regressor" : 0 or 1
Extra features provided by users.
They are provided through ``extra_pred_cols`` in the fit function.
"is_interaction" : 0 or 1
Interaction feature or not.
Interaction features have ":".
"""
coef_summary = coef_summary.copy()
pred_cols = coef_summary["Pred_col"].tolist()
coef_summary["is_intercept"] = [1 if col in pred_category["intercept"]
else 0 for col in pred_cols]
coef_summary["is_time_feature"] = [1 if col in pred_category["time_features"]
else 0 for col in pred_cols]
coef_summary["is_event"] = [1 if col in pred_category["event_features"]
else 0 for col in pred_cols]
coef_summary["is_trend"] = [1 if col in pred_category["trend_features"]
else 0 for col in pred_cols]
coef_summary["is_seasonality"] = [1 if col in pred_category["seasonality_features"]
else 0 for col in pred_cols]
coef_summary["is_lag"] = [1 if col in pred_category["lag_features"]
else 0 for col in pred_cols]
coef_summary["is_regressor"] = [1 if col in pred_category["regressor_features"]
else 0 for col in pred_cols]
coef_summary["is_interaction"] = [1 if col in pred_category["interaction_features"]
else 0 for col in pred_cols]
return coef_summary
The provided code snippet includes necessary dependencies for implementing the `filter_coef_summary` function. Write a Python function `def filter_coef_summary( coef_summary, pred_category, is_intercept=None, is_time_feature=None, is_event=None, is_trend=None, is_seasonality=None, is_lag=None, is_regressor=None, is_interaction=None)` to solve the following problem:
Gets the coefficient summary df after applying the given filters. Set any of the parameters to `bool` to enable filtering. - Any argument set to True will be aggregated with logical operator "or", i.e. a category will be displayed when set to True. - Any argument set to False will be aggregated with logical operator "and", i.e. a category will not be displayed when set to False (even it has interaction with a category that is set to True). - Any argument set to None will be ignored unless all arguments are None. - ``is_interaction`` is used to exclude interaction terms by setting it to False. It is not used when the value is True and other argument is not None. The design here is to use ``is_interaction`` as a second pass filter. Parameters ---------- coef_summary : `pandas.DataFrame` The coefficient summary df. pred_category : `dict` The predictor category dictionary by `~greykite.algo.common.col_name_utils.create_pred_category`. is_intercept : `bool` or `None`, default `None` Intercept or not. is_time_feature : `bool` or `None`, default `None` Time features or not. Time features belong to `~greykite.common.constants.TimeFeaturesEnum`. is_event : `bool` or `None`, default `None` Event features or not. Event features have `~greykite.common.constants.EVENT_PREFIX`. is_trend : `bool` or `None`, default `None` Trend features or not. Trend features have `~greykite.common.constants.CHANGEPOINT_COL_PREFIX`. is_seasonality : `bool` or `None`, default `None` Seasonality feature or not. Seasonality features have `~greykite.common.constants.SEASONALITY_REGEX`. is_lag : `bool` or `None`, default `None` Lagged features or not. Lagged features have "lag_". is_regressor : `bool` or `None`, default `None` User supplied regressor features or not. They are provided with the `extra_pred_cols`. is_interaction : `bool` or `None`, default `None` Interaction feature or not. Interaction features have ":". Returns ------- filtered_coef_summary : `pandas.DataFrame` The filtered coefficient summary df filtered by the given conditions.
Here is the function:
def filter_coef_summary(
coef_summary,
pred_category,
is_intercept=None,
is_time_feature=None,
is_event=None,
is_trend=None,
is_seasonality=None,
is_lag=None,
is_regressor=None,
is_interaction=None):
"""Gets the coefficient summary df after applying the given filters.
Set any of the parameters to `bool` to enable filtering.
- Any argument set to True will be aggregated with logical operator "or", i.e.
a category will be displayed when set to True.
- Any argument set to False will be aggregated with logical operator "and", i.e.
a category will not be displayed when set to False (even it has interaction with
a category that is set to True).
- Any argument set to None will be ignored unless all arguments are None.
- ``is_interaction`` is used to exclude interaction terms by setting it
to False. It is not used when the value is True and other argument is not None.
The design here is to use ``is_interaction`` as a second pass filter.
Parameters
----------
coef_summary : `pandas.DataFrame`
The coefficient summary df.
pred_category : `dict`
The predictor category dictionary by
`~greykite.algo.common.col_name_utils.create_pred_category`.
is_intercept : `bool` or `None`, default `None`
Intercept or not.
is_time_feature : `bool` or `None`, default `None`
Time features or not.
Time features belong to `~greykite.common.constants.TimeFeaturesEnum`.
is_event : `bool` or `None`, default `None`
Event features or not.
Event features have `~greykite.common.constants.EVENT_PREFIX`.
is_trend : `bool` or `None`, default `None`
Trend features or not.
Trend features have `~greykite.common.constants.CHANGEPOINT_COL_PREFIX`.
is_seasonality : `bool` or `None`, default `None`
Seasonality feature or not.
Seasonality features have `~greykite.common.constants.SEASONALITY_REGEX`.
is_lag : `bool` or `None`, default `None`
Lagged features or not.
Lagged features have "lag_".
is_regressor : `bool` or `None`, default `None`
User supplied regressor features or not.
They are provided with the `extra_pred_cols`.
is_interaction : `bool` or `None`, default `None`
Interaction feature or not.
Interaction features have ":".
Returns
-------
filtered_coef_summary : `pandas.DataFrame`
The filtered coefficient summary df filtered by the given conditions.
"""
coef_summary_categorized = add_category_cols(coef_summary, pred_category)
coef_summary_categorized["Pred_col"] = simplify_pred_cols(coef_summary_categorized["Pred_col"])
# And True values will be aggregated with "or".
# Any False values will be aggregated with "and".
# This aligns with human sense.
conditions_true = []
conditions_false = []
for k, v in locals().items():
if "is_" in k and k != "is_interaction":
if v is not None:
if v:
conditions_true.append(f"{k} == {int(v)}")
else:
conditions_false.append(f"{k} == {int(v)}")
query_true = f"{' or '.join(conditions_true)}"
query_false = f"{' and '.join(conditions_false)}"
if query_true and query_false:
query = f"({query_true}) and ({query_false})"
elif query_true:
query = f"({query_true})"
elif query_false:
query = f"({query_false})"
else:
query = ""
# Deal with is_interaction
if query:
if is_interaction is False:
# When is_interaction is False, remove interaction terms.
# By default, the filters include interaction terms.
query = f"({query}) and (is_interaction == {int(is_interaction)})"
new_df = coef_summary_categorized.query(query)
else:
# In there is no query, is_interaction is used filter rows.
if is_interaction is not None:
query = f"is_interaction == {int(is_interaction)}"
new_df = coef_summary_categorized.query(query)
else:
new_df = coef_summary_categorized
return new_df.reset_index(drop=True) | Gets the coefficient summary df after applying the given filters. Set any of the parameters to `bool` to enable filtering. - Any argument set to True will be aggregated with logical operator "or", i.e. a category will be displayed when set to True. - Any argument set to False will be aggregated with logical operator "and", i.e. a category will not be displayed when set to False (even it has interaction with a category that is set to True). - Any argument set to None will be ignored unless all arguments are None. - ``is_interaction`` is used to exclude interaction terms by setting it to False. It is not used when the value is True and other argument is not None. The design here is to use ``is_interaction`` as a second pass filter. Parameters ---------- coef_summary : `pandas.DataFrame` The coefficient summary df. pred_category : `dict` The predictor category dictionary by `~greykite.algo.common.col_name_utils.create_pred_category`. is_intercept : `bool` or `None`, default `None` Intercept or not. is_time_feature : `bool` or `None`, default `None` Time features or not. Time features belong to `~greykite.common.constants.TimeFeaturesEnum`. is_event : `bool` or `None`, default `None` Event features or not. Event features have `~greykite.common.constants.EVENT_PREFIX`. is_trend : `bool` or `None`, default `None` Trend features or not. Trend features have `~greykite.common.constants.CHANGEPOINT_COL_PREFIX`. is_seasonality : `bool` or `None`, default `None` Seasonality feature or not. Seasonality features have `~greykite.common.constants.SEASONALITY_REGEX`. is_lag : `bool` or `None`, default `None` Lagged features or not. Lagged features have "lag_". is_regressor : `bool` or `None`, default `None` User supplied regressor features or not. They are provided with the `extra_pred_cols`. is_interaction : `bool` or `None`, default `None` Interaction feature or not. Interaction features have ":". Returns ------- filtered_coef_summary : `pandas.DataFrame` The filtered coefficient summary df filtered by the given conditions. |
167,384 | from __future__ import annotations
from typing import Dict
from typing import Optional
import cvxpy as cp
import numpy as np
import pandas as pd
import scipy
from sklearn.base import BaseEstimator
from sklearn.base import RegressorMixin
from greykite.algo.common.partial_regularize_regression import constant_col_finder
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
class LoggingLevelEnum(Enum):
"""Valid types of logging levels available to use."""
CRITICAL = 50
ERROR = 40
WARNING = 30
INFO = 20
DEBUG = 10
NOTSET = 0
def log_message(message, level=LoggingLevelEnum.INFO):
"""Adds a message to logger.
Parameters
----------
message : `any`
The message to be added to logger.
level : `Enum`
One of the levels in the `~greykite.common.enums.LoggingLevelEnum`.
"""
if level.name not in list(LoggingLevelEnum.__members__):
raise ValueError(f"{level} not found, it must be a member of the LoggingLevelEnum class.")
logger.log(level.value, message)
The provided code snippet includes necessary dependencies for implementing the `ordinary_quantile_regression` function. Write a Python function `def ordinary_quantile_regression( x: np.array, y: np.array, q: float, sample_weight: Optional[np.array] = None, max_iter: int = 200, tol: float = 1e-2) -> np.array` to solve the following problem:
Implements the quantile regression without penalty terms. Supports sample weight. Applies the iterative re-weighted least square (IRLS) algorithm to solve the quantile regression without regularization. Minimizes beta = argmin 1/n * sum {w_i * [(1 - q) * (y_i - x_i^T beta)_- + q * (y_i - x_i^T beta)_+]} This works for singular matrix and supports sample weights, while statsmodels does not. Please make sure the design matrix has an intercept as intercept is very important to quantile regression. Parameters ---------- x : `numpy.array` The design matrix. y : `numpy.array` The response vector. q : `float` between 0.0 and 1.0 The quantile of the response to model. sample_weight : `numpy.array` or None, default None The sample weight in the loss function. max_iter : int, default 200 The maximum number of iterations. tol : float, default 1e-2 The tolerance to stop the algorithm. Returns ------- beta : numpy.array The estimated coefficients.
Here is the function:
def ordinary_quantile_regression(
x: np.array,
y: np.array,
q: float,
sample_weight: Optional[np.array] = None,
max_iter: int = 200,
tol: float = 1e-2) -> np.array:
"""Implements the quantile regression without penalty terms.
Supports sample weight.
Applies the iterative re-weighted least square (IRLS) algorithm
to solve the quantile regression without regularization. Minimizes
beta = argmin 1/n * sum {w_i * [(1 - q) * (y_i - x_i^T beta)_- + q * (y_i - x_i^T beta)_+]}
This works for singular matrix and supports sample weights, while statsmodels does not.
Please make sure the design matrix has an intercept as intercept is very important to quantile regression.
Parameters
----------
x : `numpy.array`
The design matrix.
y : `numpy.array`
The response vector.
q : `float` between 0.0 and 1.0
The quantile of the response to model.
sample_weight : `numpy.array` or None, default None
The sample weight in the loss function.
max_iter : int, default 200
The maximum number of iterations.
tol : float, default 1e-2
The tolerance to stop the algorithm.
Returns
-------
beta : numpy.array
The estimated coefficients.
"""
# Uses IRLS to solve the problem.
n, p = x.shape
if sample_weight is None:
sample_weight = np.ones(n)
# Minimum constant for denominator to prevent from dividing by zero.
delta = 1e-6
beta = np.zeros(p)
for i in range(max_iter):
eta = x @ beta
eps = np.abs(y - eta)
# Re-weights.
left = np.where(y < eta, q, 1 - q) / sample_weight
right = np.where(eps > delta, eps, delta)
s = (left * right).reshape(-1, 1)
# Solves with formula.
# Multiplies weights to x first to speed up.
x_l = x / s
# Tries to solve with `scipy.linalg.solve`, which gives a more stable solution.
# In cases it fails, uses `numpy.linalg.pinv`.
try:
beta_new = scipy.linalg.solve(x_l.T @ x, x_l.T @ y, assume_a="pos")
except np.linalg.LinAlgError:
beta_new = np.linalg.pinv(x_l.T @ x) @ (x_l.T @ y)
err = (np.abs(beta_new - beta) / np.abs(beta)).max()
beta = beta_new
if err < tol:
break
if i == max_iter - 1:
log_message(
message=f"Max number of iterations reached. "
f"Deviation is {err}. "
f"Consider increasing max_iter.",
level=LoggingLevelEnum.WARNING
)
return beta | Implements the quantile regression without penalty terms. Supports sample weight. Applies the iterative re-weighted least square (IRLS) algorithm to solve the quantile regression without regularization. Minimizes beta = argmin 1/n * sum {w_i * [(1 - q) * (y_i - x_i^T beta)_- + q * (y_i - x_i^T beta)_+]} This works for singular matrix and supports sample weights, while statsmodels does not. Please make sure the design matrix has an intercept as intercept is very important to quantile regression. Parameters ---------- x : `numpy.array` The design matrix. y : `numpy.array` The response vector. q : `float` between 0.0 and 1.0 The quantile of the response to model. sample_weight : `numpy.array` or None, default None The sample weight in the loss function. max_iter : int, default 200 The maximum number of iterations. tol : float, default 1e-2 The tolerance to stop the algorithm. Returns ------- beta : numpy.array The estimated coefficients. |
167,385 | from __future__ import annotations
from typing import Dict
from typing import Optional
import cvxpy as cp
import numpy as np
import pandas as pd
import scipy
from sklearn.base import BaseEstimator
from sklearn.base import RegressorMixin
from greykite.algo.common.partial_regularize_regression import constant_col_finder
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `l1_quantile_regression` function. Write a Python function `def l1_quantile_regression( x: np.array, y: np.array, q: float, alpha: float, sample_weight: Optional[np.array] = None, feature_weight: Optional[np.array] = None, include_intercept: bool = True) -> Dict[str, any]` to solve the following problem:
Implements the quantile regression with penalty terms. Supports sample weight and feature weights in penalty. This is solved with linear programming formulation: min c^Tx s.t. ax<=b where x is [beta+, beta-, alpha+, alpha-, (y-alpha-X beta)+, (y-alpha-X beta)-]. Please make sure the design matrix is normalized. Parameters ---------- x : `numpy.array` The design matrix. y : `numpy.array` The response vector. q : `float` between 0.0 and 1.0 The quantile of the response to model. alpha : `float` The regularization parameter. sample_weight : `numpy.array` or None, default None The sample weight in the loss function. feature_weight : `numpy.array` or None, default None The feature weight in the penalty term. This parameter enables adaptive L1 norm regularization. include_intercept : `bool`, default True Whether to include intercept. If True, will fit an intercept separately and drop any degenerate columns. False is not recommended because intercept is very useful in distinguishing the quantiles (it shifts the predictions up and down). Returns ------- coefs : `dict` [`str`, any] The coefficients dictionary with the following elements: intercept : `float` The intercept. beta : `numpy.array` The estimated coefficients.
Here is the function:
def l1_quantile_regression(
x: np.array,
y: np.array,
q: float,
alpha: float,
sample_weight: Optional[np.array] = None,
feature_weight: Optional[np.array] = None,
include_intercept: bool = True) -> Dict[str, any]:
"""Implements the quantile regression with penalty terms.
Supports sample weight and feature weights in penalty.
This is solved with linear programming formulation:
min c^Tx s.t. ax<=b
where x is [beta+, beta-, alpha+, alpha-, (y-alpha-X beta)+, (y-alpha-X beta)-].
Please make sure the design matrix is normalized.
Parameters
----------
x : `numpy.array`
The design matrix.
y : `numpy.array`
The response vector.
q : `float` between 0.0 and 1.0
The quantile of the response to model.
alpha : `float`
The regularization parameter.
sample_weight : `numpy.array` or None, default None
The sample weight in the loss function.
feature_weight : `numpy.array` or None, default None
The feature weight in the penalty term.
This parameter enables adaptive L1 norm regularization.
include_intercept : `bool`, default True
Whether to include intercept.
If True, will fit an intercept separately and drop any degenerate columns.
False is not recommended because intercept is very useful in distinguishing the quantiles
(it shifts the predictions up and down).
Returns
-------
coefs : `dict` [`str`, any]
The coefficients dictionary with the following elements:
intercept : `float`
The intercept.
beta : `numpy.array`
The estimated coefficients.
"""
n, p = x.shape
if sample_weight is None:
sample_weight = np.ones(n)
if feature_weight is None:
feature_weight = np.ones(p)
# Linear coefficients.
c = [alpha * feature_weight, alpha * feature_weight]
if include_intercept:
c += [np.zeros(2)]
c += [q * sample_weight, (1 - q) * sample_weight]
c = np.concatenate(c, axis=0)
# Variable.
var_size = 2*p + 2*n + 2*include_intercept
var = cp.Variable(var_size)
# Equality constraint coefficients.
x_vec = [x, -x]
if include_intercept:
x_vec += [np.ones([n, 1]), -np.ones([n, 1])]
x_vec += [np.eye(n), -np.eye(n)]
x_vec = np.concatenate(x_vec, axis=1)
# The problem.
prob = cp.Problem(cp.Minimize(c.T @ var),
[var >= 0, x_vec @ var == y])
prob.solve()
# Gets the results.
if include_intercept:
intercept = var.value[2 * p] - var.value[2 * p + 1]
else:
intercept = 0
coef = var.value[:p] - var.value[p: 2 * p]
return {
"intercept": intercept,
"coef": coef
} | Implements the quantile regression with penalty terms. Supports sample weight and feature weights in penalty. This is solved with linear programming formulation: min c^Tx s.t. ax<=b where x is [beta+, beta-, alpha+, alpha-, (y-alpha-X beta)+, (y-alpha-X beta)-]. Please make sure the design matrix is normalized. Parameters ---------- x : `numpy.array` The design matrix. y : `numpy.array` The response vector. q : `float` between 0.0 and 1.0 The quantile of the response to model. alpha : `float` The regularization parameter. sample_weight : `numpy.array` or None, default None The sample weight in the loss function. feature_weight : `numpy.array` or None, default None The feature weight in the penalty term. This parameter enables adaptive L1 norm regularization. include_intercept : `bool`, default True Whether to include intercept. If True, will fit an intercept separately and drop any degenerate columns. False is not recommended because intercept is very useful in distinguishing the quantiles (it shifts the predictions up and down). Returns ------- coefs : `dict` [`str`, any] The coefficients dictionary with the following elements: intercept : `float` The intercept. beta : `numpy.array` The estimated coefficients. |
167,386 | from typing import Union
import numpy as np
import pandas as pd
from sklearn.exceptions import ConvergenceWarning
from sklearn.linear_model import Lasso
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge
from sklearn.linear_model import RidgeCV
from sklearn.linear_model._coordinate_descent import _alpha_grid
from sklearn.model_selection import check_cv
from greykite.common.python_utils import ignore_warnings
The provided code snippet includes necessary dependencies for implementing the `constant_col_finder` function. Write a Python function `def constant_col_finder(x, exclude_cols=None)` to solve the following problem:
Finds constant columns in x. A column is considered as a constant column if all rows have the same value and the value is not zero. Parameters ---------- x : `numpy.array` The design matrix. exclude_cols : `list`[`int`], default None Columns in ``exlucde_cols`` are not considered as constant columns. Returns ------- constant_cols : `list`[`int`] A list of indices that satisfy the constant column conditions.
Here is the function:
def constant_col_finder(x, exclude_cols=None):
"""Finds constant columns in x.
A column is considered as a constant column if all rows have the same value
and the value is not zero.
Parameters
----------
x : `numpy.array`
The design matrix.
exclude_cols : `list`[`int`], default None
Columns in ``exlucde_cols`` are not considered as constant columns.
Returns
-------
constant_cols : `list`[`int`]
A list of indices that satisfy the constant column conditions.
"""
if exclude_cols is None:
exclude_cols = []
var = x.var(axis=0)
constant_cols = [i for i in range(len(var)) if var[i] == 0 and x[0, i] != 0 and i not in exclude_cols]
return constant_cols | Finds constant columns in x. A column is considered as a constant column if all rows have the same value and the value is not zero. Parameters ---------- x : `numpy.array` The design matrix. exclude_cols : `list`[`int`], default None Columns in ``exlucde_cols`` are not considered as constant columns. Returns ------- constant_cols : `list`[`int`] A list of indices that satisfy the constant column conditions. |
167,387 | import datetime
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
import pandas as pd
from pandas.tseries.frequencies import to_offset
from greykite.algo.forecast.silverkite.forecast_simple_silverkite_helper import get_event_pred_cols
from greykite.common.constants import EVENT_DF_DATE_COL
from greykite.common.constants import EVENT_DF_LABEL_COL
from greykite.common.constants import EVENT_PREFIX
from greykite.common.constants import EVENT_SHIFTED_SUFFIX_AFTER
from greykite.common.constants import EVENT_SHIFTED_SUFFIX_BEFORE
from greykite.common.python_utils import split_offset_str
The provided code snippet includes necessary dependencies for implementing the `get_dow_grouped_suffix` function. Write a Python function `def get_dow_grouped_suffix(date: datetime.datetime) -> str` to solve the following problem:
Utility function to generate a suffix given an input ``date``. Parameters ---------- date : `datetime.datetime` Input timestamp. Returns ------- suffix : `str` The suffix string starting with "_".
Here is the function:
def get_dow_grouped_suffix(date: datetime.datetime) -> str:
"""Utility function to generate a suffix given an input ``date``.
Parameters
----------
date : `datetime.datetime`
Input timestamp.
Returns
-------
suffix : `str`
The suffix string starting with "_".
"""
if date.day_name() == "Saturday":
return "_Sat"
elif date.day_name() == "Sunday":
return "_Sun"
elif date.day_name() in ["Friday", "Monday"]:
return "_Mon/Fri"
else:
return "_WD" | Utility function to generate a suffix given an input ``date``. Parameters ---------- date : `datetime.datetime` Input timestamp. Returns ------- suffix : `str` The suffix string starting with "_". |
167,388 | import datetime
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
import pandas as pd
from pandas.tseries.frequencies import to_offset
from greykite.algo.forecast.silverkite.forecast_simple_silverkite_helper import get_event_pred_cols
from greykite.common.constants import EVENT_DF_DATE_COL
from greykite.common.constants import EVENT_DF_LABEL_COL
from greykite.common.constants import EVENT_PREFIX
from greykite.common.constants import EVENT_SHIFTED_SUFFIX_AFTER
from greykite.common.constants import EVENT_SHIFTED_SUFFIX_BEFORE
from greykite.common.python_utils import split_offset_str
The provided code snippet includes necessary dependencies for implementing the `get_weekday_weekend_suffix` function. Write a Python function `def get_weekday_weekend_suffix(date: datetime.datetime) -> str` to solve the following problem:
Utility function to generate a suffix given an input ``date``. Parameters ---------- date : `datetime.datetime` Input timestamp. Returns ------- suffix : `str` The suffix string starting with "_".
Here is the function:
def get_weekday_weekend_suffix(date: datetime.datetime) -> str:
"""Utility function to generate a suffix given an input ``date``.
Parameters
----------
date : `datetime.datetime`
Input timestamp.
Returns
-------
suffix : `str`
The suffix string starting with "_".
"""
if date.day_name() in ("Saturday", "Sunday"):
return "_WE"
else:
return "_WD" | Utility function to generate a suffix given an input ``date``. Parameters ---------- date : `datetime.datetime` Input timestamp. Returns ------- suffix : `str` The suffix string starting with "_". |
167,389 | import datetime
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
import pandas as pd
from pandas.tseries.frequencies import to_offset
from greykite.algo.forecast.silverkite.forecast_simple_silverkite_helper import get_event_pred_cols
from greykite.common.constants import EVENT_DF_DATE_COL
from greykite.common.constants import EVENT_DF_LABEL_COL
from greykite.common.constants import EVENT_PREFIX
from greykite.common.constants import EVENT_SHIFTED_SUFFIX_AFTER
from greykite.common.constants import EVENT_SHIFTED_SUFFIX_BEFORE
from greykite.common.python_utils import split_offset_str
def get_event_pred_cols(
daily_event_df_dict,
daily_event_shifted_effect=None):
"""Generates the names of internal predictor columns from
the event dictionary passed to
`~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`.
These can be passed via the ``extra_pred_cols`` parameter to model event effects.
.. note::
The returned strings are patsy model formula terms.
Each provides full set of levels so that prediction works even if a
level is not found in the training set.
If a level does not appear in the training set, its coefficient may
be unbounded in the "linear" fit_algorithm. A method with regularization
avoids this issue (e.g. "ridge", "elastic_net").
Parameters
----------
daily_event_df_dict : `dict` or None, optional, default None
A dictionary of data frames, each representing events data for the corresponding key.
See `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`.
daily_event_shifted_effect : `list` [`str`] or None, default None
Additional neighbor events based on given events.
For example, passing ["-1D", "7D"] will add extra daily events which are 1 day before
and 7 days after the given events.
Offset format is {d}{freq} with any integer plus a frequency string.
Must be parsable by pandas ``to_offset``.
The new events' names will be the current events' names with suffix "{offset}_before" or "{offset}_after".
For example, if we have an event named "US_Christmas Day",
a "7D" shift will have name "US_Christmas Day_7D_after".
This is useful when you expect an offset of the current holidays also has impact on the
time series, or you want to interact the lagged terms with autoregression.
The interaction can be specified with e.g. ``y_lag7:events_US_Christmas Day_7D_after``.
If ``daily_event_neighbor_impact`` is also specified, this will be applied after adding neighboring days.
Returns
-------
event_pred_cols : `list` [`str`]
List of patsy model formula terms, one for each
key of ``daily_event_df_dict``.
"""
event_pred_cols = []
if daily_event_df_dict is not None:
for key in sorted(daily_event_df_dict.keys()):
# `add_daily_events` creates a column with this name.
term = f"{cst.EVENT_PREFIX}_{key}"
# Its values are set to the event df label column. Dates that do not correspond
# to the event are set to `cst.EVENT_DEFAULT`.
event_levels = [cst.EVENT_DEFAULT] # reference level for non-event days
event_levels += list(daily_event_df_dict[key][cst.EVENT_DF_LABEL_COL].unique()) # this event's levels
event_pred_cols += [patsy_categorical_term(term=term, levels=event_levels)]
# Adds columns for additional neighbor events.
# Does the above for each additional lagged event.
if daily_event_shifted_effect is not None:
for lag in daily_event_shifted_effect:
num, freq = split_offset_str(lag)
num = int(num)
suffix = cst.EVENT_SHIFTED_SUFFIX_BEFORE if num < 0 else cst.EVENT_SHIFTED_SUFFIX_AFTER
term = f"{cst.EVENT_PREFIX}_{key}_{abs(num)}{freq}{suffix}"
event_levels = [cst.EVENT_DEFAULT]
levels = list(daily_event_df_dict[key][cst.EVENT_DF_LABEL_COL].unique())
levels = [f"{level}_{abs(num)}{freq}{suffix}" for level in levels]
event_levels += levels
event_pred_cols += [patsy_categorical_term(term=term, levels=event_levels)]
return event_pred_cols
The provided code snippet includes necessary dependencies for implementing the `get_autoreg_holiday_interactions` function. Write a Python function `def get_autoreg_holiday_interactions( daily_event_df_dict: Dict[str, pd.DataFrame], lag_names: List[str]) -> List[str]` to solve the following problem:
Gets the interaction terms between holidays and autoregression terms or other lag terms. Parameters ---------- daily_event_df_dict : `Dict` [`str`, `pandas.DataFrame`] The input event configuration. A dictionary with keys being the event names and values being a pandas DataFrame of dates. See `~greykite.algo.forecast.silverkite.forecast_silverkite` for details. lag_names : `List` [`str`] A list of lag names, e.g. ["y_lag1"]. Each will be interacting with the holidays. Returns ------- interactions : `List` [`str`] A list of interaction terms between holidays and lags, to be passed to ``extra_pred_cols``.
Here is the function:
def get_autoreg_holiday_interactions(
daily_event_df_dict: Dict[str, pd.DataFrame],
lag_names: List[str]) -> List[str]:
"""Gets the interaction terms between holidays and autoregression terms or other lag terms.
Parameters
----------
daily_event_df_dict : `Dict` [`str`, `pandas.DataFrame`]
The input event configuration.
A dictionary with keys being the event names and values being a pandas DataFrame of dates.
See `~greykite.algo.forecast.silverkite.forecast_silverkite` for details.
lag_names : `List` [`str`]
A list of lag names, e.g. ["y_lag1"].
Each will be interacting with the holidays.
Returns
-------
interactions : `List` [`str`]
A list of interaction terms between holidays and lags, to be passed to ``extra_pred_cols``.
"""
holiday_names = get_event_pred_cols(daily_event_df_dict)
interactions = [f"{holiday}:{lag}" for lag in lag_names for holiday in holiday_names]
return interactions | Gets the interaction terms between holidays and autoregression terms or other lag terms. Parameters ---------- daily_event_df_dict : `Dict` [`str`, `pandas.DataFrame`] The input event configuration. A dictionary with keys being the event names and values being a pandas DataFrame of dates. See `~greykite.algo.forecast.silverkite.forecast_silverkite` for details. lag_names : `List` [`str`] A list of lag names, e.g. ["y_lag1"]. Each will be interacting with the holidays. Returns ------- interactions : `List` [`str`] A list of interaction terms between holidays and lags, to be passed to ``extra_pred_cols``. |
167,390 | import datetime
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
import pandas as pd
from pandas.tseries.frequencies import to_offset
from greykite.algo.forecast.silverkite.forecast_simple_silverkite_helper import get_event_pred_cols
from greykite.common.constants import EVENT_DF_DATE_COL
from greykite.common.constants import EVENT_DF_LABEL_COL
from greykite.common.constants import EVENT_PREFIX
from greykite.common.constants import EVENT_SHIFTED_SUFFIX_AFTER
from greykite.common.constants import EVENT_SHIFTED_SUFFIX_BEFORE
from greykite.common.python_utils import split_offset_str
def get_event_pred_cols(
daily_event_df_dict,
daily_event_shifted_effect=None):
"""Generates the names of internal predictor columns from
the event dictionary passed to
`~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`.
These can be passed via the ``extra_pred_cols`` parameter to model event effects.
.. note::
The returned strings are patsy model formula terms.
Each provides full set of levels so that prediction works even if a
level is not found in the training set.
If a level does not appear in the training set, its coefficient may
be unbounded in the "linear" fit_algorithm. A method with regularization
avoids this issue (e.g. "ridge", "elastic_net").
Parameters
----------
daily_event_df_dict : `dict` or None, optional, default None
A dictionary of data frames, each representing events data for the corresponding key.
See `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`.
daily_event_shifted_effect : `list` [`str`] or None, default None
Additional neighbor events based on given events.
For example, passing ["-1D", "7D"] will add extra daily events which are 1 day before
and 7 days after the given events.
Offset format is {d}{freq} with any integer plus a frequency string.
Must be parsable by pandas ``to_offset``.
The new events' names will be the current events' names with suffix "{offset}_before" or "{offset}_after".
For example, if we have an event named "US_Christmas Day",
a "7D" shift will have name "US_Christmas Day_7D_after".
This is useful when you expect an offset of the current holidays also has impact on the
time series, or you want to interact the lagged terms with autoregression.
The interaction can be specified with e.g. ``y_lag7:events_US_Christmas Day_7D_after``.
If ``daily_event_neighbor_impact`` is also specified, this will be applied after adding neighboring days.
Returns
-------
event_pred_cols : `list` [`str`]
List of patsy model formula terms, one for each
key of ``daily_event_df_dict``.
"""
event_pred_cols = []
if daily_event_df_dict is not None:
for key in sorted(daily_event_df_dict.keys()):
# `add_daily_events` creates a column with this name.
term = f"{cst.EVENT_PREFIX}_{key}"
# Its values are set to the event df label column. Dates that do not correspond
# to the event are set to `cst.EVENT_DEFAULT`.
event_levels = [cst.EVENT_DEFAULT] # reference level for non-event days
event_levels += list(daily_event_df_dict[key][cst.EVENT_DF_LABEL_COL].unique()) # this event's levels
event_pred_cols += [patsy_categorical_term(term=term, levels=event_levels)]
# Adds columns for additional neighbor events.
# Does the above for each additional lagged event.
if daily_event_shifted_effect is not None:
for lag in daily_event_shifted_effect:
num, freq = split_offset_str(lag)
num = int(num)
suffix = cst.EVENT_SHIFTED_SUFFIX_BEFORE if num < 0 else cst.EVENT_SHIFTED_SUFFIX_AFTER
term = f"{cst.EVENT_PREFIX}_{key}_{abs(num)}{freq}{suffix}"
event_levels = [cst.EVENT_DEFAULT]
levels = list(daily_event_df_dict[key][cst.EVENT_DF_LABEL_COL].unique())
levels = [f"{level}_{abs(num)}{freq}{suffix}" for level in levels]
event_levels += levels
event_pred_cols += [patsy_categorical_term(term=term, levels=event_levels)]
return event_pred_cols
EVENT_DF_DATE_COL = "date"
EVENT_DF_LABEL_COL = "event_name"
EVENT_PREFIX = "events"
EVENT_SHIFTED_SUFFIX_BEFORE = "_before"
EVENT_SHIFTED_SUFFIX_AFTER = "_after"
def split_offset_str(
offset_str: str) -> List[str]:
"""Splits a pandas offset string into number part and frequency string part.
Parameters
----------
offset_str : `str`
An offset string parsable by `pandas`.
For example, "7D", "-5H", etc.
The number part should only include numbers and "+" or "-".
The frequency part should only include letters.
Returns
-------
split_strs : `list` [`str`]
A list of split strings.
For example, ["7", "D"].
"""
freq = offset_str.lstrip("+-012334556789")
num = offset_str[:-len(freq)]
return [num, freq]
The provided code snippet includes necessary dependencies for implementing the `add_shifted_events` function. Write a Python function `def add_shifted_events( daily_event_df_dict: Dict[str, pd.DataFrame], shifted_effect_lags: Optional[List[str]] = None, event_df_date_col: str = EVENT_DF_DATE_COL, event_df_label_col: str = EVENT_DF_LABEL_COL) -> Dict[str, Any]` to solve the following problem:
This function does two things: - (1) adds shifted events to ``daily_event_df_dict`` and returns the new event dictionary. - (2) returns a list of new column names to be added in the model. This is useful when we need to remove these main effects from the model. Parameters ---------- daily_event_df_dict : `Dict` [`str`, `pandas.DataFrame`] The input event configuration. A dictionary with keys being the event names and values being a pandas DataFrame of dates. See `~greykite.algo.forecast.silverkite.forecast_silverkite` for details. shifted_effect_lags : `List` [`str`] or None, default None Additional neighbor events based on given events. For example, passing ["-1D", "7D"] will add extra daily events which are 1 day before and 7 days after the given events. Offset format is {d}{freq} with any integer plus a frequency string. Must be parsable by pandas ``to_offset``. The new events' names will be the current events' names with suffix "{offset}_before" or "{offset}_after". For example, if we have an event named "US_Christmas Day", a "7D" shift will have name "US_Christmas Day_7D_after". This is useful when you expect an offset of the current holidays also has impact on the time series, or you want to interact the lagged terms with autoregression. event_df_date_col : `str`, default ``EVENT_DF_DATE_COL`` Date column of the dataframes in ``daily_event_df_dict``. event_df_label_col : `str`, default ``EVENT_DF_LABEL_COL`` Label column of the dataframes in ``daily_event_df_dict``. Returns ------- shifted_events_dict : `Dict` [`str`, `Any`] A dictionary of results: - "new_daily_event_df_dict": the new event dictionary that expands the input ``daily_event_df_dict`` by adding new shifted events. Note that this is intended to be used to manually add the events. One can also specify the ``events["daily_event_shifted_effect"]`` field to directly add them. - "shifted_events_cols": the column names of the newly added shifted event in the model. This is useful when we need to remove these main effects from the model. One can specify this in ``drop_pred_cols`` to achieve this.
Here is the function:
def add_shifted_events(
daily_event_df_dict: Dict[str, pd.DataFrame],
shifted_effect_lags: Optional[List[str]] = None,
event_df_date_col: str = EVENT_DF_DATE_COL,
event_df_label_col: str = EVENT_DF_LABEL_COL) -> Dict[str, Any]:
"""This function does two things:
- (1) adds shifted events to ``daily_event_df_dict`` and returns the new event dictionary.
- (2) returns a list of new column names to be added in the model.
This is useful when we need to remove these main effects from the model.
Parameters
----------
daily_event_df_dict : `Dict` [`str`, `pandas.DataFrame`]
The input event configuration.
A dictionary with keys being the event names and values being a pandas DataFrame of dates.
See `~greykite.algo.forecast.silverkite.forecast_silverkite` for details.
shifted_effect_lags : `List` [`str`] or None, default None
Additional neighbor events based on given events.
For example, passing ["-1D", "7D"] will add extra daily events which are 1 day before
and 7 days after the given events.
Offset format is {d}{freq} with any integer plus a frequency string. Must be parsable by pandas ``to_offset``.
The new events' names will be the current events' names with suffix "{offset}_before" or "{offset}_after".
For example, if we have an event named "US_Christmas Day",
a "7D" shift will have name "US_Christmas Day_7D_after".
This is useful when you expect an offset of the current holidays also has impact on the
time series, or you want to interact the lagged terms with autoregression.
event_df_date_col : `str`, default ``EVENT_DF_DATE_COL``
Date column of the dataframes in ``daily_event_df_dict``.
event_df_label_col : `str`, default ``EVENT_DF_LABEL_COL``
Label column of the dataframes in ``daily_event_df_dict``.
Returns
-------
shifted_events_dict : `Dict` [`str`, `Any`]
A dictionary of results:
- "new_daily_event_df_dict": the new event dictionary that expands the input
``daily_event_df_dict`` by adding new shifted events.
Note that this is intended to be used to manually add the events.
One can also specify the ``events["daily_event_shifted_effect"]`` field to directly add them.
- "shifted_events_cols": the column names of the newly added shifted event in the model.
This is useful when we need to remove these main effects from the model.
One can specify this in ``drop_pred_cols`` to achieve this.
"""
if shifted_effect_lags is None:
shifted_effect_lags = []
new_daily_event_df_dict = {}
shifted_events_cols = []
drop_pred_cols = []
for order in shifted_effect_lags:
num, freq = split_offset_str(order)
if num == 0:
break
num = int(num)
lag_offset = to_offset(order)
for name, event_df in daily_event_df_dict.items():
new_event_df = event_df.copy()
new_event_df[event_df_date_col] = pd.to_datetime(new_event_df[event_df_date_col])
new_event_df[event_df_date_col] += lag_offset
# Sets suffix of the new event.
suffix = EVENT_SHIFTED_SUFFIX_BEFORE if num < 0 else EVENT_SHIFTED_SUFFIX_AFTER
# Creates a new dataframe to add to `new_daily_event_df_dict`.
new_name = f"{name}_{abs(num)}{freq}{suffix}"
new_event_df[event_df_label_col] = new_name
new_daily_event_df_dict[new_name] = new_event_df
# Records the new column name in the model.
new_col = f"{EVENT_PREFIX}_{new_name}"
shifted_events_cols.append(new_col)
if len(new_daily_event_df_dict) > 0:
drop_pred_cols = get_event_pred_cols(new_daily_event_df_dict)
new_daily_event_df_dict.update(daily_event_df_dict)
return {
"new_daily_event_df_dict": new_daily_event_df_dict,
"shifted_events_cols": shifted_events_cols,
"drop_pred_cols": drop_pred_cols
} | This function does two things: - (1) adds shifted events to ``daily_event_df_dict`` and returns the new event dictionary. - (2) returns a list of new column names to be added in the model. This is useful when we need to remove these main effects from the model. Parameters ---------- daily_event_df_dict : `Dict` [`str`, `pandas.DataFrame`] The input event configuration. A dictionary with keys being the event names and values being a pandas DataFrame of dates. See `~greykite.algo.forecast.silverkite.forecast_silverkite` for details. shifted_effect_lags : `List` [`str`] or None, default None Additional neighbor events based on given events. For example, passing ["-1D", "7D"] will add extra daily events which are 1 day before and 7 days after the given events. Offset format is {d}{freq} with any integer plus a frequency string. Must be parsable by pandas ``to_offset``. The new events' names will be the current events' names with suffix "{offset}_before" or "{offset}_after". For example, if we have an event named "US_Christmas Day", a "7D" shift will have name "US_Christmas Day_7D_after". This is useful when you expect an offset of the current holidays also has impact on the time series, or you want to interact the lagged terms with autoregression. event_df_date_col : `str`, default ``EVENT_DF_DATE_COL`` Date column of the dataframes in ``daily_event_df_dict``. event_df_label_col : `str`, default ``EVENT_DF_LABEL_COL`` Label column of the dataframes in ``daily_event_df_dict``. Returns ------- shifted_events_dict : `Dict` [`str`, `Any`] A dictionary of results: - "new_daily_event_df_dict": the new event dictionary that expands the input ``daily_event_df_dict`` by adding new shifted events. Note that this is intended to be used to manually add the events. One can also specify the ``events["daily_event_shifted_effect"]`` field to directly add them. - "shifted_events_cols": the column names of the newly added shifted event in the model. This is useful when we need to remove these main effects from the model. One can specify this in ``drop_pred_cols`` to achieve this. |
167,391 | import numpy as np
import pandas as pd
import statsmodels
import statsmodels.api as sm
from scipy.stats import f
from scipy.stats import norm
from scipy.stats import t
from sklearn.base import clone
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from greykite.algo.common.col_name_utils import INTERCEPT
from greykite.algo.common.col_name_utils import simplify_pred_cols
INTERCEPT = "Intercept"
The provided code snippet includes necessary dependencies for implementing the `process_intercept` function. Write a Python function `def process_intercept(x, beta, intercept, pred_cols)` to solve the following problem:
Processes the intercept term. Merges intercept in beta and dummy column in x if they are not there. Appends "(Intercept)" to the front of ``pred_cols`` if it is not there. Parameters ---------- x : `numpy.array` The design matrix. beta : `numpy.array` The estimated coefficients. intercept : `float` The estimated intercept. pred_cols : `list` [ `str` ] The names for predictors. Returns ------- x : `numpy.array` The design matrix with dummy column. beta : `numpy.array` The estimated coefficients with intercept in the first position. pred_cols : `list` [ `str` ] List of names of predictors, with "Intercept" in the first position.
Here is the function:
def process_intercept(x, beta, intercept, pred_cols):
"""Processes the intercept term.
Merges intercept in beta and dummy column in x if they are not there.
Appends "(Intercept)" to the front of ``pred_cols`` if it is not there.
Parameters
----------
x : `numpy.array`
The design matrix.
beta : `numpy.array`
The estimated coefficients.
intercept : `float`
The estimated intercept.
pred_cols : `list` [ `str` ]
The names for predictors.
Returns
-------
x : `numpy.array`
The design matrix with dummy column.
beta : `numpy.array`
The estimated coefficients with intercept in the first position.
pred_cols : `list` [ `str` ]
List of names of predictors, with "Intercept" in the first position.
"""
beta = np.copy(beta.ravel())
x = np.copy(x)
# Checks if x has an intercept column
if not all(x[:, 0] == 1):
x = np.concatenate([np.ones([x.shape[0], 1]), x], axis=1)
# Checks beta has intercept column.
# In this case, the coefficient for intercept column should be zero.
# Use intercept as the coefficient for beta column
if x.shape[1] == beta.shape[0]:
beta[0] += intercept # combines the intercept term
# If beta does not have intercept term, concatenate the intercept term.
elif x.shape[1] == beta.shape[0] + 1:
beta = np.concatenate([[intercept], beta])
else:
raise ValueError("The shape of x and beta do not match. "
f"x has shape ({x.shape[0]}, {x.shape[1]}) with the intercept column, "
f"but beta has length {len(beta)}.")
# Processes pred_cols
if len(pred_cols) == x.shape[1] - 1:
pred_cols = [INTERCEPT] + pred_cols
elif len(pred_cols) == x.shape[1] and "Intercept" in pred_cols[0]:
pass
else:
raise ValueError("The length of pred_cols does not match the shape of x. "
f"x has shape ({x.shape[0]}, {x.shape[1]}) with the intercept column, "
f"but pred_cols has length {len(pred_cols)}.")
return x, beta, pred_cols | Processes the intercept term. Merges intercept in beta and dummy column in x if they are not there. Appends "(Intercept)" to the front of ``pred_cols`` if it is not there. Parameters ---------- x : `numpy.array` The design matrix. beta : `numpy.array` The estimated coefficients. intercept : `float` The estimated intercept. pred_cols : `list` [ `str` ] The names for predictors. Returns ------- x : `numpy.array` The design matrix with dummy column. beta : `numpy.array` The estimated coefficients with intercept in the first position. pred_cols : `list` [ `str` ] List of names of predictors, with "Intercept" in the first position. |
167,392 | import numpy as np
import pandas as pd
import statsmodels
import statsmodels.api as sm
from scipy.stats import f
from scipy.stats import norm
from scipy.stats import t
from sklearn.base import clone
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from greykite.algo.common.col_name_utils import INTERCEPT
from greykite.algo.common.col_name_utils import simplify_pred_cols
def create_info_dict_lm(x, y, beta, ml_model, fit_algorithm, pred_cols):
"""Creates a information dictionary for linear model results.
Only basic information will be created in this function.
A series of these functions are used in a flow to get all information needed
in linear model summary. The flow is
`~greykite.algo.common.model_summary_utils.create_info_dict_lm`,
`~greykite.algo.common.model_summary_utils.add_model_params_lm`,
`~greykite.algo.common.model_summary_utils.add_model_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_ss_lm`,
`~greykite.algo.common.model_summary_utils.add_beta_var_lm`,
`~greykite.algo.common.model_summary_utils.add_model_coef_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_significance_lm`.
For flow implementation, see
`~greykite.algo.common.model_summary_utils.get_info_dict_lm`.
Parameters
----------
x : `numpy.array`
The design matrix.
y : `numpy.array`
The response vector.
beta : `numpy.arrar`
The estimated coefficients.
ml_model : `class`
The trained machine learning model class, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`.
fit_algorithm : `str`
The name of fit algorithm, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`.
pred_cols : `list` [ `str` ]
A list of predictor names.
Returns
-------
info_dict : `dict`
A dictionary of basic information with the following keys:
"x" : `numpy.array`
The design matrix.
"y" : `numpy.array`
The response vector.
"beta" : `numpy.array`
The estimated coefficients.
"ml_model" : `class`
The trained machine learning model class, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`.
"fit_algorithm" : `str`
The name of fit algorithm, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`.
"pred_cols" : `list` [ `str` ]
A list of predictor names.
"degenerate_index" : `numpy.array`
The indices where the x columns are degenerate.
"n_sample" : `int`
Number of observations.
"n_feature" : `int`
Number of features.
"nonzero_index" : `numpy.array`
Indices of nonzero coefficients.
"n_feature_nonzero" : `int`
Number of nonzero coefficients.
"y_pred" : `numpy.array`
The predicted values.
"y_mean" : `float`
The mean of response.
"residual" : `numpy.array`
Residuals.
"residual_summary" : `numpy.array`
Five number summary of residuals.
"""
info_dict = dict()
# Passes through the given information
info_dict["x"] = x
info_dict["y"] = y.ravel()
info_dict["beta"] = beta.ravel()
info_dict["ml_model"] = ml_model
info_dict["fit_algorithm"] = fit_algorithm
info_dict["pred_cols"] = pred_cols
# Derives direct information of the input
info_dict["degenerate_index"] = np.arange(x.shape[1])[x.var(axis=0) == 0]
info_dict["n_sample"] = x.shape[0]
info_dict["n_feature"] = x.shape[1]
info_dict["nonzero_index"] = np.nonzero(beta.ravel())[0]
info_dict["n_feature_nonzero"] = len(info_dict["nonzero_index"])
info_dict["y_pred"] = x @ beta
info_dict["y_mean"] = np.mean(y)
info_dict["residual"] = info_dict["y"] - info_dict["y_pred"]
info_dict["residual_summary"] = np.percentile(info_dict["residual"], [0, 25, 50, 75, 100])
return info_dict
def add_model_params_lm(info_dict):
"""Adds model parameter information to ``info_dict`` for linear models.
Only model-related information will be added in this function.
A series of these functions are used in a flow to get all information needed
in linear model summary. The flow is
`~greykite.algo.common.model_summary_utils.create_info_dict_lm`,
`~greykite.algo.common.model_summary_utils.add_model_params_lm`,
`~greykite.algo.common.model_summary_utils.add_model_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_ss_lm`,
`~greykite.algo.common.model_summary_utils.add_beta_var_lm`,
`~greykite.algo.common.model_summary_utils.add_model_coef_df_lm`,
`cadd_model_significance_lm`.
For flow implementation, see
`~greykite.algo.common.model_summary_utils.get_info_dict_lm`.
Parameters
----------
info_dict : `dict`
The information dictionary returned by
`~greykite.algo.common.model_summary_utils.create_info_dict_lm`.
Returns
-------
info_dict : `dict`
The information dictionary with the following keys added:
"model" : `str`
The model name.
"weights" : `numpy.array`, optional
The weight matrix.
"family" : `str`, optional
The distribution family in generalized linear model.
"link_function" : `str`, optional
The link function used in generalized linear model.
"alpha" : `float`, optional
The regularization parameter in regularized methods.
"l1_ratio" : `float`, optional
The l1 norm ratio in Elastic Net methods.
"""
fit_algorithm = info_dict["fit_algorithm"]
ml_model = info_dict["ml_model"]
n_sample = info_dict["n_sample"]
# Dictionary for model parameters
valid_linear_fit_algorithms = ["linear", "statsmodels_ols", "statsmodels_wls", "statsmodels_gls", "statsmodels_glm",
"ridge", "lasso", "lars", "lasso_lars", "sgd", "elastic_net"]
if fit_algorithm in valid_linear_fit_algorithms:
# Adds special parameters
if fit_algorithm in ["linear", "statsmodels_ols"]:
info_dict["model"] = "Ordinary least squares"
elif fit_algorithm == "statsmodels_wls":
info_dict["model"] = "Weighted least squares"
info_dict["weights"] = ml_model.model.weights
elif fit_algorithm == "statsmodels_gls":
info_dict["model"] = "Generalized least squares"
info_dict["weights"] = ml_model.model.sigma
elif fit_algorithm == "statsmodels_glm":
info_dict["model"] = "Generalized linear model"
info_dict["family"] = ml_model.model.family.__class__.__name__
info_dict["link_function"] = ml_model.model.family.link.__class__.__name__
elif fit_algorithm in ["ridge", "lasso", "lars", "lasso_lars"]:
info_dict["model"] = fit_algorithm.capitalize() + " regression"
info_dict["alpha"] = ml_model.alpha_
elif fit_algorithm == "elastic_net":
info_dict["model"] = "Elastic Net regression"
info_dict["alpha"] = ml_model.alpha_
info_dict["l1_ratio"] = ml_model.l1_ratio_
elif fit_algorithm == "sgd":
info_dict["model"] = "Elastic Net regression via SGD"
info_dict["alpha"] = ml_model.alpha # does not have underscore, because this is not cv
if info_dict["ml_model"].penalty == "l1":
info_dict["l1_ratio"] = 1.0
elif info_dict["ml_model"].penalty == "l2":
info_dict["l1_ratio"] = 0.0
else:
info_dict["l1_ratio"] = ml_model.l1_ratio
# Processes parameters
if "weights" in info_dict:
if info_dict["weights"] is None:
weights = np.eye(info_dict["n_sample"])
else:
weights = np.array(info_dict["weights"])
if weights.shape == (): # checks if weights is a scalar
weights = np.diag(np.repeat(weights, n_sample))
elif weights.shape == (n_sample,) or weights.shape == (n_sample, 1): # checks if weights is a vector
weights = np.diag(weights.ravel())
elif weights.shape == (n_sample, n_sample):
weights = weights
else:
raise ValueError("The shape of weights does not match the design matrix. "
f"The design matrix has length {n_sample}. "
f"The weights has shape {weights.shape}.")
info_dict["weights"] = weights
else:
raise ValueError(f"{fit_algorithm} is not a valid algorithm, it must be in "
f"{valid_linear_fit_algorithms}.")
return info_dict
def add_model_df_lm(info_dict):
"""Adds degrees of freedom of the regression model to ``info_dict`` for linear models.
The df is defined as the trace of hat matrix. In general, we have
H=X(X'WX+a*I)^-1X'W and df=trace(H), where X is the design matrix, W is the weight matrix,
a is the regularization parameter, and I it the identity matrix. For non-weighted methods,
W is identity matrix, and for non-regularized methods, a is 0.
For sparse solutions, this is calculated on the nonzero predictors.
Only degree of freedom information will be added in this function.
A series of these functions are used in a flow to get all information needed
in linear model summary. The flow is
`~greykite.algo.common.model_summary_utils.create_info_dict_lm`,
`~greykite.algo.common.model_summary_utils.add_model_params_lm`,
`~greykite.algo.common.model_summary_utils.add_model_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_ss_lm`,
`~greykite.algo.common.model_summary_utils.add_beta_var_lm`,
`~greykite.algo.common.model_summary_utils.add_model_coef_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_significance_lm`.
For flow implementation, see
`~greykite.algo.common.model_summary_utils.get_info_dict_lm`.
Parameters
----------
info_dict : `dict`
The information dictionary returned by
`~greykite.algo.common.model_summary_utils.add_model_params_lm`.
Returns
-------
info_dict : `dict`
The information dictionary with the following keys added:
"x_nz" : `numpy.array`
The design matrix with columns corresponding to nonzero estimated coefficients.
"condition_number" : `float`
The condition number for sample covariance matrix (weighted, adjusted).
"xtwx_alphai_inv" : `numpy.array`
(X'WX+a*I)^-1
"reg_df" : `float`
The regression degree of freedom, defined as the trace of hat matrix.
"df_sse" : `float`
The degree of freedom of residuals, defined as n_sample - reg_df.
"df_ssr" : `float`
The degree of freedom of the regression, defined as reg_df - 1.
"df_sst" : `int`
The degree of freedom of total, defined as n_sample - 1.
"""
x = info_dict["x"]
n_sample = info_dict["n_sample"]
w = info_dict.get("weights")
if w is None:
w = np.eye(n_sample)
alpha = info_dict.get("alpha", 0)
l1_ratio = info_dict.get("l1_ratio", 0)
# In ElasticNet type models (ElasticNetCV, SGD with penalty == "elasticnet"), the penalty is
# alpha * l1_ratio * ||beta||_1 + alpha * (1 - l1_ratio) * ||beta||_2^2.
# For ridge regression, we have l1_ratio = 0, so the l2_norm regularization parameter is alpha.
# For lasso regression, we have l1_ratio = 1, so the l2_norm regularization parameter is zero.
alpha = alpha * (1 - l1_ratio) # if model has l1_ratio, the l2 norm regularization parameter is alpha * (1 - l1_ratio)
if info_dict["fit_algorithm"] in ["lasso", "lars", "lasso_lars"]:
alpha = 0 # alpha is specifically for l2 norm regularization in calculating df
nonzero_idx = info_dict["nonzero_index"]
x_nz = x[:, nonzero_idx]
xtwx = x_nz.T @ w @ x_nz
xtwx_alphai = xtwx + alpha * np.eye(x_nz.shape[1])
xtwx_alphai_inv = np.linalg.pinv(xtwx_alphai)
# The hat matrix was x_nz @ xtwx_alphai_inv @ x_nz.T @ w.
# The regression degrees of freedom is the trace of this hat matrix.
# This matrix is n x n, which causes memory overflow for large n.
# Using the trace property trace(ABCD)=trace(CDAB),
# we compute x_nz.T @ w @ x_nz @ xtwx_alphai_inv,
# which has dimension p x p.
trace = np.trace(x_nz.T @ w @ x_nz @ xtwx_alphai_inv)
info_dict["x_nz"] = x_nz
info_dict["condition_number"] = np.linalg.cond(xtwx_alphai)
info_dict["xtwx_alphai_inv"] = xtwx_alphai_inv # (X'WX+aI)^-1
info_dict["reg_df"] = trace
info_dict["df_sse"] = n_sample - info_dict["reg_df"]
info_dict["df_ssr"] = info_dict["reg_df"] - 1
info_dict["df_sst"] = n_sample - 1
return info_dict
def add_model_ss_lm(info_dict):
"""Adds model sum of squared errors to ``info_dict`` for linear models.
Only sum of squared error information will be added in this function.
A series of these functions are used in a flow to get all information needed
in linear model summary. The flow is
`~greykite.algo.common.model_summary_utils.create_info_dict_lm`,
`~greykite.algo.common.model_summary_utils.add_model_params_lm`,
`~greykite.algo.common.model_summary_utils.add_model_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_ss_lm`,
`~greykite.algo.common.model_summary_utils.add_beta_var_lm`,
`~greykite.algo.common.model_summary_utils.add_model_coef_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_significance_lm`.
For flow implementation, see
`~greykite.algo.common.model_summary_utils.get_info_dict_lm`.
Parameters
----------
info_dict : `dict`
The information dictionary returned by
`~greykite.algo.common.model_summary_utils.add_model_df_lm`.
Returns
-------
info_dict : `dict`
The information dictionary with the following keys added:
"sse" : `float`
Sum of squared errors from residuals.
"mse" : `float`
``sse`` divided by its degree of freedom.
"ssr" : `float`
Sum of squared errors from regression.
"msr" : `float`
``ssr`` divided by its degree of freedom.
"sst" : `float`
Sum of squared errors from total.
"mst" : `float`
``sst`` divided by its degree of freedom.
"""
residual = info_dict["residual"]
weights = info_dict.get("weights")
if weights is None:
weights = np.eye(info_dict["n_sample"])
y = info_dict["y"]
y_pred = info_dict["y_pred"]
y_mean = info_dict["y_mean"]
info_dict["sse"] = residual.T @ weights @ residual
info_dict["mse"] = info_dict["sse"] / info_dict["df_sse"]
info_dict["ssr"] = (y_pred - y_mean).T @ weights @ (y_pred - y_mean)
info_dict["msr"] = info_dict["ssr"] / info_dict["df_ssr"]
info_dict["sst"] = (y - y_mean).T @ weights @ (y - y_mean)
info_dict["mst"] = info_dict["sst"] / info_dict["df_sst"]
return info_dict
def add_beta_var_lm(info_dict):
"""Adds the covariance matrix for estimated coefficients to `info_dict` for linear models.
The covariance matrix for estimated coefficients is defined as
.. code-block:: none
mse * (X'WX+aI)^-1X'X(X'WX+aI)
for linear models, and defined as the inverse Fisher information matrix
divided by ``n_sample`` for generalized linear models.
Only variance of beta hat information will be added in this function.
A series of these functions are used in a flow to get all information needed
in linear model summary. The flow is
`~greykite.algo.common.model_summary_utils.create_info_dict_lm`,
`~greykite.algo.common.model_summary_utils.add_model_params_lm`,
`~greykite.algo.common.model_summary_utils.add_model_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_ss_lm`,
`~greykite.algo.common.model_summary_utils.add_beta_var_lm`,
`~greykite.algo.common.model_summary_utils.add_model_coef_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_significance_lm`.
For flow implementation, see
`~greykite.algo.common.model_summary_utils.get_info_dict_lm`.
Parameters
----------
info_dict : `dict`
The information dictionary returned by
`~greykite.algo.common.model_summary_utils.add_model_ss_lm`.
Returns
-------
info_dict : `dict`
The information dictionary with the following keys added:
"beta_var_cov" : `numpy.array` or `None`
The covariance matrix of estimated coefficients. The square root of
its diagonal elements are standard errors of the estimated coefficients.
Set as ``None`` for sparse solutions.
"""
if (info_dict["fit_algorithm"] in ["statsmodels_ols", "statsmodels_wls", "statsmodels_gls", "linear", "ridge"]
or info_dict["fit_algorithm"] in ["sgd", "elastic_net"] and info_dict["l1_ratio"] == 0):
xtwx_alphai_inv = info_dict["xtwx_alphai_inv"]
mse = info_dict["mse"]
# Variance of estimated coefficients mse * (X'WX+aI)^-1X'X(X'WX+aI)^-1
x_nz = info_dict["x_nz"]
info_dict["beta_var_cov"] = xtwx_alphai_inv @ x_nz.T @ x_nz @ xtwx_alphai_inv * mse
elif info_dict["fit_algorithm"] in ["statsmodels_glm"]:
# Variance of mle is approximately I(beta_hat)^-1/n, where I is Fisher's information matrix.
assert isinstance(info_dict["ml_model"], statsmodels.genmod.generalized_linear_model.GLMResultsWrapper)
info_dict["beta_var_cov"] = info_dict["ml_model"].cov_params()
else:
info_dict["beta_var_cov"] = None # The covariance matrix for beta is not support with sparse solution
return info_dict
def add_model_coef_df_lm(info_dict):
"""Adds the tests and confidence intervals for estimated coefficients
to `info_dict` for linear models.
Only tests and confidence intervals information will be added in this function.
A series of these functions are used in a flow to get all information needed
in linear model summary. The flow is
`~greykite.algo.common.model_summary_utils.create_info_dict_lm`,
`~greykite.algo.common.model_summary_utils.add_model_params_lm`,
`~greykite.algo.common.model_summary_utils.add_model_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_ss_lm`,
`~greykite.algo.common.model_summary_utils.add_beta_var_lm`,
`~greykite.algo.common.model_summary_utils.add_model_coef_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_significance_lm`.
For flow implementation, see
`~greykite.algo.common.model_summary_utils.get_info_dict_lm`.
Parameters
----------
info_dict : `dict`
The information dictionary returned by
`~greykite.algo.common.model_summary_utils.add_beta_var_lm`.
Returns
-------
info_dict : `dict`
The information dictionary with the following keys added:
"coef_summary_df" : `pandas.DataFrame`
The summary df for estimated coefficients.
"significance_code_legend" : `str`, optional
The significance code legend.
"""
if info_dict["fit_algorithm"] in ["statsmodels_ols", "statsmodels_wls", "statsmodels_gls", "linear"]:
info_dict = get_ls_coef_df(info_dict)
elif info_dict["fit_algorithm"] in ["statsmodels_glm"]:
info_dict = get_glm_coef_df(info_dict)
elif (info_dict["fit_algorithm"] in ["ridge"]
or (info_dict["fit_algorithm"] in ["sgd", "elastic_net"] and info_dict["l1_ratio"] == 0)):
info_dict = get_ridge_coef_df(info_dict)
elif (info_dict["fit_algorithm"] in ["lasso", "lars", "lasso_lars"]
or (info_dict["fit_algorithm"] in ["elastic_net"] and info_dict["l1_ratio"] == 1)):
info_dict = get_lasso_coef_df(info_dict)
elif info_dict["fit_algorithm"] in ["sgd", "elastic_net"]:
info_dict = get_elasticnet_coef_df(info_dict)
return info_dict
def add_model_significance_lm(info_dict):
"""Adds model significance metrics to `info_dict` for linear models.
Only model significance metrics information will be added in this function.
A series of these functions are used in a flow to get all information needed
in linear model summary. The flow is
`~greykite.algo.common.model_summary_utils.create_info_dict_lm`,
`~greykite.algo.common.model_summary_utils.add_model_params_lm`,
`~greykite.algo.common.model_summary_utils.add_model_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_ss_lm`,
`~greykite.algo.common.model_summary_utils.add_beta_var_lm`,
`~greykite.algo.common.model_summary_utils.add_model_coef_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_significance_lm`.
For flow implementation, see
`~greykite.algo.common.model_summary_utils.get_info_dict_lm`.
Parameters
----------
info_dict : `dict`
The information dictionary returned by
`~greykite.algo.common.model_summary_utils.add_model_coef_df_lm`.
Returns
-------
info_dict : `dict`
The information dictionary with the following keys added:
"f_value" : `float`
The F-ratio for model significance.
Defined as ``msr / mse``
"f_p_value" : `float`
The p-value of F-ratio using degrees of freedom
``df_ssr`` and ``df_sse``.
"r2" : `float`
The coefficient of determination.
Defined as ``ssr / sst``
"r2_adj" : `float`
The adjusted coefficient of determination.
Defined as ``msr / mst``
"aic" : `float`
The AIC of model, with the constants depending only on
``n_sample`` removed.
"bic" : `float`
The BIC of model, with the constants depending only on
``n_sample`` removed.
"""
# Gets F-value and its p-value
info_dict["f_value"] = info_dict["msr"] / info_dict["mse"]
info_dict["f_p_value"] = 1 - f.cdf(info_dict["f_value"], info_dict["df_ssr"], info_dict["df_sse"])
# Gets R^2 and adjusted R^2
info_dict["r2"] = 1 - info_dict["sse"] / info_dict["sst"]
info_dict["r2_adj"] = 1 - info_dict["mse"] / info_dict["mst"]
# Gets AIC and BIC
if info_dict["fit_algorithm"] == "statsmodels_glm":
info_dict["aic"] = info_dict["ml_model"].aic
info_dict["bic"] = info_dict["ml_model"].bic
else:
info_dict["aic"] = 2 * info_dict["reg_df"] + info_dict["n_sample"] * np.log(info_dict["sse"]) # Ignores the constants
info_dict["bic"] = np.log(info_dict["n_sample"]) * info_dict["reg_df"] + info_dict["n_sample"] * np.log(info_dict["sse"]) # Ignores the constants
return info_dict
The provided code snippet includes necessary dependencies for implementing the `get_info_dict_lm` function. Write a Python function `def get_info_dict_lm(x, y, beta, ml_model, fit_algorithm, pred_cols)` to solve the following problem:
Get the ``info_dict`` dictionary for linear models. A series of functions are used in a flow to get all information needed in linear model summary. The flow is `~greykite.algo.common.model_summary_utils.create_info_dict_lm`, `~greykite.algo.common.model_summary_utils.add_model_params_lm`, `~greykite.algo.common.model_summary_utils.add_model_df_lm`, `~greykite.algo.common.model_summary_utils.add_model_ss_lm`, `~greykite.algo.common.model_summary_utils.add_beta_var_lm`, `~greykite.algo.common.model_summary_utils.add_model_coef_df_lm`, `~greykite.algo.common.model_summary_utils.add_model_significance_lm`. Parameters ---------- x : `numpy.array` The design matrix. y : `numpy.array` The response vector. beta : `numpy.array` The estimated coefficients. ml_model : `class` The trained machine learning model class, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix`. fit_algorithm : `str` The name of fit algorithm, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix`. pred_cols : `list` [ `str` ] A list of predictor names. Returns ------- info_dict : `dict` The dictionary of linear model summary information with the following keys: "x" : `numpy.array` The design matrix. "y" : `numpy.array` The response vector. "beta" : `numpy.array` The estimated coefficients. "ml_model" : `class` The trained machine learning model class, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix` "fit_algorithm" : `str` The name of fit algorithm, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix` "pred_cols" : `list` [ `str` ] A list of predictor names. "degenerate_index" : `numpy.array` The indices where the x columns are degenerate. "n_sample" : `int` Number of observations. "n_feature" : `int` Number of features. "nonzero_index" : `numpy.array` Indices of nonzero coefficients. "n_feature_nonzero" : `int` Number of nonzero coefficients. "y_pred" : `numpy.array` The predicted values. "y_mean" : `float` The mean of response. "residual" : `numpy.array` Residuals. "residual_summary" : `numpy.array` Five number summary of residuals. "model" : `str` The model name. "weights" : `numpy.array`, optional The weight matrix. "family" : `str`, optional The distribution family in generalized linear model. "link_function" : `str`, optional The link function used in generalized linear model. "alpha" : `float`, optional The regularization parameter in regularized methods. "l1_ratio" : `float`, optional The l1 norm ratio in Elastic Net methods. "x_nz" : `numpy.array` The design matrix with columns corresponding to nonzero estimated coefficients. "condition_number" : `float` The condition number for sample covariance matrix (weighted, adjusted). "xtwx_alphai_inv" : `numpy.array` (X'WX+a*I)^-1 "reg_df" : `float` The regression degree of freedom, defined as the trace of hat matrix. "df_sse" : `float` The degree of freedom of residuals, defined as n_sample - reg_df. "df_ssr" : `float` The degree of freedom of the regression, defined as reg_df - 1. "df_sst" : `int` The degree of freedom of total, defined as n_sample - 1. "sse" : `float` Sum of squared errors from residuals. "mse" : `float` ``sse`` divided by its degree of freedom. "ssr" : `float` Sum of squared errors from regression. "msr" : `float` ``ssr`` divided by its degree of freedom. "sst" : `float` Sum of squared errors from total. "mst" : `float` ``sst`` divided by its degree of freedom. "beta_var_cov" : `numpy.array` The covariance matrix of estimated coefficients. The squared root of its diagonal elements are standard errors of the estimated coefficients. Set as ``None`` for sparse solutions. "coef_summary_df" : `pandas.DataFrame` The summary df for estimated coefficients. "significance_code_legend" : `str`, optional The significance code legend. "f_value" : `float` The F-ratio for model significance. Defined as ``msr / mse`` "f_p_value" : `float` The p-value of F-ratio using degrees of freedom ``df_ssr`` and ``df_sse``. "r2" : `float` The coefficient of determination. Defined as ``ssr / sst`` "r2_adj" : `float` The adjusted coefficient of determination. Defined as ``msr / mst`` "aic" : `float` The AIC of model, with the constants depending only on ``n_sample`` removed. "bic" : `float` The BIC of model, with the constants depending only on ``n_sample`` removed. "model_type" : `str` Equals "lm".
Here is the function:
def get_info_dict_lm(x, y, beta, ml_model, fit_algorithm, pred_cols):
"""Get the ``info_dict`` dictionary for linear models.
A series of functions are used in a flow to get all information needed
in linear model summary. The flow is
`~greykite.algo.common.model_summary_utils.create_info_dict_lm`,
`~greykite.algo.common.model_summary_utils.add_model_params_lm`,
`~greykite.algo.common.model_summary_utils.add_model_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_ss_lm`,
`~greykite.algo.common.model_summary_utils.add_beta_var_lm`,
`~greykite.algo.common.model_summary_utils.add_model_coef_df_lm`,
`~greykite.algo.common.model_summary_utils.add_model_significance_lm`.
Parameters
----------
x : `numpy.array`
The design matrix.
y : `numpy.array`
The response vector.
beta : `numpy.array`
The estimated coefficients.
ml_model : `class`
The trained machine learning model class, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`.
fit_algorithm : `str`
The name of fit algorithm, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`.
pred_cols : `list` [ `str` ]
A list of predictor names.
Returns
-------
info_dict : `dict`
The dictionary of linear model summary information with the following keys:
"x" : `numpy.array`
The design matrix.
"y" : `numpy.array`
The response vector.
"beta" : `numpy.array`
The estimated coefficients.
"ml_model" : `class`
The trained machine learning model class, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`
"fit_algorithm" : `str`
The name of fit algorithm, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`
"pred_cols" : `list` [ `str` ]
A list of predictor names.
"degenerate_index" : `numpy.array`
The indices where the x columns are degenerate.
"n_sample" : `int`
Number of observations.
"n_feature" : `int`
Number of features.
"nonzero_index" : `numpy.array`
Indices of nonzero coefficients.
"n_feature_nonzero" : `int`
Number of nonzero coefficients.
"y_pred" : `numpy.array`
The predicted values.
"y_mean" : `float`
The mean of response.
"residual" : `numpy.array`
Residuals.
"residual_summary" : `numpy.array`
Five number summary of residuals.
"model" : `str`
The model name.
"weights" : `numpy.array`, optional
The weight matrix.
"family" : `str`, optional
The distribution family in generalized linear model.
"link_function" : `str`, optional
The link function used in generalized linear model.
"alpha" : `float`, optional
The regularization parameter in regularized methods.
"l1_ratio" : `float`, optional
The l1 norm ratio in Elastic Net methods.
"x_nz" : `numpy.array`
The design matrix with columns corresponding to nonzero estimated coefficients.
"condition_number" : `float`
The condition number for sample covariance matrix (weighted, adjusted).
"xtwx_alphai_inv" : `numpy.array`
(X'WX+a*I)^-1
"reg_df" : `float`
The regression degree of freedom, defined as the trace of hat matrix.
"df_sse" : `float`
The degree of freedom of residuals, defined as n_sample - reg_df.
"df_ssr" : `float`
The degree of freedom of the regression, defined as reg_df - 1.
"df_sst" : `int`
The degree of freedom of total, defined as n_sample - 1.
"sse" : `float`
Sum of squared errors from residuals.
"mse" : `float`
``sse`` divided by its degree of freedom.
"ssr" : `float`
Sum of squared errors from regression.
"msr" : `float`
``ssr`` divided by its degree of freedom.
"sst" : `float`
Sum of squared errors from total.
"mst" : `float`
``sst`` divided by its degree of freedom.
"beta_var_cov" : `numpy.array`
The covariance matrix of estimated coefficients. The squared root of
its diagonal elements are standard errors of the estimated coefficients.
Set as ``None`` for sparse solutions.
"coef_summary_df" : `pandas.DataFrame`
The summary df for estimated coefficients.
"significance_code_legend" : `str`, optional
The significance code legend.
"f_value" : `float`
The F-ratio for model significance.
Defined as ``msr / mse``
"f_p_value" : `float`
The p-value of F-ratio using degrees of freedom
``df_ssr`` and ``df_sse``.
"r2" : `float`
The coefficient of determination.
Defined as ``ssr / sst``
"r2_adj" : `float`
The adjusted coefficient of determination.
Defined as ``msr / mst``
"aic" : `float`
The AIC of model, with the constants depending only on
``n_sample`` removed.
"bic" : `float`
The BIC of model, with the constants depending only on
``n_sample`` removed.
"model_type" : `str`
Equals "lm".
"""
info_dict = create_info_dict_lm(x, y, beta, ml_model, fit_algorithm, pred_cols)
info_dict = add_model_params_lm(info_dict)
info_dict = add_model_df_lm(info_dict)
info_dict = add_model_ss_lm(info_dict)
info_dict = add_beta_var_lm(info_dict)
info_dict = add_model_coef_df_lm(info_dict)
info_dict = add_model_significance_lm(info_dict)
info_dict["model_type"] = "lm"
return info_dict | Get the ``info_dict`` dictionary for linear models. A series of functions are used in a flow to get all information needed in linear model summary. The flow is `~greykite.algo.common.model_summary_utils.create_info_dict_lm`, `~greykite.algo.common.model_summary_utils.add_model_params_lm`, `~greykite.algo.common.model_summary_utils.add_model_df_lm`, `~greykite.algo.common.model_summary_utils.add_model_ss_lm`, `~greykite.algo.common.model_summary_utils.add_beta_var_lm`, `~greykite.algo.common.model_summary_utils.add_model_coef_df_lm`, `~greykite.algo.common.model_summary_utils.add_model_significance_lm`. Parameters ---------- x : `numpy.array` The design matrix. y : `numpy.array` The response vector. beta : `numpy.array` The estimated coefficients. ml_model : `class` The trained machine learning model class, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix`. fit_algorithm : `str` The name of fit algorithm, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix`. pred_cols : `list` [ `str` ] A list of predictor names. Returns ------- info_dict : `dict` The dictionary of linear model summary information with the following keys: "x" : `numpy.array` The design matrix. "y" : `numpy.array` The response vector. "beta" : `numpy.array` The estimated coefficients. "ml_model" : `class` The trained machine learning model class, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix` "fit_algorithm" : `str` The name of fit algorithm, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix` "pred_cols" : `list` [ `str` ] A list of predictor names. "degenerate_index" : `numpy.array` The indices where the x columns are degenerate. "n_sample" : `int` Number of observations. "n_feature" : `int` Number of features. "nonzero_index" : `numpy.array` Indices of nonzero coefficients. "n_feature_nonzero" : `int` Number of nonzero coefficients. "y_pred" : `numpy.array` The predicted values. "y_mean" : `float` The mean of response. "residual" : `numpy.array` Residuals. "residual_summary" : `numpy.array` Five number summary of residuals. "model" : `str` The model name. "weights" : `numpy.array`, optional The weight matrix. "family" : `str`, optional The distribution family in generalized linear model. "link_function" : `str`, optional The link function used in generalized linear model. "alpha" : `float`, optional The regularization parameter in regularized methods. "l1_ratio" : `float`, optional The l1 norm ratio in Elastic Net methods. "x_nz" : `numpy.array` The design matrix with columns corresponding to nonzero estimated coefficients. "condition_number" : `float` The condition number for sample covariance matrix (weighted, adjusted). "xtwx_alphai_inv" : `numpy.array` (X'WX+a*I)^-1 "reg_df" : `float` The regression degree of freedom, defined as the trace of hat matrix. "df_sse" : `float` The degree of freedom of residuals, defined as n_sample - reg_df. "df_ssr" : `float` The degree of freedom of the regression, defined as reg_df - 1. "df_sst" : `int` The degree of freedom of total, defined as n_sample - 1. "sse" : `float` Sum of squared errors from residuals. "mse" : `float` ``sse`` divided by its degree of freedom. "ssr" : `float` Sum of squared errors from regression. "msr" : `float` ``ssr`` divided by its degree of freedom. "sst" : `float` Sum of squared errors from total. "mst" : `float` ``sst`` divided by its degree of freedom. "beta_var_cov" : `numpy.array` The covariance matrix of estimated coefficients. The squared root of its diagonal elements are standard errors of the estimated coefficients. Set as ``None`` for sparse solutions. "coef_summary_df" : `pandas.DataFrame` The summary df for estimated coefficients. "significance_code_legend" : `str`, optional The significance code legend. "f_value" : `float` The F-ratio for model significance. Defined as ``msr / mse`` "f_p_value" : `float` The p-value of F-ratio using degrees of freedom ``df_ssr`` and ``df_sse``. "r2" : `float` The coefficient of determination. Defined as ``ssr / sst`` "r2_adj" : `float` The adjusted coefficient of determination. Defined as ``msr / mst`` "aic" : `float` The AIC of model, with the constants depending only on ``n_sample`` removed. "bic" : `float` The BIC of model, with the constants depending only on ``n_sample`` removed. "model_type" : `str` Equals "lm". |
167,393 | import numpy as np
import pandas as pd
import statsmodels
import statsmodels.api as sm
from scipy.stats import f
from scipy.stats import norm
from scipy.stats import t
from sklearn.base import clone
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from greykite.algo.common.col_name_utils import INTERCEPT
from greykite.algo.common.col_name_utils import simplify_pred_cols
def create_info_dict_tree(x, y, ml_model, fit_algorithm, pred_cols):
"""Creates a information dictionary for tree model results.
Only basic information will be created in this function.
A series of these functions are used in a flow to get all information needed
in tree model summary. The flow is
`~greykite.algo.common.model_summary_utils.create_info_dict_tree`,
`~greykite.algo.common.model_summary_utils.add_model_params_tree`,
`~greykite.algo.common.model_summary_utils.add_model_coef_df_tree`.
For flow implementation, see
`~greykite.algo.common.model_summary_utils.get_info_dict_tree`.
Parameters
----------
x : `numpy.array`
The design matrix.
y : `numpy.array`
The response vector.
ml_model : `class`
The trained machine learning model class, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`.
fit_algorithm : `str`
The name of fit algorithm, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`.
pred_cols : `list` [ `str` ]
A list of predictor names.
Returns
-------
info_dict : `dict`
A dictionary of basic information with the following keys:
"x" : `numpy.array`
The design matrix.
"y" : `numpy.array`
The response vector.
"ml_model" : `class`
The trained machine learning model class, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`.
"fit_algorithm" : `str`
The name of fit algorithm, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`.
"pred_cols" : `list` [ `str` ]
A list of predictor names.
"degenerate_index" : `numpy.array`
The indices where the x columns are degenerate.
"n_sample" : `int`
Number of observations.
"n_feature" : `int`
Number of features.
"y_pred" : `numpy.array`
The predicted values.
"y_mean" : `float`
The mean of response.
"residual" : `numpy.array`
Residuals.
"residual_summary" : `numpy.array`
Five number summary of residuals.
"""
info_dict = dict()
# Passes through the given information
info_dict["x"] = x
info_dict["y"] = y
info_dict["ml_model"] = ml_model
info_dict["fit_algorithm"] = fit_algorithm
info_dict["pred_cols"] = pred_cols
# Derives simple information
info_dict["n_sample"] = x.shape[0]
info_dict["n_feature"] = x.shape[1]
info_dict["y_pred"] = ml_model.predict(x)
info_dict["y_mean"] = np.mean(y)
info_dict["residual"] = info_dict["y"] - info_dict["y_pred"]
info_dict["residual_summary"] = np.percentile(info_dict["residual"], [0, 25, 50, 75, 100])
return info_dict
def add_model_params_tree(info_dict):
"""Adds model parameters to `info_dict` for tree models.
Only model-related parameter information will be added in this function.
A series of these functions are used in a flow to get all information needed
in tree model summary. The flow is
`~greykite.algo.common.model_summary_utils.create_info_dict_tree`,
`~greykite.algo.common.model_summary_utils.add_model_params_tree`,
`~greykite.algo.common.model_summary_utils.add_model_coef_df_tree`.
For flow implementation, see
`~greykite.algo.common.model_summary_utils.get_info_dict_tree`.
Parameters
----------
info_dict : `dict`
The information dictionary returned by
`~greykite.algo.common.model_summary_utils.create_info_dict_tree`.
Returns
-------
info_dict : `dict`
The information dictionary with the following keys added:
"model" : `str`
The model name.
"num_tree" : `int`
Number of trees used.
"criterion" : `str`
The criterion to be minimized.
"max_depth" : `int` or `None`
The maximal tree depth.
"subsample" : `float`, `int` or `None`
The subsampling proportion or a whole number to sample.
"max_features" : `int` or `None`
The maximal number of features to be used in a single split.
"""
fit_algorithm = info_dict["fit_algorithm"]
ml_model = info_dict["ml_model"]
valid_tree_fit_algorithms = ["rf", "gradient_boosting"]
if fit_algorithm in valid_tree_fit_algorithms:
if fit_algorithm == "gradient_boosting":
info_dict["model"] = "Gradient Boosting"
info_dict["num_tree"] = ml_model.n_estimators_
info_dict["criterion"] = ml_model.criterion
info_dict["max_depth"] = ml_model.max_depth
info_dict["subsample"] = ml_model.subsample
info_dict["max_features"] = ml_model.max_features_
elif fit_algorithm == "rf":
info_dict["model"] = "Random Forest"
info_dict["num_tree"] = ml_model.n_estimators
info_dict["criterion"] = ml_model.criterion
info_dict["max_depth"] = ml_model.max_depth
info_dict["subsample"] = ml_model.max_samples
info_dict["max_features"] = ml_model.max_features
else:
raise ValueError(f"{fit_algorithm} is not a valid algorithm, it must be in "
f"{valid_tree_fit_algorithms}.")
return info_dict
def add_model_coef_df_tree(info_dict):
"""Adds coefficient summary df to `info_dict` for tree models.
Only coefficient summary information will be added in this function.
A series of these functions are used in a flow to get all information needed
in tree model summary. The flow is
`~greykite.algo.common.model_summary_utils.create_info_dict_tree`,
`~greykite.algo.common.model_summary_utils.add_model_params_tree`,
`~greykite.algo.common.model_summary_utils.add_model_coef_df_tree`.
For flow implementation, see
`~greykite.algo.common.model_summary_utils.get_info_dict_tree`.
Parameters
----------
info_dict : `dict`
The information dictionary returned by
`~greykite.algo.common.model_summary_utils.add_model_params_tree`.
Returns
-------
info_dict : `dict`
The information dictionary with the following keys added:
"coef_summary_df" : `pandas.DataFrame`
The model summary df with the following columns:
"Pred_col" : `str`
The predictor names.
"Feature importance" : `float`
The impurity-based feature importance.
"Importance rank" : `int`
The rank of feature importance.
"""
feature_importance = info_dict["ml_model"].feature_importances_
# Gets ranks
temp = feature_importance.argsort()
ranks = np.empty_like(temp)
ranks[temp] = np.arange(len(feature_importance))
coef_df = pd.DataFrame({
"Pred_col": info_dict["pred_cols"],
"Feature importance": feature_importance,
"Importance rank": len(feature_importance) - ranks # Reverse order
})
info_dict["coef_summary_df"] = coef_df
return info_dict
The provided code snippet includes necessary dependencies for implementing the `get_info_dict_tree` function. Write a Python function `def get_info_dict_tree(x, y, ml_model, fit_algorithm, pred_cols)` to solve the following problem:
Get the ``info_dict`` dictionary for tree models. A series of functions are used in a flow to get all information needed in tree model summary. The flow is `~greykite.algo.common.model_summary_utils.create_info_dict_tree`, `~greykite.algo.common.model_summary_utils.add_model_params_tree`, `~greykite.algo.common.model_summary_utils.add_model_coef_df_tree`. Parameters ---------- x : `numpy.array` The design matrix. y : `numpy.array` The response vector. ml_model : `class` The trained machine learning model class, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix` fit_algorithm : `str` The name of fit algorithm, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix` pred_cols : `list` [ `str` ] A list of predictor names. Returns ------- info_dict : `dict` The dictionary of tree model summary information with the following keys: "x" : `numpy.array` The design matrix. "y" : `numpy.array` The response vector. "ml_model" : `class` The trained machine learning model class, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix` "fit_algorithm" : `str` The name of fit algorithm, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix` "pred_cols" : `list` [ `str` ] A list of predictor names. "degenerate_index" : `numpy.array` The indices where the x columns are degenerate. "n_sample" : `int` Number of observations. "n_feature" : `int` Number of features. "y_pred" : `numpy.array` The predicted values. "y_mean" : `float` The mean of response. "residual" : `numpy.array` Residuals. "residual_summary" : `numpy.array` Five number summary of residuals. "model" : `str` The model name. "num_tree" : `int` Number of trees used. "criterion" : `str` The criterion to be minimized. "max_depth" : `int` or `None` The maximal tree depth. "subsample" : `float` or `None` The subsampling proportion. "max_features" : `int` or `None` The maximal number of features to be used in a single split. "coef_summary_df" : `pandas.DataFrame` The model summary df with the following columns: "Pred_col" : `str` The predictor names. "Feature importance" : `float` The impurity-based feature importance. "Importance rank" : `int` The rank of feature importance. "model_type" : `str` Equals "tree" for tree models.
Here is the function:
def get_info_dict_tree(x, y, ml_model, fit_algorithm, pred_cols):
"""Get the ``info_dict`` dictionary for tree models.
A series of functions are used in a flow to get all information needed
in tree model summary. The flow is
`~greykite.algo.common.model_summary_utils.create_info_dict_tree`,
`~greykite.algo.common.model_summary_utils.add_model_params_tree`,
`~greykite.algo.common.model_summary_utils.add_model_coef_df_tree`.
Parameters
----------
x : `numpy.array`
The design matrix.
y : `numpy.array`
The response vector.
ml_model : `class`
The trained machine learning model class, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`
fit_algorithm : `str`
The name of fit algorithm, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`
pred_cols : `list` [ `str` ]
A list of predictor names.
Returns
-------
info_dict : `dict`
The dictionary of tree model summary information with the following keys:
"x" : `numpy.array`
The design matrix.
"y" : `numpy.array`
The response vector.
"ml_model" : `class`
The trained machine learning model class, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`
"fit_algorithm" : `str`
The name of fit algorithm, see
`~greykite.algo.common.ml_models.fit_model_via_design_matrix`
"pred_cols" : `list` [ `str` ]
A list of predictor names.
"degenerate_index" : `numpy.array`
The indices where the x columns are degenerate.
"n_sample" : `int`
Number of observations.
"n_feature" : `int`
Number of features.
"y_pred" : `numpy.array`
The predicted values.
"y_mean" : `float`
The mean of response.
"residual" : `numpy.array`
Residuals.
"residual_summary" : `numpy.array`
Five number summary of residuals.
"model" : `str`
The model name.
"num_tree" : `int`
Number of trees used.
"criterion" : `str`
The criterion to be minimized.
"max_depth" : `int` or `None`
The maximal tree depth.
"subsample" : `float` or `None`
The subsampling proportion.
"max_features" : `int` or `None`
The maximal number of features to be used in a single split.
"coef_summary_df" : `pandas.DataFrame`
The model summary df with the following columns:
"Pred_col" : `str`
The predictor names.
"Feature importance" : `float`
The impurity-based feature importance.
"Importance rank" : `int`
The rank of feature importance.
"model_type" : `str`
Equals "tree" for tree models.
"""
info_dict = create_info_dict_tree(x, y, ml_model, fit_algorithm, pred_cols)
info_dict = add_model_params_tree(info_dict)
info_dict = add_model_coef_df_tree(info_dict)
info_dict["model_type"] = "tree"
return info_dict | Get the ``info_dict`` dictionary for tree models. A series of functions are used in a flow to get all information needed in tree model summary. The flow is `~greykite.algo.common.model_summary_utils.create_info_dict_tree`, `~greykite.algo.common.model_summary_utils.add_model_params_tree`, `~greykite.algo.common.model_summary_utils.add_model_coef_df_tree`. Parameters ---------- x : `numpy.array` The design matrix. y : `numpy.array` The response vector. ml_model : `class` The trained machine learning model class, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix` fit_algorithm : `str` The name of fit algorithm, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix` pred_cols : `list` [ `str` ] A list of predictor names. Returns ------- info_dict : `dict` The dictionary of tree model summary information with the following keys: "x" : `numpy.array` The design matrix. "y" : `numpy.array` The response vector. "ml_model" : `class` The trained machine learning model class, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix` "fit_algorithm" : `str` The name of fit algorithm, see `~greykite.algo.common.ml_models.fit_model_via_design_matrix` "pred_cols" : `list` [ `str` ] A list of predictor names. "degenerate_index" : `numpy.array` The indices where the x columns are degenerate. "n_sample" : `int` Number of observations. "n_feature" : `int` Number of features. "y_pred" : `numpy.array` The predicted values. "y_mean" : `float` The mean of response. "residual" : `numpy.array` Residuals. "residual_summary" : `numpy.array` Five number summary of residuals. "model" : `str` The model name. "num_tree" : `int` Number of trees used. "criterion" : `str` The criterion to be minimized. "max_depth" : `int` or `None` The maximal tree depth. "subsample" : `float` or `None` The subsampling proportion. "max_features" : `int` or `None` The maximal number of features to be used in a single split. "coef_summary_df" : `pandas.DataFrame` The model summary df with the following columns: "Pred_col" : `str` The predictor names. "Feature importance" : `float` The impurity-based feature importance. "Importance rank" : `int` The rank of feature importance. "model_type" : `str` Equals "tree" for tree models. |
167,394 | import numpy as np
import pandas as pd
import statsmodels
import statsmodels.api as sm
from scipy.stats import f
from scipy.stats import norm
from scipy.stats import t
from sklearn.base import clone
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from greykite.algo.common.col_name_utils import INTERCEPT
from greykite.algo.common.col_name_utils import simplify_pred_cols
def create_title_section():
"""Creates the title section for model summary.
Returns
-------
content : `str`
Title section.
"""
content = " Forecast Model Summary ".center(80, "=") + "\n\n"
return content
def create_model_parameter_section(info_dict):
"""Creates the model parameter section for model summary.
Parameters
----------
info_dict : `dict`
The dictionary returned by
`~greykite.algo.common.model_summary_utils.get_info_dict_lm`.
or
`~greykite.algo.common.model_summary_utils.get_info_dict_tree`.
Returns
-------
content : `str`
The model parameter section.
"""
content = f"Number of observations: {info_dict['n_sample']}"
content += ", "
content += f"Number of features: {info_dict['n_feature']}"
content += "\n"
content += f"Method: {info_dict['model']}"
content += "\n"
if info_dict["model_type"] == "lm":
content += f"Number of nonzero features: {info_dict['n_feature_nonzero']}"
content += "\n"
if info_dict["fit_algorithm"] == "statsmodels_glm":
content += f"Family: {info_dict['family']}"
content += ", "
content += f"Link function: {info_dict['link_function']}"
content += "\n"
elif info_dict["fit_algorithm"] in ["ridge", "lasso", "lars", "lasso_lars",
"elastic_net", "sgd"]:
content += f"Regularization parameter: {round_numbers(info_dict['alpha'], 4)}"
if info_dict["fit_algorithm"] in ["elastic_net", "sgd"]:
content += ", "
content += f"l1_ratio: {round_numbers(info_dict['l1_ratio'], 4)}"
content += "\n"
elif info_dict["model_type"] == "tree":
content += f"Number of Trees: {info_dict['num_tree']}"
content += ", "
content += f"Criterion: {info_dict['criterion'].upper()}"
content += "\n"
content += f"Subsample: {info_dict['subsample']}"
content += ", "
content += f"Max features: {info_dict['max_features']}"
content += ", "
content += f"Max depth: {info_dict['max_depth']}"
content += "\n"
content += "\n"
return content
def create_residual_section(info_dict):
"""Creates the residual section for model summary.
Parameters
----------
info_dict : `dict`
The dictionary returned by
`~greykite.algo.common.model_summary_utils.get_info_dict_lm`.
or
`~greykite.algo.common.model_summary_utils.get_info_dict_tree`.
Returns
-------
content : `str`
The residual section.
"""
residual_summary = round_numbers(info_dict["residual_summary"], 4)
content = "Residuals:\n"
content += "{:>12} {:>12} {:>12} {:>12} {:>12}".format("Min", "1Q", "Median", "3Q", "Max") + "\n"
content += "{:>12} {:>12} {:>12} {:>12} {:>12}".format(*list(residual_summary)) + "\n"
content += "\n"
return content
def create_coef_df_section(info_dict, max_colwidth=20):
"""Creates the coefficient summary df section for model summary.
Parameters
----------
info_dict : `dict`
The dictionary returned by
`~greykite.algo.common.model_summary_utils.get_info_dict_lm`.
or
`~greykite.algo.common.model_summary_utils.get_info_dict_tree`.
max_colwidth : `int`
The maximum length for predictors to be shown in their original name.
If the maximum length of predictors exceeds this parameter, all
predictors name will be suppressed and only indices are shown.
Returns
-------
content : `str`
The coefficient summary df section.
"""
content = format_summary_df(info_dict["coef_summary_df"], max_colwidth).to_string(index=False)
content += "\n"
if "significance_code_legend" in info_dict.keys():
content += f"Signif. Code: {info_dict['significance_code_legend']}"
content += "\n"
content += "\n"
return content
def create_significance_section(info_dict):
"""Creates the model sifnificance section for model summary.
Parameters
----------
info_dict : `dict`
The dictionary returned by
`~greykite.algo.common.model_summary_utils.get_info_dict_lm`.
or
`~greykite.algo.common.model_summary_utils.get_info_dict_tree`.
Returns
-------
content : `str`
The model significance section.
"""
if info_dict["model_type"] == "lm":
content = f"Multiple R-squared: {round_numbers(info_dict['r2'], 4)},"
content += " "
content += f"Adjusted R-squared: {round_numbers(info_dict['r2_adj'], 4)}"
content += "\n"
content += f"F-statistic: {round_numbers(info_dict['f_value'], 5)} " \
f"on {int(info_dict['df_ssr'])} and" \
f" {int(info_dict['df_sse'])} DF,"
content += " "
content += f"p-value: {round_numbers(info_dict['f_p_value'], 4)}"
content += "\n"
content += f"Model AIC: {round_numbers(info_dict['aic'], 5)},"
content += " "
content += f"model BIC: {round_numbers(info_dict['bic'], 5)}"
content += "\n\n"
return content
else:
return None
def create_warning_section(info_dict):
"""Creates the warning section for model summary.
The following warnings are possible to be included:
Condition number is too big.
F-ratio and p-value on regularized methods.
R-squared and F-ratio in glm.
Zero coefficients in non-sparse regression methods due to degenerate columns.
Parameters
----------
info_dict : `dict`
The dictionary returned by
`~greykite.algo.common.model_summary_utils.get_info_dict_lm`.
or
`~greykite.algo.common.model_summary_utils.get_info_dict_tree`.
Returns
-------
content : `str`
The model warnings section.
"""
if info_dict["model_type"] == "lm":
content = ""
if info_dict["condition_number"] > 1000:
content += f"WARNING: the condition number is large, {'{:.2e}'.format(info_dict['condition_number'])}. " \
f"This might indicate that there are strong multicollinearity " \
f"or other numerical problems."
content += "\n"
if info_dict["fit_algorithm"] in ["ridge", "lasso", "lars", "lasso_lars",
"sgd", "elastic_net"]:
content += "WARNING: the F-ratio and its p-value on regularized methods might be misleading, " \
"they are provided only for reference purposes."
content += "\n"
if info_dict["fit_algorithm"] in ["statsmodels_glm"]:
content += "WARNING: the R-squared and F-statistics on glm might be misleading, " \
"they are provided only for reference purposes."
content += "\n"
if (len(info_dict["nonzero_index"]) < info_dict["n_feature"]
and
info_dict["fit_algorithm"] in ["linear", "ridge", "statsmodels_ols",
"statsmodels_wls", "statsmodels_gls",
"statsmodels_glm"]):
content += "WARNING: the following columns have estimated coefficients equal to zero, " \
f"while {info_dict['fit_algorithm']} is not supposed to have zero estimates. " \
f"This is probably because these columns are degenerate in the design matrix. " \
f"Make sure these columns do not have constant values." + "\n" +\
f"{[col for i, col in enumerate(info_dict['pred_cols']) if i not in info_dict['nonzero_index']]}"
content += "\n"
if len(info_dict["degenerate_index"]) > 1:
content += "WARNING: the following columns are degenerate, do you really want to include them in your model? " \
"This may cause some of them to show unrealistic significance. Consider using the `drop_degenerate` transformer." + "\n" +\
f"{[col for i, col in enumerate(info_dict['pred_cols']) if i in info_dict['degenerate_index']]}"
content += "\n"
if content == "":
content = None
else:
content = None
return content
The provided code snippet includes necessary dependencies for implementing the `print_summary` function. Write a Python function `def print_summary(info_dict, max_colwidth=20)` to solve the following problem:
Creates the content for printing the summary. Parameters ---------- info_dict : `dict` The output summary dictionary from `~greykite.algo.common.model_summary.ModelSummary._get_summary`, which is originally from `~greykite.algo.common.model_summary_utils.get_info_dict_lm` or `~greykite.algo.common.model_summary_utils.get_info_dict_tree`. max_colwidth : `int` The maximum length for predictors to be shown in their original name. If the maximum length of predictors exceeds this parameter, all predictors name will be suppressed and only indices are shown. Returns ------- summary_content : `str` The content to be printed.
Here is the function:
def print_summary(info_dict, max_colwidth=20):
"""Creates the content for printing the summary.
Parameters
----------
info_dict : `dict`
The output summary dictionary from
`~greykite.algo.common.model_summary.ModelSummary._get_summary`,
which is originally from
`~greykite.algo.common.model_summary_utils.get_info_dict_lm`
or
`~greykite.algo.common.model_summary_utils.get_info_dict_tree`.
max_colwidth : `int`
The maximum length for predictors to be shown in their original name.
If the maximum length of predictors exceeds this parameter, all
predictors name will be suppressed and only indices are shown.
Returns
-------
summary_content : `str`
The content to be printed.
"""
content = create_title_section()
model_param_section = create_model_parameter_section(info_dict)
if model_param_section is not None:
content += model_param_section
residual_section = create_residual_section(info_dict)
if residual_section is not None:
content += residual_section
coef_df_section = create_coef_df_section(info_dict, max_colwidth)
if coef_df_section is not None:
content += coef_df_section
signif_section = create_significance_section(info_dict)
if signif_section is not None:
content += signif_section
warning_section = create_warning_section(info_dict)
if warning_section is not None:
content += warning_section
return content | Creates the content for printing the summary. Parameters ---------- info_dict : `dict` The output summary dictionary from `~greykite.algo.common.model_summary.ModelSummary._get_summary`, which is originally from `~greykite.algo.common.model_summary_utils.get_info_dict_lm` or `~greykite.algo.common.model_summary_utils.get_info_dict_tree`. max_colwidth : `int` The maximum length for predictors to be shown in their original name. If the maximum length of predictors exceeds this parameter, all predictors name will be suppressed and only indices are shown. Returns ------- summary_content : `str` The content to be printed. |
167,395 | import random
import re
import traceback
import warnings
from typing import Dict
from typing import List
from typing import Optional
import matplotlib
import numpy as np
import pandas as pd
import patsy
import scipy
import statsmodels.api as sm
from pandas.plotting import register_matplotlib_converters
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import ElasticNetCV
from sklearn.linear_model import LarsCV
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LassoLarsCV
from sklearn.linear_model import RidgeCV
from sklearn.linear_model import SGDRegressor
from greykite.algo.common.l1_quantile_regression import QuantileRegression
from greykite.algo.uncertainty.conditional.conf_interval import conf_interval
from greykite.algo.uncertainty.conditional.conf_interval import predict_ci
from greykite.common.constants import RESIDUAL_COL
from greykite.common.constants import R2_null_model_score
from greykite.common.evaluation import calc_pred_err
from greykite.common.evaluation import r2_null_model_score
from greykite.common.features.normalize import normalize_df
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.common.python_utils import group_strs_with_regex_patterns
from greykite.common.viz.timeseries_plotting import plot_multivariate
import matplotlib.pyplot as plt
def fit_ml_model(
df,
model_formula_str=None,
fit_algorithm="linear",
fit_algorithm_params=None,
y_col=None,
pred_cols=None,
min_admissible_value=None,
max_admissible_value=None,
uncertainty_dict=None,
normalize_method="zero_to_one",
regression_weight_col=None,
remove_intercept=False):
"""Fits predictive ML (machine learning) models to continuous
response vector (given in ``y_col``)
and returns fitted model.
Parameters
----------
df : pd.DataFrame
A data frame with the response vector (y) and the feature columns
(``x_mat``).
model_formula_str : str
The prediction model formula string e.g. "y~x1+x2+x3*x4".
This is similar to R formulas.
See https://patsy.readthedocs.io/en/latest/formulas.html#how-formulas-work.
fit_algorithm : `str`, optional, default "linear"
The type of predictive model used in fitting.
See `~greykite.algo.common.ml_models.fit_model_via_design_matrix`
for available options and their parameters.
fit_algorithm_params : `dict` or None, optional, default None
Parameters passed to the requested fit_algorithm.
If None, uses the defaults in `~greykite.algo.common.ml_models.fit_model_via_design_matrix`.
y_col : str
The column name which has the value of interest to be forecasted
If the model_formula_str is not passed, ``y_col`` e.g. ["y"]
is used as the response vector column
pred_cols : List[str]
The names of the feature columns
If the ``model_formula_str`` is not passed, ``pred_cols`` e.g.
["x1", "x2", "x3"] is used as the design matrix columns
min_admissible_value : Optional[Union[int, float, double]]
the minimum admissible value for the ``predict`` function to return
max_admissible_value : Optional[Union[int, float, double]]
the maximum admissible value for the ``predict`` function to return
uncertainty_dict : `dict` or None
If passed as a dictionary an uncertainty model will be fit.
The items in the dictionary are:
``"uncertainty_method"`` : `str`
the title of the method
as of now only "simple_conditional_residuals" is implemented
which calculates CIs by using residuals
``"params"`` : `dict`
A dictionary of parameters needed for the ``uncertainty_method``
requested
normalize_method : `str` or None, default "zero_to_one"
If a string is provided, it will be used as the normalization method
in `~greykite.common.features.normalize.normalize_df`, passed via
the argument ``method``.
Available options are: "zero_to_one", "statistical", "minus_half_to_half", "zero_at_origin".
If None, no normalization will be performed.
See that function for more details.
regression_weight_col : `str` or None, default None
The column name for the weights to be used in weighted regression version
of applicable machine-learning models.
remove_intercept : `bool`, default False
Whether to remove explicit and implicit intercepts.
By default, `patsy` will make the design matrix always full rank.
It will always include an intercept term unless we specify "-1" or "+0".
However, if there are categorical variables, even we specify "-1" or "+0",
it will include an implicit intercept by adding all levels of a categorical
variable into the design matrix.
Sometimes we don't want this to happen.
Setting this parameter to True will remove both explicit and implicit intercepts.
Returns
-------
trained_model : `dict`
Trained model dictionary with keys:
- "y" : response values
- "x_design_info" : design matrix information
- "ml_model" : A trained model with predict method
- "uncertainty_model" : `dict`
The returned uncertainty_model dict from
`~greykite.algo.uncertainty.conditional.conf_interval.conf_interval`.
- "ml_model_summary": model summary
- "y_col" : response columns
- "x_mat ": design matrix
- "min_admissible_value" : minimum acceptable value
- "max_admissible_value" : maximum acceptable value
- "normalize_df_func" : normalization function
- "regression_weight_col" : regression weight column
- "alpha" : the regularization term from the linear / ridge regression.
Note that the OLS (ridge) estimator is ``inv(X.T @ X + alpha * np.eye(p)) @ X.T @ Y =: H @ Y``.
- "p_effective" : effective number of parameters.
In linear regressions, it is also equal to ``trace(X @ H)``, where H is defined above.
``X @ H`` is also called the hat matrix.
- "h_mat" : the H matrix (p by n) in linear regression estimator, as defined above.
Note that H is not necessarily of full-rank p even in ridge regression.
``H = inv(X.T @ X + alpha * np.eye(p)) @ X.T``.
- "sigma_scaler" : theoretical scaler of the estimated sigma.
Volatility model estimates sigma by taking the sample standard deviation, and
we need to scale it by ``np.sqrt((n_train - 1) / (n_train - p_effective))`` to obtain
an unbiased estimator.
- "x_mean" : column mean of ``x_mat`` as a row vector.
This is stored and used in ridge regression to compute the prediction intervals.
In other methods, it is set to `None`.
"""
# Builds model matrices.
res = design_mat_from_formula(
df=df,
model_formula_str=model_formula_str,
y_col=y_col,
pred_cols=pred_cols,
remove_intercept=remove_intercept
)
y = res["y"]
y_mean = np.mean(y)
y_std = np.std(y)
x_mat = res["x_mat"]
y_col = res["y_col"]
x_design_info = res["x_design_info"]
drop_intercept_col = res["drop_intercept_col"]
normalize_df_func = None
if normalize_method is not None:
if "Intercept" in (x_mat.columns):
cols = [col for col in list(x_mat.columns) if col != "Intercept"]
else:
cols = list(x_mat.columns)
normalize_info = normalize_df(
df=x_mat[cols],
method=normalize_method,
drop_degenerate_cols=False,
replace_zero_denom=True)
x_mat[cols] = normalize_info["normalized_df"]
x_mat = x_mat.fillna(value=0)
normalize_df_func = normalize_info["normalize_df_func"]
sample_weight = None
if regression_weight_col is not None:
if df[regression_weight_col].min() < 0:
raise ValueError(
"Weights can not be negative. "
f"The column {regression_weight_col} includes negative values.")
sample_weight = df[regression_weight_col]
# Prediction model generated by using all observed data.
ml_model = fit_model_via_design_matrix(
x_train=x_mat,
y_train=y,
fit_algorithm=fit_algorithm,
fit_algorithm_params=fit_algorithm_params,
sample_weight=sample_weight)
# Obtains `alpha`, `p_effective`, `h_mat` (H), and `sigma_scaler`.
# See comments below the variables.
# Read more at https://online.stat.psu.edu/stat508/lesson/5/5.1 or
# book: “Applied Regression Analysis” by Norman R. Draper, Harry Smith.
alpha = None
"""The regularization term from the linear / ridge regression.
Note that the OLS (ridge) estimator is ``inv(X.T @ X + alpha * np.eye(p)) @ X.T @ Y =: H @ Y``.
"""
p_effective = None
"""Effective number of parameters.
In linear regressions, it is also equal to ``trace(X @ H)``, where H is defined above.
``X @ H`` is also called the hat matrix.
"""
h_mat = None
"""The H matrix (p by n) in linear regression estimator, as defined above.
Note that H is not necessarily of full-rank p even in ridge regression.
``H = inv(X.T @ X + alpha * np.eye(p)) @ X.T``.
"""
sigma_scaler = None
"""Theoretical scaler of the estimated sigma.
Volatility model estimates sigma by taking the sample standard deviation, and
we need to scale it by ``np.sqrt((n_train - 1) / (n_train - p_effective))`` to obtain
an unbiased estimator.
"""
x_mean = None
"""Column mean of ``x_mat`` as a row vector.
This is stored and used in ridge regression to compute the prediction intervals.
In other methods, it is set to `None`.
"""
if fit_algorithm in ["ridge", "linear"]:
X = np.array(x_mat)
n_train, p = X.shape
# Extracts `alpha` from the fitted ML model.
# In linear regression, the rank of the design matrix is `p_effective`,
# but `RidgeCV` we need to manually derive it by taking the trace.
# Note that `RidgeCV` centers `X` and `Y` before fitting, hence we need to center `X` too.
if fit_algorithm == "ridge":
alpha = ml_model.alpha_
x_mean = X.mean(axis=0).reshape(1, -1)
X = X - x_mean
else:
alpha = 0
p_effective = np.linalg.matrix_rank(X)
# Computes `h_mat` (H, p x n).
try:
h_mat = get_h_mat(x_mat=X, alpha=alpha)
if fit_algorithm == "ridge":
# Computes the effective number of parameters.
# Note that `p_effective` is the trace of `X @ h_mat` plus 1 for intercept, however
# computing `trace(h_mat @ X)` is more efficient due to much faster matrix multiplication.
p_effective = round(np.trace(h_mat @ X), 6) + 1 # Avoids floating issues e.g. 1.9999999999999998.
except np.linalg.LinAlgError as e:
message = traceback.format_exc()
warning_msg = f"Error '{e}' occurred when computing `h_mat`, no variance scaling is done!\n" \
f"{message}"
log_message(warning_msg, LoggingLevelEnum.WARNING)
warnings.warn(warning_msg)
if p_effective is not None and round(p_effective) < n_train:
# Computes scaler on sigma estimate.
sigma_scaler = np.sqrt((n_train - 1) / (n_train - p_effective))
else:
warnings.warn(f"Zero degrees of freedom ({n_train}-{p_effective}) or the inverse solver failed. "
f"Likely caused by singular `X.T @ X + alpha * np.eye(p)`. "
f"Please check \"x_mat\", \"alpha\". "
f"`sigma_scaler` cannot be computed!")
# Uncertainty model is fitted if `uncertainty_dict` is passed.
uncertainty_model = None
if uncertainty_dict is not None:
uncertainty_method = uncertainty_dict["uncertainty_method"]
if uncertainty_method == "simple_conditional_residuals":
# Resets index to match behavior of predict before assignment.
new_df = df.reset_index(drop=True)
(new_x_mat,) = patsy.build_design_matrices(
[x_design_info],
data=new_df,
return_type="dataframe")
if drop_intercept_col is not None:
new_x_mat = new_x_mat.drop(columns=drop_intercept_col)
if normalize_df_func is not None:
if "Intercept" in list(x_mat.columns):
cols = [col for col in list(x_mat.columns) if col != "Intercept"]
else:
cols = list(x_mat.columns)
new_x_mat[cols] = normalize_df_func(new_x_mat[cols])
new_x_mat = new_x_mat.fillna(value=0)
new_df[f"{y_col}_pred"] = ml_model.predict(new_x_mat)
new_df[RESIDUAL_COL] = new_df[y_col] - new_df[f"{y_col}_pred"]
# Re-assigns some param defaults for function `conf_interval`
# with values best suited to this case.
conf_interval_params = {
"quantiles": [0.025, 0.975],
"sample_size_thresh": 10}
if uncertainty_dict["params"] is not None:
conf_interval_params.update(uncertainty_dict["params"])
uncertainty_model = conf_interval(
df=new_df,
distribution_col=RESIDUAL_COL,
offset_col=y_col,
sigma_scaler=sigma_scaler,
h_mat=h_mat,
x_mean=x_mean,
min_admissible_value=min_admissible_value,
max_admissible_value=max_admissible_value,
**conf_interval_params)
else:
raise NotImplementedError(
f"uncertainty method: {uncertainty_method} is not implemented")
# We get the model summary for a subset of models
# where summary is available (`statsmodels` module),
# or summary can be constructed (a subset of models from `sklearn`).
ml_model_summary = None
if "statsmodels" in fit_algorithm:
ml_model_summary = ml_model.summary()
elif hasattr(ml_model, "coef_"):
var_names = list(x_mat.columns)
coefs = ml_model.coef_
ml_model_summary = pd.DataFrame({
"variable": var_names,
"coef": coefs})
trained_model = {
"y": y,
"y_mean": y_mean,
"y_std": y_std,
"x_design_info": x_design_info,
"ml_model": ml_model,
"uncertainty_model": uncertainty_model,
"ml_model_summary": ml_model_summary,
"y_col": y_col,
"x_mat": x_mat,
"min_admissible_value": min_admissible_value,
"max_admissible_value": max_admissible_value,
"normalize_df_func": normalize_df_func,
"regression_weight_col": regression_weight_col,
"drop_intercept_col": drop_intercept_col,
"alpha": alpha,
"h_mat": h_mat,
"p_effective": p_effective,
"sigma_scaler": sigma_scaler,
"x_mean": x_mean}
if uncertainty_dict is None:
fitted_df = predict_ml(
fut_df=df,
trained_model=trained_model)["fut_df"]
else:
fitted_df = predict_ml_with_uncertainty(
fut_df=df,
trained_model=trained_model)["fut_df"]
trained_model["fitted_df"] = fitted_df
return trained_model
def predict_ml(
fut_df,
trained_model):
"""Returns predictions on new data using the machine-learning (ml) model
fitted via ``fit_ml_model``.
:param fut_df: `pd.DataFrame`
Input data for prediction.
Must have all columns used for training,
specified in ``model_formula_str`` or ``pred_cols``
:param trained_model: `dict`
A trained model returned from ``fit_ml_model``
:return: `dict`
A dictionary with following keys
- "fut_df": `pd.DataFrame`
Input data with ``y_col`` set to the predicted values
- "x_mat": `patsy.design_info.DesignMatrix`
Design matrix of the predictive model
"""
y_col = trained_model["y_col"]
ml_model = trained_model["ml_model"]
x_design_info = trained_model["x_design_info"]
drop_intercept_col = trained_model["drop_intercept_col"]
min_admissible_value = trained_model["min_admissible_value"]
max_admissible_value = trained_model["max_admissible_value"]
# reset indices to avoid issues when adding new cols
fut_df = fut_df.reset_index(drop=True)
(x_mat,) = patsy.build_design_matrices(
[x_design_info],
data=fut_df,
return_type="dataframe")
if drop_intercept_col is not None:
x_mat = x_mat.drop(columns=drop_intercept_col)
if trained_model["normalize_df_func"] is not None:
if "Intercept" in list(x_mat.columns):
cols = [col for col in list(x_mat.columns) if col != "Intercept"]
else:
cols = list(x_mat.columns)
x_mat[cols] = trained_model["normalize_df_func"](x_mat[cols])
x_mat = x_mat.fillna(value=0)
y_pred = ml_model.predict(x_mat)
if min_admissible_value is not None or max_admissible_value is not None:
y_pred = np.clip(
a=y_pred,
a_min=min_admissible_value,
a_max=max_admissible_value)
fut_df[y_col] = y_pred.tolist()
return {
"fut_df": fut_df,
"x_mat": x_mat}
R2_null_model_score = "R2_null_model_score"
def r2_null_model_score(
y_true,
y_pred,
y_pred_null=None,
y_train=None,
loss_func=mean_squared_error):
"""Calculates improvement in the loss function compared
to the predictions of a null model. Can be used to evaluate
model quality with respect to a simple baseline model.
The score is defined as::
R2_null_model_score = 1.0 - loss_func(y_true, y_pred) / loss_func(y_true, y_pred_null)
Parameters
----------
y_true : `list` [`float`] or `numpy.array`
Observed response (usually on a test set).
y_pred : `list` [`float`] or `numpy.array`
Model predictions (usually on a test set).
y_pred_null : `list` [`float`] or `numpy.array` or None
A baseline prediction model to compare against.
If None, derived from ``y_train`` or ``y_true``.
y_train : `list` [`float`] or `numpy.array` or None
Response values in the training data.
If ``y_pred_null`` is None, then ``y_pred_null`` is set to the mean of ``y_train``.
If ``y_train`` is also None, then ``y_pred_null`` is set to the mean of ``y_true``.
loss_func : callable, default `sklearn.metrics.mean_squared_error`
The error loss function with signature (true_values, predicted_values).
Returns
-------
r2_null_model : `float`
A value within (-\\infty, 1.0]. Higher scores are better.
Can be interpreted as the improvement in the loss function
compared to the predictions of the null model.
For example, a score of 0.74 means the loss is 74% lower
than for the null model.
Notes
-----
There is a connection between ``R2_null_model_score`` and ``R2``.
``R2_null_model_score`` can be interpreted as the additional improvement in the
coefficient of determination (i.e. ``R2``, see `sklearn.metrics.r2_score`) with
respect to a null model.
Under the default settings of this function, where ``loss_func`` is
mean squared error and ``y_pred_null`` is the average of
``y_true``, the scores are equivalent::
# simplified definition of R2_score, where SSE is sum of squared error
y_true_avg = np.repeat(np.average(y_true), y_true.shape[0])
R2_score := 1.0 - SSE(y_true, y_pred) / SSE(y_true, y_true_avg)
R2_score := 1.0 - MSE(y_true, y_pred) / VAR(y_true) # equivalent definition
r2_null_model_score(y_true, y_pred) == r2_score(y_true, y_pred)
``r2_score`` is 0 if simply predicting the mean (y_pred = y_true_avg).
If ``y_pred_null`` is passed, and if ``loss_func`` is mean squared error
and ``y_true`` has nonzero variance, this function measures how much "r2_score of the
predictions (``y_pred``)" closes the gap between "r2_score of the null model (``y_pred``)"
and the "r2_score of the best possible model (``y_true``)", which is 1.0::
R2_pred = r2_score(y_true, y_pred) # R2 of predictions
R2_null = r2_score(y_pred_null, y_pred) # R2 of null model
r2_null_model_score(y_true, y_pred, y_pred_null) == (R2_pred - R2_null) / (1.0 - R2_null)
When ``y_pred_null=y_true_avg``, ``R2_null`` is 0 and this reduces to the formula above.
Summary (for ``loss_func=mean_squared_error``):
- If ``R2_null>0`` (good null model), then ``R2_null_model_score < R2_score``
- If ``R2_null=0`` (uninformative null model), then ``R2_null_model_score = R2_score``
- If ``R2_null<0`` (poor null model), then ``R2_null_model_score > R2_score``
For other loss functions, ``r2_null_model_score`` has the same connection to pseudo R2.
"""
y_true, y_pred, y_train, y_pred_null = valid_elements_for_evaluation(
reference_arrays=[y_true],
arrays=[y_pred, y_train, y_pred_null],
reference_array_names="y_true",
drop_leading_only=False,
keep_inf=False)
r2_null_model = None
if len(y_true) > 0:
# determines null model
if y_pred_null is None and y_train is not None: # from training data
y_pred_null = np.repeat(y_train.mean(), len(y_true))
elif y_pred_null is None: # from test data
y_pred_null = np.repeat(y_true.mean(), len(y_true))
elif isinstance(y_pred_null, (float, int, np.float32)): # constant null model
y_pred_null = np.repeat(y_pred_null, len(y_true))
# otherwise, y_pred_null is an array, used directly
model_loss = loss_func(y_true, y_pred)
null_loss = loss_func(y_true, y_pred_null)
if null_loss > 0.0:
r2_null_model = 1.0 - (model_loss / null_loss)
return r2_null_model
def calc_pred_err(y_true, y_pred):
"""Calculates the basic error measures in
`~greykite.common.evaluation.EvaluationMetricEnum`
and returns them in a dictionary.
Parameters
----------
y_true : `list` [`float`] or `numpy.array`
Observed values.
y_pred : `list` [`float`] or `numpy.array`
Model predictions.
Returns
-------
error : `dict` [`str`, `float` or None]
Dictionary mapping
`~greykite.common.evaluation.EvaluationMetricEnum`
metric names to their values for the given ``y_true``
and ``y_pred``.
The dictionary is empty is there are no finite elements
in ``y_true``.
"""
y_true, y_pred = valid_elements_for_evaluation(
reference_arrays=[y_true],
arrays=[y_pred],
reference_array_names="y_true",
drop_leading_only=False,
keep_inf=False)
# The Silverkite Multistage model has NANs at the beginning
# when predicting on the training data.
# We only drop the leading NANs/infs from ``y_pred``,
# since they are not supposed to appear in the middle.
y_pred, y_true = valid_elements_for_evaluation(
reference_arrays=[y_pred],
arrays=[y_true],
reference_array_names="y_pred",
drop_leading_only=True,
keep_inf=True)
error = {}
if len(y_true) > 0:
for enum in EvaluationMetricEnum:
metric_name = enum.get_metric_name()
metric_func = enum.get_metric_func()
error.update({metric_name: metric_func(y_true, y_pred)})
return error
The provided code snippet includes necessary dependencies for implementing the `fit_ml_model_with_evaluation` function. Write a Python function `def fit_ml_model_with_evaluation( df, model_formula_str=None, y_col=None, pred_cols=None, fit_algorithm="linear", fit_algorithm_params=None, ind_train=None, ind_test=None, training_fraction=0.9, randomize_training=False, min_admissible_value=None, max_admissible_value=None, uncertainty_dict=None, normalize_method="zero_to_one", regression_weight_col=None, remove_intercept=False)` to solve the following problem:
Fits prediction models to continuous response vector (y) and report results. Parameters ---------- df : `pandas.DataFrame` A data frame with the response vector (y) and the feature columns (``x_mat``) model_formula_str : `str` The prediction model formula e.g. "y~x1+x2+x3*x4". This is similar to R language (https://www.r-project.org/) formulas. See https://patsy.readthedocs.io/en/latest/formulas.html#how-formulas-work. y_col : `str` The column name which has the value of interest to be forecasted If the ``model_formula_str`` is not passed, ``y_col`` e.g. ["y"] is used as the response vector column pred_cols : `list` [`str`] The names of the feature columns If the ``model_formula_str`` is not passed, ``pred_cols`` e.g. ["x1", "x2", "x3"] is used as the design matrix columns fit_algorithm : `str`, optional, default "linear" The type of predictive model used in fitting. See `~greykite.algo.common.ml_models.fit_model_via_design_matrix` for available options and their parameters. fit_algorithm_params : `dict` or None, optional, default None Parameters passed to the requested fit_algorithm. If None, uses the defaults in `~greykite.algo.common.ml_models.fit_model_via_design_matrix`. ind_train : `list` [`int`] The index (row number) of the training set ind_test : `list` [`int`] The index (row number) of the test set training_fraction : `float`, between 0.0 and 1.0 The fraction of data used for training This is invoked if ind_train and ind_test are not passed If this is also None or 1.0, then we skip testing and train on the entire dataset randomize_training : `bool` If True, then the training and the test sets will be randomized rather than in chronological order min_admissible_value : Optional[Union[int, float, double]] The minimum admissible value for the ``predict`` function to return max_admissible_value : Optional[Union[int, float, double]] The maximum admissible value for the ``predict`` function to return uncertainty_dict: `dict` or None If passed as a dictionary an uncertainty model will be fit. The items in the dictionary are: ``"uncertainty_method"`` : `str` the title of the method as of now only "simple_conditional_residuals" is implemented which calculates CIs by using residuals ``"params"`` : `dict` A dictionary of parameters needed for the ``uncertainty_method`` requested normalize_method : `str` or None, default "zero_to_one" If a string is provided, it will be used as the normalization method in `~greykite.common.features.normalize.normalize_df`, passed via the argument ``method``. Available options are: "zero_to_one", "statistical", "minus_half_to_half", "zero_at_origin". If None, no normalization will be performed. See that function for more details. regression_weight_col : `str` or None, default None The column name for the weights to be used in weighted regression version of applicable machine-learning models. remove_intercept : `bool`, default False Whether to remove explicit and implicit intercepts. By default, `patsy` will make the design matrix always full rank. It will always include an intercept term unless we specify "-1" or "+0". However, if there are categorical variables, even we specify "-1" or "+0", it will include an implicit intercept by adding all levels of a categorical variable into the design matrix. Sometimes we don't want this to happen. Setting this parameter to True will remove both explicit and implicit intercepts. Returns ------- trained_model : `dict` Trained model dictionary with the following keys. "ml_model": A trained model object "summary": Summary of the final model trained on all data "x_mat": Feature vectors matrix used for training of full data (rows of ``df`` with NA are dropped) "y": Response vector for training and testing (rows of ``df`` with NA are dropped). The index corresponds to selected rows in the input ``df``. "y_train": Response vector used for training "y_train_pred": Predicted values of ``y_train`` "training_evaluation": score function value of ``y_train`` and ``y_train_pred`` "y_test": Response vector used for testing "y_test_pred": Predicted values of ``y_test`` "test_evaluation": score function value of ``y_test`` and ``y_test_pred`` "uncertainty_model": `dict` The returned uncertainty_model dict from `~greykite.algo.uncertainty.conditional.conf_interval.conf_interval`. "plt_compare_test": plot function to compare ``y_test`` and ``y_test_pred``, "plt_pred": plot function to compare ``y_train``, ``y_train_pred``, ``y_test`` and ``y_test_pred``.
Here is the function:
def fit_ml_model_with_evaluation(
df,
model_formula_str=None,
y_col=None,
pred_cols=None,
fit_algorithm="linear",
fit_algorithm_params=None,
ind_train=None,
ind_test=None,
training_fraction=0.9,
randomize_training=False,
min_admissible_value=None,
max_admissible_value=None,
uncertainty_dict=None,
normalize_method="zero_to_one",
regression_weight_col=None,
remove_intercept=False):
"""Fits prediction models to continuous response vector (y)
and report results.
Parameters
----------
df : `pandas.DataFrame`
A data frame with the response vector (y) and the feature columns (``x_mat``)
model_formula_str : `str`
The prediction model formula e.g. "y~x1+x2+x3*x4".
This is similar to R language (https://www.r-project.org/) formulas.
See https://patsy.readthedocs.io/en/latest/formulas.html#how-formulas-work.
y_col : `str`
The column name which has the value of interest to be forecasted
If the ``model_formula_str`` is not passed, ``y_col`` e.g. ["y"] is used as the response
vector column
pred_cols : `list` [`str`]
The names of the feature columns
If the ``model_formula_str`` is not passed, ``pred_cols`` e.g. ["x1", "x2", "x3"]
is used as the design matrix columns
fit_algorithm : `str`, optional, default "linear"
The type of predictive model used in fitting.
See `~greykite.algo.common.ml_models.fit_model_via_design_matrix`
for available options and their parameters.
fit_algorithm_params : `dict` or None, optional, default None
Parameters passed to the requested fit_algorithm.
If None, uses the defaults in `~greykite.algo.common.ml_models.fit_model_via_design_matrix`.
ind_train : `list` [`int`]
The index (row number) of the training set
ind_test : `list` [`int`]
The index (row number) of the test set
training_fraction : `float`, between 0.0 and 1.0
The fraction of data used for training
This is invoked if ind_train and ind_test are not passed
If this is also None or 1.0, then we skip testing
and train on the entire dataset
randomize_training : `bool`
If True, then the training and the test sets will be randomized
rather than in chronological order
min_admissible_value : Optional[Union[int, float, double]]
The minimum admissible value for the ``predict`` function to return
max_admissible_value : Optional[Union[int, float, double]]
The maximum admissible value for the ``predict`` function to return
uncertainty_dict: `dict` or None
If passed as a dictionary an uncertainty model will be fit.
The items in the dictionary are:
``"uncertainty_method"`` : `str`
the title of the method
as of now only "simple_conditional_residuals" is implemented
which calculates CIs by using residuals
``"params"`` : `dict`
A dictionary of parameters needed for the ``uncertainty_method``
requested
normalize_method : `str` or None, default "zero_to_one"
If a string is provided, it will be used as the normalization method
in `~greykite.common.features.normalize.normalize_df`, passed via
the argument ``method``.
Available options are: "zero_to_one", "statistical", "minus_half_to_half", "zero_at_origin".
If None, no normalization will be performed.
See that function for more details.
regression_weight_col : `str` or None, default None
The column name for the weights to be used in weighted regression version
of applicable machine-learning models.
remove_intercept : `bool`, default False
Whether to remove explicit and implicit intercepts.
By default, `patsy` will make the design matrix always full rank.
It will always include an intercept term unless we specify "-1" or "+0".
However, if there are categorical variables, even we specify "-1" or "+0",
it will include an implicit intercept by adding all levels of a categorical
variable into the design matrix.
Sometimes we don't want this to happen.
Setting this parameter to True will remove both explicit and implicit intercepts.
Returns
-------
trained_model : `dict`
Trained model dictionary with the following keys.
"ml_model": A trained model object
"summary": Summary of the final model trained on all data
"x_mat": Feature vectors matrix used for training of full data (rows of ``df`` with NA are dropped)
"y": Response vector for training and testing (rows of ``df`` with NA are dropped).
The index corresponds to selected rows in the input ``df``.
"y_train": Response vector used for training
"y_train_pred": Predicted values of ``y_train``
"training_evaluation": score function value of ``y_train`` and ``y_train_pred``
"y_test": Response vector used for testing
"y_test_pred": Predicted values of ``y_test``
"test_evaluation": score function value of ``y_test`` and ``y_test_pred``
"uncertainty_model": `dict`
The returned uncertainty_model dict from
`~greykite.algo.uncertainty.conditional.conf_interval.conf_interval`.
"plt_compare_test": plot function to compare ``y_test`` and ``y_test_pred``,
"plt_pred": plot function to compare
``y_train``, ``y_train_pred``, ``y_test`` and ``y_test_pred``.
"""
# to avoid pandas unnecessary warnings due to chain assignment
pd.options.mode.chained_assignment = None
# dropping NAs
if df.isnull().values.any():
nrows_original = df.shape[0]
df = df.dropna(subset=df.columns) # preserves index
nrows = df.shape[0]
warnings.warn(
f"The data frame included {nrows_original-nrows} row(s) with NAs which were removed for model fitting.",
UserWarning)
if nrows <= 2:
raise ValueError(
f"Model training requires at least 3 observations, but the dataframe passed "
f"to training has {nrows} rows after removing NAs."
f"Sometimes this can be caused by unnecessary columns in your training data "
f"which contain NAs. Make sure to remove unnecessary columns from data before "
f"passing it to the function.")
# an internal function for fitting model
# this is wrapped into a function since we can do evaluations
trained_model = fit_ml_model(
df=df,
model_formula_str=model_formula_str,
fit_algorithm=fit_algorithm,
fit_algorithm_params=fit_algorithm_params,
y_col=y_col,
pred_cols=pred_cols,
min_admissible_value=min_admissible_value,
max_admissible_value=max_admissible_value,
uncertainty_dict=uncertainty_dict,
normalize_method=normalize_method,
regression_weight_col=regression_weight_col,
remove_intercept=remove_intercept)
# we store the obtained ``y_col`` from the function in a new variable (``y_col_final``)
# this is done since the input y_col could be None
# in which case we extract ``y_col`` from the formula (``model_formula_str``)
y_col_final = trained_model["y_col"]
# determining what should be the training and test sets
n = len(df)
skip_test = False
if ind_train is not None and ind_test is not None:
if max(ind_train) >= min(ind_test):
raise Exception("Test set indices should start after training set indices.")
elif max(ind_test) >= n:
warnings.warn(
"Testing set indices exceed the size of the dataset."
"Setting max index of the Test set "
"equal to the max index of the dataset.")
ind_test = [x for x in ind_test if x < n]
elif ind_train is None and training_fraction is not None and training_fraction < 1.0:
k = round(n * training_fraction)
k = int(k)
ind_train = range(k)
if randomize_training:
ind_train = random.sample(range(n), k)
ind_train = np.sort(ind_train)
ind_test = list(set(range(n)) - set(ind_train))
ind_test = np.sort(ind_test)
else:
ind_train = range(n)
ind_test = []
skip_test = True
df_train = df.iloc[ind_train]
df_test = df.iloc[ind_test]
y_train = df_train[y_col_final]
y_test = df_test[y_col_final]
if skip_test:
y_test_pred = None
test_evaluation = None
plt_compare_test = None
y_train_pred = predict_ml(
fut_df=df,
trained_model=trained_model,
)["fut_df"][y_col_final].tolist()
def plt_pred():
plt.plot(ind_train, y_train, label="full data", alpha=0.4)
plt.plot(ind_train, y_train_pred, label="fit", alpha=0.4)
plt.xlabel("index")
plt.ylabel("value")
plt.title("fit on the whole dataset")
plt.legend()
else:
# validation: fit with df_train only and predict with df_test
# first remove responses from df_test
df_test[y_col_final] = None
trained_model_tr = fit_ml_model(
df=df_train,
model_formula_str=model_formula_str,
fit_algorithm=fit_algorithm,
y_col=y_col,
pred_cols=pred_cols,
min_admissible_value=min_admissible_value,
max_admissible_value=max_admissible_value,
uncertainty_dict=uncertainty_dict,
normalize_method=normalize_method,
regression_weight_col=regression_weight_col,
remove_intercept=remove_intercept)
y_train_pred = predict_ml(
fut_df=df_train,
trained_model=trained_model_tr)["fut_df"][y_col_final].tolist()
y_test_pred = predict_ml(
fut_df=df_test,
trained_model=trained_model_tr)["fut_df"][y_col_final].tolist()
test_evaluation = calc_pred_err(
y_true=y_test,
y_pred=y_test_pred)
test_evaluation[R2_null_model_score] = r2_null_model_score(
y_true=y_test,
y_pred=y_test_pred,
y_pred_null=y_train.mean(),
y_train=None)
def plt_compare_test():
plt.scatter(y_test, y_test_pred, color="red", alpha=0.05)
plt.xlabel("observed")
plt.ylabel("predicted")
plt.title("test set")
def plt_pred():
plt.plot(ind_train, y_train, label="train", alpha=0.4)
plt.plot(ind_train, y_train_pred, label="fit", alpha=0.4)
plt.plot(ind_test, y_test, label="observed test set", alpha=0.4)
plt.plot(ind_test, y_test_pred, label="predicted test set", alpha=0.4)
plt.xlabel("index")
plt.ylabel("value")
plt.title("training and test fits")
plt.legend()
training_evaluation = calc_pred_err(
y_true=y_train,
y_pred=y_train_pred)
training_evaluation[R2_null_model_score] = r2_null_model_score(
y_true=y_train,
y_pred=y_train_pred,
y_pred_null=y_train.mean(),
y_train=None)
trained_model["summary"] = None
trained_model["y"] = df[y_col_final]
trained_model["y_train"] = y_train
trained_model["y_train_pred"] = y_train_pred
trained_model["training_evaluation"] = training_evaluation
trained_model["y_test"] = y_test
trained_model["y_test_pred"] = y_test_pred
trained_model["test_evaluation"] = test_evaluation
trained_model["plt_compare_test"] = plt_compare_test
trained_model["plt_pred"] = plt_pred
return trained_model | Fits prediction models to continuous response vector (y) and report results. Parameters ---------- df : `pandas.DataFrame` A data frame with the response vector (y) and the feature columns (``x_mat``) model_formula_str : `str` The prediction model formula e.g. "y~x1+x2+x3*x4". This is similar to R language (https://www.r-project.org/) formulas. See https://patsy.readthedocs.io/en/latest/formulas.html#how-formulas-work. y_col : `str` The column name which has the value of interest to be forecasted If the ``model_formula_str`` is not passed, ``y_col`` e.g. ["y"] is used as the response vector column pred_cols : `list` [`str`] The names of the feature columns If the ``model_formula_str`` is not passed, ``pred_cols`` e.g. ["x1", "x2", "x3"] is used as the design matrix columns fit_algorithm : `str`, optional, default "linear" The type of predictive model used in fitting. See `~greykite.algo.common.ml_models.fit_model_via_design_matrix` for available options and their parameters. fit_algorithm_params : `dict` or None, optional, default None Parameters passed to the requested fit_algorithm. If None, uses the defaults in `~greykite.algo.common.ml_models.fit_model_via_design_matrix`. ind_train : `list` [`int`] The index (row number) of the training set ind_test : `list` [`int`] The index (row number) of the test set training_fraction : `float`, between 0.0 and 1.0 The fraction of data used for training This is invoked if ind_train and ind_test are not passed If this is also None or 1.0, then we skip testing and train on the entire dataset randomize_training : `bool` If True, then the training and the test sets will be randomized rather than in chronological order min_admissible_value : Optional[Union[int, float, double]] The minimum admissible value for the ``predict`` function to return max_admissible_value : Optional[Union[int, float, double]] The maximum admissible value for the ``predict`` function to return uncertainty_dict: `dict` or None If passed as a dictionary an uncertainty model will be fit. The items in the dictionary are: ``"uncertainty_method"`` : `str` the title of the method as of now only "simple_conditional_residuals" is implemented which calculates CIs by using residuals ``"params"`` : `dict` A dictionary of parameters needed for the ``uncertainty_method`` requested normalize_method : `str` or None, default "zero_to_one" If a string is provided, it will be used as the normalization method in `~greykite.common.features.normalize.normalize_df`, passed via the argument ``method``. Available options are: "zero_to_one", "statistical", "minus_half_to_half", "zero_at_origin". If None, no normalization will be performed. See that function for more details. regression_weight_col : `str` or None, default None The column name for the weights to be used in weighted regression version of applicable machine-learning models. remove_intercept : `bool`, default False Whether to remove explicit and implicit intercepts. By default, `patsy` will make the design matrix always full rank. It will always include an intercept term unless we specify "-1" or "+0". However, if there are categorical variables, even we specify "-1" or "+0", it will include an implicit intercept by adding all levels of a categorical variable into the design matrix. Sometimes we don't want this to happen. Setting this parameter to True will remove both explicit and implicit intercepts. Returns ------- trained_model : `dict` Trained model dictionary with the following keys. "ml_model": A trained model object "summary": Summary of the final model trained on all data "x_mat": Feature vectors matrix used for training of full data (rows of ``df`` with NA are dropped) "y": Response vector for training and testing (rows of ``df`` with NA are dropped). The index corresponds to selected rows in the input ``df``. "y_train": Response vector used for training "y_train_pred": Predicted values of ``y_train`` "training_evaluation": score function value of ``y_train`` and ``y_train_pred`` "y_test": Response vector used for testing "y_test_pred": Predicted values of ``y_test`` "test_evaluation": score function value of ``y_test`` and ``y_test_pred`` "uncertainty_model": `dict` The returned uncertainty_model dict from `~greykite.algo.uncertainty.conditional.conf_interval.conf_interval`. "plt_compare_test": plot function to compare ``y_test`` and ``y_test_pred``, "plt_pred": plot function to compare ``y_train``, ``y_train_pred``, ``y_test`` and ``y_test_pred``. |
167,396 | import random
import re
import traceback
import warnings
from typing import Dict
from typing import List
from typing import Optional
import matplotlib
import numpy as np
import pandas as pd
import patsy
import scipy
import statsmodels.api as sm
from pandas.plotting import register_matplotlib_converters
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import ElasticNetCV
from sklearn.linear_model import LarsCV
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LassoLarsCV
from sklearn.linear_model import RidgeCV
from sklearn.linear_model import SGDRegressor
from greykite.algo.common.l1_quantile_regression import QuantileRegression
from greykite.algo.uncertainty.conditional.conf_interval import conf_interval
from greykite.algo.uncertainty.conditional.conf_interval import predict_ci
from greykite.common.constants import RESIDUAL_COL
from greykite.common.constants import R2_null_model_score
from greykite.common.evaluation import calc_pred_err
from greykite.common.evaluation import r2_null_model_score
from greykite.common.features.normalize import normalize_df
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.common.python_utils import group_strs_with_regex_patterns
from greykite.common.viz.timeseries_plotting import plot_multivariate
import matplotlib.pyplot as plt
def group_strs_with_regex_patterns(
strings,
regex_patterns):
"""Given a list/tuple of strings (``strings``), it partitions it into various groups (sub-lists) as
specified in a set of patterns given in ``regex_patterns``. Note that the order
of patterns matter as patterns will be consumed sequentially and if two patterns
overlap, the one appearing first will get the string assigned to its group.
Also note that the result will be a partition (``str_groups``) without overlap
and any remaining element not satisfying any pattern will be returned in ``remainder``.
Parameters
----------
strings : `list` [`str`] or `tuple` [`str`]
A list/tuple of strings which is to be partitioned into various groups
regex_patterns : `list` [`str`]
A list of strings each being a regex.
Returns
-------
result : `dict`
A dictionary with following items:
- "str_groups": `list` [`list` [`str`]]
A list of list of strings each corresponding to the patterns given in
``regex_patterns``. Note that some of these groups might be empty
lists if that pattern is not satisfied by any regex pattern, or a
regex pattern appearing before has already consumed all such strings.
-"remainder": `list` [`str`]
The remaining elements in ``strings`` which do not satisfy any of the
patterns given in ``regex_patterns``. This list can be empty.
"""
strings_list = list(strings)
str_groups = []
for regex_pattern in regex_patterns:
group = [x for x in strings_list if bool(re.match(regex_pattern, x))]
str_groups.append(group)
strings_list = [x for x in strings_list if x not in group]
return {"str_groups": str_groups, "remainder": strings_list}
def plot_multivariate(
df,
x_col,
y_col_style_dict="plotly",
default_color="rgba(0, 145, 202, 1.0)",
xlabel=None,
ylabel=cst.VALUE_COL,
title=None,
showlegend=True):
"""Plots one or more lines against the same x-axis values.
Parameters
----------
df : `pandas.DataFrame`
Data frame with ``x_col`` and columns named by the keys in ``y_col_style_dict``.
x_col: `str`
Which column to plot on the x-axis.
y_col_style_dict: `dict` [`str`, `dict` or None] or "plotly" or "auto" or "auto-fill", default "plotly"
The column(s) to plot on the y-axis, and how to style them.
If a dictionary:
- key : `str`
column name in ``df``
- value : `dict` or None
Optional styling options, passed as kwargs to `go.Scatter`.
If None, uses the default: line labeled by the column name.
See reference page for `plotly.graph_objects.Scatter` for options
(e.g. color, mode, width/size, opacity).
https://plotly.com/python/reference/#scatter.
If a string, plots all columns in ``df`` besides ``x_col`` against ``x_col``:
- "plotly": plot lines with default plotly styling
- "auto": plot lines with color ``default_color``, sorted by value (ascending)
- "auto-fill": plot lines with color ``default_color``, sorted by value (ascending), and fills between lines
default_color: `str`, default "rgba(0, 145, 202, 1.0)" (blue)
Default line color when ``y_col_style_dict`` is one of "auto", "auto-fill".
xlabel : `str` or None, default None
x-axis label. If None, default is ``x_col``.
ylabel : `str` or None, default ``VALUE_COL``
y-axis label
title : `str` or None, default None
Plot title. If None, default is based on axis labels.
showlegend : `bool`, default True
Whether to show the legend.
Returns
-------
fig : `plotly.graph_objects.Figure`
Interactive plotly graph of one or more columns
in ``df`` against ``x_col``.
See `~greykite.common.viz.timeseries_plotting.plot_forecast_vs_actual`
return value for how to plot the figure and add customization.
"""
if xlabel is None:
xlabel = x_col
if title is None and ylabel is not None:
title = f"{ylabel} vs {xlabel}"
auto_style = {"line": {"color": default_color}}
if y_col_style_dict == "plotly":
# Uses plotly default style
y_col_style_dict = {col: None for col in df.columns if col != x_col}
elif y_col_style_dict in ["auto", "auto-fill"]:
# Columns ordered from low to high
means = df.drop(columns=x_col).mean()
column_order = list(means.sort_values().index)
if y_col_style_dict == "auto":
# Lines with color `default_color`
y_col_style_dict = {col: auto_style for col in column_order}
elif y_col_style_dict == "auto-fill":
# Lines with color `default_color`, with fill between lines
y_col_style_dict = {column_order[0]: auto_style}
y_col_style_dict.update({
col: {
"line": {"color": default_color},
"fill": "tonexty"
} for col in column_order[1:]
})
data = []
default_style = dict(mode="lines")
for column, style_dict in y_col_style_dict.items():
# By default, column name in ``df`` is used to label the line
default_col_style = update_dictionary(default_style, overwrite_dict={"name": column})
# User can overwrite any of the default values, or remove them by setting key value to None
style_dict = update_dictionary(default_col_style, overwrite_dict=style_dict)
line = go.Scatter(
x=df[x_col],
y=df[column],
**style_dict)
data.append(line)
layout = go.Layout(
xaxis=dict(title=xlabel),
yaxis=dict(title=ylabel),
title=title,
title_x=0.5,
showlegend=showlegend,
legend={'traceorder': 'reversed'} # Matches the order of ``y_col_style_dict`` (bottom to top)
)
fig = go.Figure(data=data, layout=layout)
return fig
The provided code snippet includes necessary dependencies for implementing the `breakdown_regression_based_prediction` function. Write a Python function `def breakdown_regression_based_prediction( trained_model, x_mat, grouping_regex_patterns_dict, remainder_group_name="OTHER", center_components=False, denominator=None, index_values=None, index_col="index_col", plt_title="prediction breakdown")` to solve the following problem:
Given a regression based ML model (``ml_model``) and a design matrix (``x_mat``), and a string based grouping rule (``grouping_regex_patterns_dict``) for the design matrix columnns, constructs a dataframe with columns corresponding to the weighted (according to ML model regression coefficient) sum of the columns in each group. Note that if a variable/column is already picked in a step, it will be taken out from the columns list and will not appear in next groups. Parameters ---------- trained_model : `dict` A trained machine-learning model which includes items: - ml_model : `sklearn.base.BaseEstimator` sklearn ML estimator/model of various form. We require this object to have ``.coef_`` and ``.intercept`` attributes. - y_mean : `float` Observed mean of the response - y_std : `float` Observed standard deviation of the response x_mat :`pandas.DataFrame` Design matrix of the regression model grouping_regex_patterns_dict : `dict` {`str`: `str`} A dictionary with group names as keys and regexes as values. This dictinary is used to partition the columns into various groups remainder_group_name : `str`, default "OTHER" In case some columns are left and not assigned to any groups, a group with this name will be added to breakdown dataframe and includes the weighted some of the remaining columns. center_components : `bool`, default False It determines if components should be centered at their mean and the mean be added to the intercept. More concretely, if a componet is "x" then it will be mapped to "x - mean(x)"; and "mean(x)" will be added to the intercept so that the sum of the components remains the same. denominator : `str`, default None If not None, it will specify a way to divide the components. There are two options implemented: - "abs_y_mean" : `float` The absolute value of the observed mean of the response - "y_std" : `float` The standard deviation of the observed response This will be useful if we want to make the components scale free. Dividing by the absolute mean value of the response, is particularly useful to understand how much impact each component has for an average response. index_values : `list`, default None The values added as index which can of any types that can be used for plotting the x axis in plotly eg `int` or `datetime`. This is useful for plotting or if later this data to be joined with other data. For example in forecasting context timestamps can be added. index_col : `str`, default "index_col" The name of the added column to breakdown data to keep track of index plt_title : `str`, default "prediction breakdown" The title of generated plot Returns ------- result : `dict` A dictionary with the following keys. - "breakdown_df" : `pandas.DataFrame` A dataframe which includes the sums for each group / component - "breakdown_df_with_index_col" : `pandas.DataFrame` Same as ``breakdown_df`` with an added column to keep track of index - "breakdown_fig" : `plotly.graph_objs._figure.Figure` plotly plot overlaying various components - "column_grouping_result" : `dict` A dictionary which includes information for the generated groups. See `~greykite.common.python_utils.group_strs_with_regex_patterns` for more details.
Here is the function:
def breakdown_regression_based_prediction(
trained_model,
x_mat,
grouping_regex_patterns_dict,
remainder_group_name="OTHER",
center_components=False,
denominator=None,
index_values=None,
index_col="index_col",
plt_title="prediction breakdown"):
"""Given a regression based ML model (``ml_model``) and a design matrix
(``x_mat``), and a string based grouping rule (``grouping_regex_patterns_dict``)
for the design matrix columnns, constructs a dataframe with columns corresponding
to the weighted (according to ML model regression coefficient) sum of the columns in each group.
Note that if a variable/column is already picked in a step, it will be taken
out from the columns list and will not appear in next groups.
Parameters
----------
trained_model : `dict`
A trained machine-learning model which includes items:
- ml_model : `sklearn.base.BaseEstimator`
sklearn ML estimator/model of various form.
We require this object to have ``.coef_`` and ``.intercept`` attributes.
- y_mean : `float`
Observed mean of the response
- y_std : `float`
Observed standard deviation of the response
x_mat :`pandas.DataFrame`
Design matrix of the regression model
grouping_regex_patterns_dict : `dict` {`str`: `str`}
A dictionary with group names as keys and regexes as values.
This dictinary is used to partition the columns into various groups
remainder_group_name : `str`, default "OTHER"
In case some columns are left and not assigned to any groups, a group
with this name will be added to breakdown dataframe and includes the
weighted some of the remaining columns.
center_components : `bool`, default False
It determines if components should be centered at their mean and the mean
be added to the intercept. More concretely, if a componet is "x" then it will
be mapped to "x - mean(x)"; and "mean(x)" will be added to the intercept so
that the sum of the components remains the same.
denominator : `str`, default None
If not None, it will specify a way to divide the components. There are
two options implemented:
- "abs_y_mean" : `float`
The absolute value of the observed mean of the response
- "y_std" : `float`
The standard deviation of the observed response
This will be useful if we want to make the components scale free.
Dividing by the absolute mean value of the response, is particularly
useful to understand how much impact each component has for an average
response.
index_values : `list`, default None
The values added as index which can of any types that can be used for
plotting the x axis in plotly eg `int` or `datetime`.
This is useful for plotting or if later this data to be joined
with other data. For example in forecasting context timestamps can be added.
index_col : `str`, default "index_col"
The name of the added column to breakdown data to keep track of index
plt_title : `str`, default "prediction breakdown"
The title of generated plot
Returns
-------
result : `dict`
A dictionary with the following keys.
- "breakdown_df" : `pandas.DataFrame`
A dataframe which includes the sums for each group / component
- "breakdown_df_with_index_col" : `pandas.DataFrame`
Same as ``breakdown_df`` with an added column to keep track of index
- "breakdown_fig" : `plotly.graph_objs._figure.Figure`
plotly plot overlaying various components
- "column_grouping_result" : `dict`
A dictionary which includes information for the generated groups.
See `~greykite.common.python_utils.group_strs_with_regex_patterns`
for more details.
"""
if index_values is not None:
assert len(index_values) == len(x_mat), "the number of indices must match the size of data"
ml_model = trained_model["ml_model"]
# The dataframe which includes the group sums
breakdown_df = pd.DataFrame()
ml_model_coef = ml_model.coef_
intercept = ml_model.intercept_
x_mat_weighted = x_mat * ml_model_coef
data_len = len(x_mat)
cols = list(x_mat.columns)
breakdown_df["Intercept"] = np.repeat(intercept, data_len)
if "Intercept" in cols:
breakdown_df["Intercept"] += x_mat_weighted["Intercept"]
# If Intercept appear in the columns, we remove it
# Note that this column was utilized and added to intercept
if "Intercept" in cols:
del x_mat_weighted["Intercept"]
cols.remove("Intercept")
regex_patterns = list(grouping_regex_patterns_dict.values())
group_names = list(grouping_regex_patterns_dict.keys())
column_grouping_result = group_strs_with_regex_patterns(
strings=cols,
regex_patterns=regex_patterns)
col_groups = column_grouping_result["str_groups"]
remainder = column_grouping_result["remainder"]
assert len(col_groups) == len(grouping_regex_patterns_dict)
for i, group_name in enumerate(group_names):
group_elements = col_groups[i]
if len(group_elements) != 0:
breakdown_df[group_name] = x_mat_weighted[group_elements].sum(axis=1)
else:
breakdown_df[group_name] = 0.0
if len(remainder) != 0:
breakdown_df[remainder_group_name] = x_mat_weighted[remainder].sum(axis=1)
group_names.append(remainder_group_name)
if center_components:
for col in group_names:
col_mean = breakdown_df[col].mean()
breakdown_df[col] += -col_mean
breakdown_df["Intercept"] += col_mean
if denominator == "abs_y_mean":
d = abs(trained_model["y_mean"])
elif denominator == "y_std":
d = trained_model["y_std"]
elif denominator is None:
d = 1.0
else:
raise NotImplementedError(f"{denominator} is not an admissable denominator")
for col in group_names + ["Intercept"]:
breakdown_df[col] /= d
if index_values is None:
index_values = range(len(breakdown_df))
breakdown_df_with_index_col = breakdown_df.copy()
breakdown_df_with_index_col[index_col] = index_values
breakdown_fig = plot_multivariate(
df=breakdown_df_with_index_col,
x_col=index_col,
title=plt_title,
ylabel="component")
return {
"breakdown_df": breakdown_df,
"breakdown_df_with_index_col": breakdown_df_with_index_col,
"breakdown_fig": breakdown_fig,
"column_grouping_result": column_grouping_result
} | Given a regression based ML model (``ml_model``) and a design matrix (``x_mat``), and a string based grouping rule (``grouping_regex_patterns_dict``) for the design matrix columnns, constructs a dataframe with columns corresponding to the weighted (according to ML model regression coefficient) sum of the columns in each group. Note that if a variable/column is already picked in a step, it will be taken out from the columns list and will not appear in next groups. Parameters ---------- trained_model : `dict` A trained machine-learning model which includes items: - ml_model : `sklearn.base.BaseEstimator` sklearn ML estimator/model of various form. We require this object to have ``.coef_`` and ``.intercept`` attributes. - y_mean : `float` Observed mean of the response - y_std : `float` Observed standard deviation of the response x_mat :`pandas.DataFrame` Design matrix of the regression model grouping_regex_patterns_dict : `dict` {`str`: `str`} A dictionary with group names as keys and regexes as values. This dictinary is used to partition the columns into various groups remainder_group_name : `str`, default "OTHER" In case some columns are left and not assigned to any groups, a group with this name will be added to breakdown dataframe and includes the weighted some of the remaining columns. center_components : `bool`, default False It determines if components should be centered at their mean and the mean be added to the intercept. More concretely, if a componet is "x" then it will be mapped to "x - mean(x)"; and "mean(x)" will be added to the intercept so that the sum of the components remains the same. denominator : `str`, default None If not None, it will specify a way to divide the components. There are two options implemented: - "abs_y_mean" : `float` The absolute value of the observed mean of the response - "y_std" : `float` The standard deviation of the observed response This will be useful if we want to make the components scale free. Dividing by the absolute mean value of the response, is particularly useful to understand how much impact each component has for an average response. index_values : `list`, default None The values added as index which can of any types that can be used for plotting the x axis in plotly eg `int` or `datetime`. This is useful for plotting or if later this data to be joined with other data. For example in forecasting context timestamps can be added. index_col : `str`, default "index_col" The name of the added column to breakdown data to keep track of index plt_title : `str`, default "prediction breakdown" The title of generated plot Returns ------- result : `dict` A dictionary with the following keys. - "breakdown_df" : `pandas.DataFrame` A dataframe which includes the sums for each group / component - "breakdown_df_with_index_col" : `pandas.DataFrame` Same as ``breakdown_df`` with an added column to keep track of index - "breakdown_fig" : `plotly.graph_objs._figure.Figure` plotly plot overlaying various components - "column_grouping_result" : `dict` A dictionary which includes information for the generated groups. See `~greykite.common.python_utils.group_strs_with_regex_patterns` for more details. |
167,397 | import re
import warnings
from datetime import datetime
from enum import Enum
from typing import List
from typing import Optional
import pandas as pd
from greykite.common.constants import LEVELSHIFT_COL_PREFIX_SHORT
from greykite.common.viz.timeseries_plotting import plot_multivariate
The provided code snippet includes necessary dependencies for implementing the `find_min_max_of_block` function. Write a Python function `def find_min_max_of_block(indices: List[int])` to solve the following problem:
Given a list of indices, with some of them being consecutive, find the start and end of each block. Indices are considered to be in the same block if they are consecutive numbers. For example, [1, 4, 5, 6, 12, 14, 15] will give [[1, 1], [4, 6], [12, 12], [14, 15]]. Parameters ---------- indices: `list` List of indices in ascending order. Example: [1, 4, 5, 6, 12, 14, 15]. Returns ---------- index_blocks : `list` List of list with start and end index of each block. Example: [[1, 1], [4, 6], [12, 12], [14, 15]].
Here is the function:
def find_min_max_of_block(indices: List[int]):
"""Given a list of indices, with some of them being consecutive,
find the start and end of each block.
Indices are considered to be in the same block if they are consecutive numbers.
For example, [1, 4, 5, 6, 12, 14, 15] will give [[1, 1], [4, 6], [12, 12], [14, 15]].
Parameters
----------
indices: `list`
List of indices in ascending order.
Example: [1, 4, 5, 6, 12, 14, 15].
Returns
----------
index_blocks : `list`
List of list with start and end index of each block.
Example: [[1, 1], [4, 6], [12, 12], [14, 15]].
"""
if not indices:
return []
block_start_i = 0
index_blocks = []
for i in range(1, len(indices)):
if indices[i] - indices[i - 1] != 1:
index_blocks.append((indices[block_start_i], indices[i - 1]))
block_start_i = i
index_blocks.append((indices[block_start_i], indices[-1]))
return index_blocks | Given a list of indices, with some of them being consecutive, find the start and end of each block. Indices are considered to be in the same block if they are consecutive numbers. For example, [1, 4, 5, 6, 12, 14, 15] will give [[1, 1], [4, 6], [12, 12], [14, 15]]. Parameters ---------- indices: `list` List of indices in ascending order. Example: [1, 4, 5, 6, 12, 14, 15]. Returns ---------- index_blocks : `list` List of list with start and end index of each block. Example: [[1, 1], [4, 6], [12, 12], [14, 15]]. |
167,398 | import warnings
from datetime import timedelta
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from pandas.plotting import register_matplotlib_converters
from pandas.tseries.frequencies import to_offset
from sklearn.linear_model import Lasso
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
from greykite.common.constants import CHANGEPOINT_COL_PREFIX
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import add_time_features_df
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import fourier_series_multi_fcn
from greykite.common.features.timeseries_features import get_changepoint_dates_from_changepoints_dict
from greykite.common.features.timeseries_features import get_changepoint_features
from greykite.common.features.timeseries_features import get_changepoint_features_and_values_from_config
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
from greykite.common.python_utils import get_pattern_cols
from greykite.common.python_utils import unique_elements_in_list
def get_pattern_cols(cols, pos_pattern=None, neg_pattern=None):
"""Get columns names from a list that matches ``pos_pattern``,
but does not match ``neg_pattern``.
If a column name matches both ``pos_pattern`` and ``neg_pattern``, it is excluded.
Parameters
----------
cols : `List` ['str']
Usually column names of a DataFrame.
pos_pattern : regular expression
If column name matches this pattern, it is included in the output.
neg_pattern : regular expression
If column name matches this pattern, it is excluded from the output.
Returns
-------
pattern_cols : `List` ['str']
List of column names that match the pattern.
"""
if pos_pattern is None:
pos_pattern_cols = []
else:
pos_regex = re.compile(pos_pattern)
pos_pattern_cols = [col for col in cols if pos_regex.findall(col)]
if neg_pattern is None:
neg_pattern_cols = []
else:
neg_regex = re.compile(neg_pattern)
neg_pattern_cols = [col for col in cols if neg_regex.findall(col)]
pattern_cols = [col for col in cols if
col in pos_pattern_cols and col not in neg_pattern_cols]
return pattern_cols
The provided code snippet includes necessary dependencies for implementing the `compute_fitted_components` function. Write a Python function `def compute_fitted_components( x, coef, regex, include_intercept, intercept=None)` to solve the following problem:
Computes the fitted values with selected regressors indicated by ``regex`` Parameters ---------- x : `pandas.DataFrame` The design matrix df with conventional column names. coef : `numpy.array` Estimated coefficients. regex : regular expression Pattern of the names of the columns to be used. include_intercept : bool Whether to include intercept. intercept : `float` The estimated intercept, must be provided if ``include_intercept`` == True. Returns ------- result: `pandas.Series` The estimated component from selected regressors.
Here is the function:
def compute_fitted_components(
x,
coef,
regex,
include_intercept,
intercept=None):
"""Computes the fitted values with selected regressors indicated by ``regex``
Parameters
----------
x : `pandas.DataFrame`
The design matrix df with conventional column names.
coef : `numpy.array`
Estimated coefficients.
regex : regular expression
Pattern of the names of the columns to be used.
include_intercept : bool
Whether to include intercept.
intercept : `float`
The estimated intercept, must be provided if ``include_intercept`` == True.
Returns
-------
result: `pandas.Series`
The estimated component from selected regressors.
"""
if include_intercept and intercept is None:
raise ValueError("``intercept`` must be provided when ``include_intercept`` is True.")
columns = list(x.columns)
selected_columns = get_pattern_cols(columns, regex)
selected_columns_idx = [columns.index(col) for col in selected_columns]
selected_coef = coef[selected_columns_idx]
component = x[selected_columns].dot(selected_coef)
if include_intercept:
component += intercept
return component | Computes the fitted values with selected regressors indicated by ``regex`` Parameters ---------- x : `pandas.DataFrame` The design matrix df with conventional column names. coef : `numpy.array` Estimated coefficients. regex : regular expression Pattern of the names of the columns to be used. include_intercept : bool Whether to include intercept. intercept : `float` The estimated intercept, must be provided if ``include_intercept`` == True. Returns ------- result: `pandas.Series` The estimated component from selected regressors. |
167,399 | import warnings
from datetime import timedelta
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from pandas.plotting import register_matplotlib_converters
from pandas.tseries.frequencies import to_offset
from sklearn.linear_model import Lasso
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
from greykite.common.constants import CHANGEPOINT_COL_PREFIX
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import add_time_features_df
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import fourier_series_multi_fcn
from greykite.common.features.timeseries_features import get_changepoint_dates_from_changepoints_dict
from greykite.common.features.timeseries_features import get_changepoint_features
from greykite.common.features.timeseries_features import get_changepoint_features_and_values_from_config
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
from greykite.common.python_utils import get_pattern_cols
from greykite.common.python_utils import unique_elements_in_list
The provided code snippet includes necessary dependencies for implementing the `plot_change` function. Write a Python function `def plot_change( observation=None, adaptive_lasso_estimate=None, trend_change=None, trend_estimate=None, year_seasonality_estimate=None, seasonality_change=None, seasonality_estimate=None, title=None, xaxis="Dates", yaxis="Values")` to solve the following problem:
Makes a plot of the observed data and estimated components, as well as detected changes The function currently allows five different components to be plotted together. Specifically, ``trend_change`` can be plotted with at least one of ``observations``, ``trend_estimate`` and ``adaptive_lasso_estimate`` is provided. Parameters ---------- observation : `pandas.Series` with time index or `None` The observed values, leave None to omit it from plot. adaptive_lasso_estimate : `pandas.Series` with time index or `None` The adaptive lasso estimated trend, leave None to omit it from plot. trend_change : `pandas.Series` with time index or `None` The detected trend change points, leave None to omit it from plot. Plotted as vertical lines if observation is provided, otherwise plotted as markers. trend_estimate : `pandas.Series` with time index or `None` The estimated trend, leave None to omit it from plot. year_seasonality_estimate : `pandas.Series` with time index or `None` The estimated yearly seasonality, leave None to omit it from plot. seasonality_change : `list` or `dict` or `None` The detected seasonality change points, leave None to omit it from plot. If the type is `list`, it should be a list of change points of all components. If the type is `dict`, its keys should be the name of components, and values should be the corresponding list of change points. seasonality_estimate : `pandas.Series` or `None` The estimated seasonality, leave None to omit it from plot. title : `str` or `None` Plot title. xaxis : `str` Plot x axis label. yaxis : `str` Plot y axis label. Returns ------- fig : `plotly.graph_objects.Figure` The plotted plotly object, can be shown with `fig.show()`.
Here is the function:
def plot_change(
observation=None,
adaptive_lasso_estimate=None,
trend_change=None,
trend_estimate=None,
year_seasonality_estimate=None,
seasonality_change=None,
seasonality_estimate=None,
title=None,
xaxis="Dates",
yaxis="Values"):
"""Makes a plot of the observed data and estimated components, as well as detected changes
The function currently allows five different components to be plotted together. Specifically,
``trend_change`` can be plotted with at least one of ``observations``, ``trend_estimate`` and
``adaptive_lasso_estimate`` is provided.
Parameters
----------
observation : `pandas.Series` with time index or `None`
The observed values, leave None to omit it from plot.
adaptive_lasso_estimate : `pandas.Series` with time index or `None`
The adaptive lasso estimated trend, leave None to omit it from plot.
trend_change : `pandas.Series` with time index or `None`
The detected trend change points, leave None to omit it from plot.
Plotted as vertical lines if observation is provided, otherwise plotted as markers.
trend_estimate : `pandas.Series` with time index or `None`
The estimated trend, leave None to omit it from plot.
year_seasonality_estimate : `pandas.Series` with time index or `None`
The estimated yearly seasonality, leave None to omit it from plot.
seasonality_change : `list` or `dict` or `None`
The detected seasonality change points, leave None to omit it from plot.
If the type is `list`, it should be a list of change points of all components.
If the type is `dict`, its keys should be the name of components, and values
should be the corresponding list of change points.
seasonality_estimate : `pandas.Series` or `None`
The estimated seasonality, leave None to omit it from plot.
title : `str` or `None`
Plot title.
xaxis : `str`
Plot x axis label.
yaxis : `str`
Plot y axis label.
Returns
-------
fig : `plotly.graph_objects.Figure`
The plotted plotly object, can be shown with `fig.show()`.
"""
if title is None:
if trend_change is None and seasonality_change is None:
title = "Timeseries Plot"
elif trend_change is None:
title = "Timeseries Plot with detected seasonality change points"
elif seasonality_change is None:
title = "Timeseries Plot with detected trend change points"
else:
title = "Timeseries Plot with detected trend and seasonality change points"
fig = go.Figure()
# shows the true observation
if observation is not None:
fig.add_trace(
go.Scatter(
x=observation.index,
y=observation,
name="true",
mode="lines",
line=dict(color="#42A5F5"), # blue 400
opacity=1)
)
# shows the seasonality estimate
if seasonality_estimate is not None:
fig.add_trace(
go.Scatter(
name="seasonality+trend",
mode="lines",
x=seasonality_estimate.index,
y=seasonality_estimate,
line=dict(color="#B2FF59"), # light green A200
opacity=0.7,
showlegend=True)
)
# shows the adaptive lasso estimated trend
if adaptive_lasso_estimate is not None:
fig.add_trace(
go.Scatter(
name="adaptive lasso estimated trend",
mode="lines",
x=adaptive_lasso_estimate.index,
y=adaptive_lasso_estimate,
line=dict(color="#FFA726"), # orange 400
opacity=1,
showlegend=True)
)
# shows the detected trend change points
# shown as vertical lines if ``observation`` is provided, otherwise as markers
if trend_change is not None:
if observation is not None or seasonality_estimate is not None:
if observation is not None:
min_y = min(0, observation.min())
max_y = max(0, observation.max())
else:
min_y = min(0, seasonality_estimate.min())
max_y = max(0, seasonality_estimate.max())
for i, cp in enumerate(trend_change):
showlegend = (i == 0)
fig.add_trace(
go.Scatter(
name="trend change point",
mode="lines",
x=[pd.to_datetime(cp), pd.to_datetime(cp)],
y=[min_y, max_y],
line=go.scatter.Line(
color="#F44336", # red 500
width=1.5,
dash="dash"
),
opacity=1,
showlegend=showlegend,
legendgroup="trend"
)
)
elif trend_estimate is not None or adaptive_lasso_estimate is not None:
trend = trend_estimate if trend_estimate is not None else adaptive_lasso_estimate
for cp in trend_change:
value = trend[cp]
fig.add_trace(
go.Scatter(
name="trend change points",
mode="markers",
x=[pd.to_datetime(cp)],
y=[value],
marker=dict(
color="#F44336", # red 500
size=15,
line=dict(
color="Black",
width=1.5
)),
opacity=0.2,
showlegend=False
)
)
else:
warnings.warn("trend_change is not shown. Must provide observations, trend_estimate, "
"adaptive_lasso_estimate or seasonality_estimate to plot trend_change.")
return None
# shows the detected seasonality change points
if seasonality_change is not None:
if observation is not None or seasonality_estimate is not None:
if observation is not None:
min_y = min(0, observation.min())
max_y = max(0, observation.max())
else:
min_y = min(0, seasonality_estimate.min())
max_y = max(0, seasonality_estimate.max())
if isinstance(seasonality_change, list):
for i, cp in enumerate(seasonality_change):
showlegend = (i == 0)
fig.add_trace(
go.Scatter(
name="seasonality change point",
mode="lines",
x=[pd.to_datetime(cp), pd.to_datetime(cp)],
y=[min_y, max_y],
line=go.scatter.Line(
color="#1E88E5", # blue 600
width=1.5,
dash="dash"
),
opacity=1,
showlegend=showlegend,
legendgroup="seasonality"
)
)
elif isinstance(seasonality_change, dict):
colors = ["#2196F3", "#0D47A1"] # [blue 500, blue 900]
dashes = ["dash", "dot", "dashdot", None]
types = [(color, dash) for color in colors for dash in dashes]
quota = len(types)
for i, (key, changepoints) in enumerate(seasonality_change.items()):
if quota == 0:
warnings.warn("Only the first 8 components with detected change points"
"are plotted.")
break
if changepoints:
for j, cp in enumerate(changepoints):
showlegend = (j == 0)
fig.add_trace(
go.Scatter(
name="seasonality change point " + key,
mode="lines",
x=[pd.to_datetime(cp), pd.to_datetime(cp)],
y=[min_y, max_y],
line=go.scatter.Line(
color=types[i][0],
width=1.5,
dash=types[i][1]
),
opacity=1,
showlegend=showlegend,
legendgroup=key
)
)
quota -= 1
else:
raise ValueError("seasonality_change must be either list or dict.")
else:
warnings.warn("seasonality_change is not shown. Must provide observations or"
" seasonality_estimate to plot seasonality_change.")
# shows the estimated trend
if trend_estimate is not None:
fig.add_trace(
go.Scatter(
name="trend",
mode="lines",
x=trend_estimate.index,
y=trend_estimate,
line=dict(
color="#FFFF00", # yellow A200
width=2),
opacity=1,
showlegend=True)
)
# shows the estimated yearly seasonality
if year_seasonality_estimate is not None:
fig.add_trace(
go.Scatter(
name="yearly seasonality",
mode="lines",
x=year_seasonality_estimate.index,
y=year_seasonality_estimate,
line=dict(color="#BF360C"), # deep orange 900
opacity=0.6,
showlegend=True)
)
fig.update_layout(dict(
xaxis=dict(title=xaxis),
yaxis=dict(title=yaxis),
title=title,
title_x=0.5
))
return fig | Makes a plot of the observed data and estimated components, as well as detected changes The function currently allows five different components to be plotted together. Specifically, ``trend_change`` can be plotted with at least one of ``observations``, ``trend_estimate`` and ``adaptive_lasso_estimate`` is provided. Parameters ---------- observation : `pandas.Series` with time index or `None` The observed values, leave None to omit it from plot. adaptive_lasso_estimate : `pandas.Series` with time index or `None` The adaptive lasso estimated trend, leave None to omit it from plot. trend_change : `pandas.Series` with time index or `None` The detected trend change points, leave None to omit it from plot. Plotted as vertical lines if observation is provided, otherwise plotted as markers. trend_estimate : `pandas.Series` with time index or `None` The estimated trend, leave None to omit it from plot. year_seasonality_estimate : `pandas.Series` with time index or `None` The estimated yearly seasonality, leave None to omit it from plot. seasonality_change : `list` or `dict` or `None` The detected seasonality change points, leave None to omit it from plot. If the type is `list`, it should be a list of change points of all components. If the type is `dict`, its keys should be the name of components, and values should be the corresponding list of change points. seasonality_estimate : `pandas.Series` or `None` The estimated seasonality, leave None to omit it from plot. title : `str` or `None` Plot title. xaxis : `str` Plot x axis label. yaxis : `str` Plot y axis label. Returns ------- fig : `plotly.graph_objects.Figure` The plotted plotly object, can be shown with `fig.show()`. |
167,400 | import warnings
from datetime import timedelta
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from pandas.plotting import register_matplotlib_converters
from pandas.tseries.frequencies import to_offset
from sklearn.linear_model import Lasso
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
from greykite.common.constants import CHANGEPOINT_COL_PREFIX
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import add_time_features_df
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import fourier_series_multi_fcn
from greykite.common.features.timeseries_features import get_changepoint_dates_from_changepoints_dict
from greykite.common.features.timeseries_features import get_changepoint_features
from greykite.common.features.timeseries_features import get_changepoint_features_and_values_from_config
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
from greykite.common.python_utils import get_pattern_cols
from greykite.common.python_utils import unique_elements_in_list
def adaptive_lasso_cv(x,
y,
initial_coef,
regularization_strength=None,
max_min_ratio=1e6):
"""Performs the adaptive lasso cross-validation.
Algorithm is based on a transformation of `sklearn.linear_model.LassoCV()`.
If initial_coef is not available, a lasso estimator is computed.
Parameters
----------
x : `numpy.array`
The design matrix.
y : `numpy.array`
The response vector.
initial_coef : `str` in ["ridge", "lasso", "old"] or `numpy.array`
How to obtain the initial estimator. If a `str` is provided, the corresponding model is trained
to obtain the initial estimator. If a `numpy.array` is provided, it is used as the initial
estimator.
regularization_strength : `float` in [0, 1] or `None`
The regularization strength for change points. Greater values imply fewer change points.
0 indicates all change points, and 1 indicates no change point.
If `None`, cross-validation will be used to select tuning parameter,
else the value will be used as the tuning parameters.
max_min_ratio : `float`
defines the min lambda by defining the ratio of lambda_max / lambda_min.
`sklearn.linear_model.lasso_path` uses 1e3, but 1e6 seems better here.
Returns
-------
intercept : `float`
The estimated intercept.
coef : `numpy.array`
The estimated coefficients.
"""
if regularization_strength is not None and (regularization_strength < 0 or regularization_strength > 1):
raise ValueError("regularization_strength must be between 0.0 and 1.0.")
if regularization_strength == 0:
# regularization_strength == 0 implies linear regression
model = LinearRegression().fit(x, y)
return model.intercept_, model.coef_
if regularization_strength == 1:
# regularization_strength == 1 implies no change point selected
# handle this case here separately for algorithm convergence and rounding concerns
intercept = y.mean()
coef = np.zeros(x.shape[1])
return intercept, coef
if type(initial_coef) == str:
model = {"lasso": LassoCV(), "ols": LinearRegression(), "ridge": RidgeCV()}[initial_coef]
model.fit(x, y)
initial_coef = model.coef_
else:
assert x.shape[1] == len(initial_coef), (
"the number of columns in x should equal to the length of weights"
f"but got {x.shape[1]} and {len(initial_coef)}."
)
weights = np.where(initial_coef != 0, 1 / abs(initial_coef), 1e16) # 1e16 is big enough for most cases.
x_t = x / weights
if regularization_strength is None:
model = LassoCV().fit(x_t, y)
else:
# finds the minimum lambda that corresponds to no selection, formula derived from KKT condition.
# this is the max lambda we need to consider
max_lam = max(abs(np.matmul(x_t.T, y - y.mean()))) / x.shape[0]
# the lambda we choose is ``regularization_strength``th log-percentile of [lambda_min, lambda_max]
lam = 10 ** (np.log10(max_lam / max_min_ratio) + np.log10(max_min_ratio) * regularization_strength)
model = Lasso(alpha=lam).fit(x_t, y)
intercept = model.intercept_
coef = model.coef_ / weights
return intercept, coef
def find_neighbor_changepoints(cp_idx, min_index_distance=2):
"""Finds neighbor change points given their indices
For example
x = [1, 2, 3, 7, 8, 10, 15, 20]
The return with `min_index_distance`=2 is
result = [[1, 2, 3], [7, 8], [10], [15], [20]]
The return with `min_index_distance`=3 is
result = [[1, 2, 3], [7, 8, 10], [15], [20]]
Parameters
----------
cp_idx : `list`
A list of the change point indices.
min_index_distance : `int`
The minimal index distance to be considered separate
Returns
-------
neighbor_cps : `list`
A list of neighbor change points lists. Single change points are put in a list as well.
"""
if min_index_distance <= 0:
raise ValueError("`min_index_distance` must be positive.")
if len(cp_idx) <= 1:
return [cp_idx]
# check if sorted
is_sorted = True
for i in range(1, len(cp_idx)):
if cp_idx[i] < cp_idx[i - 1]:
is_sorted = False
break
# sort if `cp_idx` is not sorted
if not is_sorted:
cp_idx.sort()
warnings.warn("The given `cp_idx` is not sorted. It has been sorted.")
neighbor_cps = []
i = 0
while i < len(cp_idx):
neighbor_cps.append([])
neighbor_cps[-1].append(cp_idx[i])
i += 1
while i < len(cp_idx) and cp_idx[i] < neighbor_cps[-1][-1] + min_index_distance:
neighbor_cps[-1].append(cp_idx[i])
i += 1
return neighbor_cps
def filter_changepoints(cp_blocks, coef, min_index_distance):
"""Filters change points that are too close.
Given the ``cp_block`` from the output of ``find_neighbor_changepoints`` and the corresponding
coefficients, finds the list of change points, one in each neighborhood list.
The algorithm keeps all individual change points. If more than one change points are in the
same block, with the maximum distance less than ``min_index_distance``, then only the one
with the maximum absolute coefficient is retained. If more than one change points are in the
same block, and the block covers a few ``max_index_distance`` length, then a greedy method
is used to select change points. The principle is that, we perform one pass of the change
points, within each ``max_index_distance``, we select one change point with the maximum
absolute coefficients. If the next change point is with in ``max_index_distance`` of the
previous one, the previous one is dropped. A back-tracking is also used to fill possible
change points when a change point is dropped.
Parameters
----------
cp_blocks : `list`
A list of list of change points, output from ``find_neighbor_changepoints``.
coef : `numpy.array`
The estimated coefficients for all potential change points.
Note: ``coef`` is a 1-D array, which is the output from regression model.
min_index_distance : `int`
The minimum index distance between two selected change points.
Note that this parameter is added to safe guard the extreme cases: if all
significant change points are included in the same block, with insignificant
change points connecting them, then we do not want to drop all and just leave
one change points. With this parameter, we can leave more than one change point
from each block, and keep them at least ``min_index_distance`` away.
Returns
-------
changepoint_indices : `list`
The indices of selected change points.
"""
if min_index_distance <= 0:
raise ValueError("`min_index_distance` is the minimum distance between change point"
"indices to consider them separate, and must be positive.")
if min_index_distance == 1:
return [cp for block in cp_blocks for cp in block]
coef = coef.ravel() # makes sure ``coef`` is 1-D array
coef = coef[[i for block in cp_blocks for i in block]] # Only needs the coefs that correspond to selected cp's.
selected_changepoints = []
if cp_blocks == [[]]:
return []
for i, block in enumerate(cp_blocks):
if len(block) == 1:
# if only one cp in a block, leaves it
selected_changepoints.append(block[0])
else:
# needs coefs to decide
coef_start = sum([len(block) for block in cp_blocks[:i]])
coef_block = coef[coef_start: coef_start + len(block)]
if block[-1] - block[0] < min_index_distance:
# If block max distance is less than `min_index_distance`,
# only one cp can be selected,
# select the one with the greatest absolute coef
selected_changepoints.append(block[abs(coef_block).argmax()])
else:
# For longer blocks, the change points with the maximum
# absolute coefficients are selected, while keeping the
# distance beyond ``min_index_distance``.
# This prevents dropping too many change points in a long block.
block_cps = []
start = block[0]
last_coef = 0
while start <= block[-1]:
# gets the current ``min_index_distance`` sized sub-block of cps and coefs
current_sub_block = [cp for cp in block if start <= cp < start + min_index_distance]
if not current_sub_block:
start += min_index_distance
continue
current_cp = current_sub_block[
abs(coef_block[[block.index(cp) for cp in current_sub_block]]).argmax()]
current_cp_idx = block.index(current_cp)
current_coef = coef_block[current_cp_idx]
# the first change point, doesn't have to look back
if start == block[0]:
block_cps.append(current_cp)
else:
# check the distance from the last change point
# if distance is enough, we can fit the new change point
last_cp = block_cps[-1]
if current_cp - last_cp >= min_index_distance:
block_cps.append(current_cp)
# if the distance is not enough and the new cp has a greater absolute coef,
# we have to remove the previous one with less absolute coef
# however, we would like to see if another cp fits in between
elif abs(current_coef) > abs(last_coef):
# checks if an extra change point can fit between last_last_cp and current_cp
if len(block_cps) >= 2:
last_last_cp = block_cps[-2]
else:
# if no last_last_cp, there's not lower bound
last_last_cp = -min_index_distance
# gets the cps that can fit between last_last_cp and current_cp
back_fill_potential_cp = [
cp for cp in block if
last_last_cp + min_index_distance <= cp <= current_cp - min_index_distance]
if back_fill_potential_cp:
# if there is cp that can fit in between, gets the one with max absolute coef
potential_coef = coef[[block.index(cp) for cp in back_fill_potential_cp]]
back_fill_cp = back_fill_potential_cp[abs(potential_coef).argmax()]
# append the cp in between
block_cps.append(back_fill_cp)
# removes the last one and append the new one
block_cps.remove(last_cp)
block_cps.append(current_cp)
# updates last_coef for comparison
last_coef = current_coef
# search ahead
start += min_index_distance
selected_changepoints += block_cps
return selected_changepoints
The provided code snippet includes necessary dependencies for implementing the `get_trend_changes_from_adaptive_lasso` function. Write a Python function `def get_trend_changes_from_adaptive_lasso(x, y, changepoint_dates, initial_coef, min_index_distance=2, regularization_strength=None)` to solve the following problem:
Parses the adaptive lasso estimator to get change point dates. The functions calls ``adaptive_lasso_cv`` to selected potential trend change points. Then a filter is applied to eliminate change points that are too close. Specifically, in a set of close change points, the one with the largest absolute coefficient will be kept. Parameters ---------- x : `numpy.array` The design matrix. y : `numpy.array` The response vector. changepoint_dates : `pandas.Series` A pandas Series of all potential change point dates that were used to generate ``x``. initial_coef : `str` in ["ridge", "lasso", "old"] or `numpy.array' How to obtain the initial estimator. If a `str` is provided, the corresponding model is trained to obtain the initial estimator. If a `numpy.array` is provided, it is used as the initial estimator. min_index_distance : `int` The minimal index distance that is allowed between two change points. regularization_strength : `float` in [0, 1] or `None` The regularization power for change points. Greater values imply fewer change points. 0 indicates all change points, and 1 indicates no change point. If `None`, cross-validation will be used to select tuning parameter, else the value will be used as the tuning parameters. Returns ------- changepoints : `list` Detected trend change points. coefs : `list` Adaptive lasso estimated coefficients. First element is intercept, and second element is coefficients.
Here is the function:
def get_trend_changes_from_adaptive_lasso(x,
y,
changepoint_dates,
initial_coef,
min_index_distance=2,
regularization_strength=None):
"""Parses the adaptive lasso estimator to get change point dates.
The functions calls ``adaptive_lasso_cv`` to selected potential trend change points.
Then a filter is applied to eliminate change points that are too close.
Specifically, in a set of close change points, the one with the largest absolute
coefficient will be kept.
Parameters
----------
x : `numpy.array`
The design matrix.
y : `numpy.array`
The response vector.
changepoint_dates : `pandas.Series`
A pandas Series of all potential change point dates that were used to generate ``x``.
initial_coef : `str` in ["ridge", "lasso", "old"] or `numpy.array'
How to obtain the initial estimator. If a `str` is provided, the corresponding model is trained
to obtain the initial estimator. If a `numpy.array` is provided, it is used as the initial
estimator.
min_index_distance : `int`
The minimal index distance that is allowed between two change points.
regularization_strength : `float` in [0, 1] or `None`
The regularization power for change points. Greater values imply fewer change points.
0 indicates all change points, and 1 indicates no change point.
If `None`, cross-validation will be used to select tuning parameter,
else the value will be used as the tuning parameters.
Returns
-------
changepoints : `list`
Detected trend change points.
coefs : `list`
Adaptive lasso estimated coefficients.
First element is intercept, and second element is coefficients.
"""
intercept, coef = adaptive_lasso_cv(x, y, initial_coef, regularization_strength)
# x may contain yearly seasonality regressors, so we need i < len(changepoint_dates)
nonzero_idx = [i for i, val in enumerate(coef) if val != 0 and i < len(changepoint_dates)]
cp_blocks = find_neighbor_changepoints(
cp_idx=nonzero_idx,
min_index_distance=min_index_distance,
)
cp_idx = filter_changepoints(cp_blocks, coef, min_index_distance)
return changepoint_dates.iloc[cp_idx].tolist(), [intercept, coef] | Parses the adaptive lasso estimator to get change point dates. The functions calls ``adaptive_lasso_cv`` to selected potential trend change points. Then a filter is applied to eliminate change points that are too close. Specifically, in a set of close change points, the one with the largest absolute coefficient will be kept. Parameters ---------- x : `numpy.array` The design matrix. y : `numpy.array` The response vector. changepoint_dates : `pandas.Series` A pandas Series of all potential change point dates that were used to generate ``x``. initial_coef : `str` in ["ridge", "lasso", "old"] or `numpy.array' How to obtain the initial estimator. If a `str` is provided, the corresponding model is trained to obtain the initial estimator. If a `numpy.array` is provided, it is used as the initial estimator. min_index_distance : `int` The minimal index distance that is allowed between two change points. regularization_strength : `float` in [0, 1] or `None` The regularization power for change points. Greater values imply fewer change points. 0 indicates all change points, and 1 indicates no change point. If `None`, cross-validation will be used to select tuning parameter, else the value will be used as the tuning parameters. Returns ------- changepoints : `list` Detected trend change points. coefs : `list` Adaptive lasso estimated coefficients. First element is intercept, and second element is coefficients. |
167,401 | import warnings
from datetime import timedelta
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from pandas.plotting import register_matplotlib_converters
from pandas.tseries.frequencies import to_offset
from sklearn.linear_model import Lasso
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
from greykite.common.constants import CHANGEPOINT_COL_PREFIX
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import add_time_features_df
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import fourier_series_multi_fcn
from greykite.common.features.timeseries_features import get_changepoint_dates_from_changepoints_dict
from greykite.common.features.timeseries_features import get_changepoint_features
from greykite.common.features.timeseries_features import get_changepoint_features_and_values_from_config
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
from greykite.common.python_utils import get_pattern_cols
from greykite.common.python_utils import unique_elements_in_list
np.seterr(divide="ignore")
def check_freq_unit_at_most_day(freq, name):
"""Checks if the ``freq`` parameter passed to a function has unit at most "D"
Parameters
----------
freq : `DateOffset`, `Timedelta` or `str`
The parameter passed as ``freq``.
name : `str`
The name of the parameter ``freq``.
Returns
-------
None
Raises
------
ValueError
Because the input frequency has unit greater than "D".
"""
if (isinstance(freq, str) and
any(char in freq for char in ["W", "M", "Y"])):
raise ValueError(f"In {name}, the maximal unit is 'D', "
"i.e., you may use units no more than 'D' such as"
"'10D', '5H', '100T', '200S'. The reason is that 'W', 'M' "
"or higher has either cycles or indefinite number of days, "
"thus is not parsable by pandas as timedelta.")
The provided code snippet includes necessary dependencies for implementing the `compute_min_changepoint_index_distance` function. Write a Python function `def compute_min_changepoint_index_distance( df, time_col, n_changepoints, min_distance_between_changepoints)` to solve the following problem:
Computes the minimal index distance between two consecutive detected change points. Given a df, its time column, the number of change points that are evenly distributed, and the min_distance_between_changepoints in `DateOffset, Timedelta or str`, gets the min distance between change point indices. Parameters ---------- df : `pandas.DataFrame` The dataframe that has a time column. time_col : `str` The column name of time in ``df``. n_changepoints : `int` Number of change points that are uniformly placed over the time period. min_distance_between_changepoints : `DateOffset`, `Timedelta` or `str` The minimal distance that is allowed between two detected change points. Note: maximal unit is 'D', i.e., you may only use units no more than 'D' such as '10D', '5H', '100T', '200S'. The reason is that 'W', 'M' or higher has either cycles or indefinite number of days, thus is not parsable by pandas as timedelta. Returns ------- min_changepoint_index_distance : `int` The minimal index distance that is allowed between two detected change points.
Here is the function:
def compute_min_changepoint_index_distance(
df,
time_col,
n_changepoints,
min_distance_between_changepoints):
"""Computes the minimal index distance between two consecutive detected change points.
Given a df, its time column, the number of change points that are evenly distributed,
and the min_distance_between_changepoints in `DateOffset, Timedelta or str`, gets the
min distance between change point indices.
Parameters
----------
df : `pandas.DataFrame`
The dataframe that has a time column.
time_col : `str`
The column name of time in ``df``.
n_changepoints : `int`
Number of change points that are uniformly placed over the time period.
min_distance_between_changepoints : `DateOffset`, `Timedelta` or `str`
The minimal distance that is allowed between two detected change points.
Note: maximal unit is 'D', i.e., you may only use units no more than 'D' such as
'10D', '5H', '100T', '200S'. The reason is that 'W', 'M' or higher has either
cycles or indefinite number of days, thus is not parsable by pandas as timedelta.
Returns
-------
min_changepoint_index_distance : `int`
The minimal index distance that is allowed between two detected change points.
"""
if n_changepoints == 0:
return df.shape[0]
check_freq_unit_at_most_day(min_distance_between_changepoints, "min_distance_between_changepoints")
# `to_offset` function handles string frequency without numbers such as 'D' instead of '1D',
# so we use `to_offset` here rather than `to_timedelta`.
min_dist = to_offset(min_distance_between_changepoints)
# There are `n_changepoints` change points and 1 growth term, so there is `n_changepoints` gaps
# Therefore the following is divided by `n_changepoints`
try:
changepoint_dist = (df[time_col].iloc[-1] - df[time_col].iloc[0]) / n_changepoints
except TypeError:
changepoint_dist = (pd.to_datetime(df[time_col].iloc[-1]) - pd.to_datetime(df[time_col].iloc[0])) \
/ n_changepoints
return int(np.ceil(min_dist.delta.total_seconds() / changepoint_dist.total_seconds())) | Computes the minimal index distance between two consecutive detected change points. Given a df, its time column, the number of change points that are evenly distributed, and the min_distance_between_changepoints in `DateOffset, Timedelta or str`, gets the min distance between change point indices. Parameters ---------- df : `pandas.DataFrame` The dataframe that has a time column. time_col : `str` The column name of time in ``df``. n_changepoints : `int` Number of change points that are uniformly placed over the time period. min_distance_between_changepoints : `DateOffset`, `Timedelta` or `str` The minimal distance that is allowed between two detected change points. Note: maximal unit is 'D', i.e., you may only use units no more than 'D' such as '10D', '5H', '100T', '200S'. The reason is that 'W', 'M' or higher has either cycles or indefinite number of days, thus is not parsable by pandas as timedelta. Returns ------- min_changepoint_index_distance : `int` The minimal index distance that is allowed between two detected change points. |
167,402 | import warnings
from datetime import timedelta
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from pandas.plotting import register_matplotlib_converters
from pandas.tseries.frequencies import to_offset
from sklearn.linear_model import Lasso
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
from greykite.common.constants import CHANGEPOINT_COL_PREFIX
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import add_time_features_df
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import fourier_series_multi_fcn
from greykite.common.features.timeseries_features import get_changepoint_dates_from_changepoints_dict
from greykite.common.features.timeseries_features import get_changepoint_features
from greykite.common.features.timeseries_features import get_changepoint_features_and_values_from_config
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
from greykite.common.python_utils import get_pattern_cols
from greykite.common.python_utils import unique_elements_in_list
def adaptive_lasso_cv(x,
y,
initial_coef,
regularization_strength=None,
max_min_ratio=1e6):
"""Performs the adaptive lasso cross-validation.
Algorithm is based on a transformation of `sklearn.linear_model.LassoCV()`.
If initial_coef is not available, a lasso estimator is computed.
Parameters
----------
x : `numpy.array`
The design matrix.
y : `numpy.array`
The response vector.
initial_coef : `str` in ["ridge", "lasso", "old"] or `numpy.array`
How to obtain the initial estimator. If a `str` is provided, the corresponding model is trained
to obtain the initial estimator. If a `numpy.array` is provided, it is used as the initial
estimator.
regularization_strength : `float` in [0, 1] or `None`
The regularization strength for change points. Greater values imply fewer change points.
0 indicates all change points, and 1 indicates no change point.
If `None`, cross-validation will be used to select tuning parameter,
else the value will be used as the tuning parameters.
max_min_ratio : `float`
defines the min lambda by defining the ratio of lambda_max / lambda_min.
`sklearn.linear_model.lasso_path` uses 1e3, but 1e6 seems better here.
Returns
-------
intercept : `float`
The estimated intercept.
coef : `numpy.array`
The estimated coefficients.
"""
if regularization_strength is not None and (regularization_strength < 0 or regularization_strength > 1):
raise ValueError("regularization_strength must be between 0.0 and 1.0.")
if regularization_strength == 0:
# regularization_strength == 0 implies linear regression
model = LinearRegression().fit(x, y)
return model.intercept_, model.coef_
if regularization_strength == 1:
# regularization_strength == 1 implies no change point selected
# handle this case here separately for algorithm convergence and rounding concerns
intercept = y.mean()
coef = np.zeros(x.shape[1])
return intercept, coef
if type(initial_coef) == str:
model = {"lasso": LassoCV(), "ols": LinearRegression(), "ridge": RidgeCV()}[initial_coef]
model.fit(x, y)
initial_coef = model.coef_
else:
assert x.shape[1] == len(initial_coef), (
"the number of columns in x should equal to the length of weights"
f"but got {x.shape[1]} and {len(initial_coef)}."
)
weights = np.where(initial_coef != 0, 1 / abs(initial_coef), 1e16) # 1e16 is big enough for most cases.
x_t = x / weights
if regularization_strength is None:
model = LassoCV().fit(x_t, y)
else:
# finds the minimum lambda that corresponds to no selection, formula derived from KKT condition.
# this is the max lambda we need to consider
max_lam = max(abs(np.matmul(x_t.T, y - y.mean()))) / x.shape[0]
# the lambda we choose is ``regularization_strength``th log-percentile of [lambda_min, lambda_max]
lam = 10 ** (np.log10(max_lam / max_min_ratio) + np.log10(max_min_ratio) * regularization_strength)
model = Lasso(alpha=lam).fit(x_t, y)
intercept = model.intercept_
coef = model.coef_ / weights
return intercept, coef
def find_neighbor_changepoints(cp_idx, min_index_distance=2):
"""Finds neighbor change points given their indices
For example
x = [1, 2, 3, 7, 8, 10, 15, 20]
The return with `min_index_distance`=2 is
result = [[1, 2, 3], [7, 8], [10], [15], [20]]
The return with `min_index_distance`=3 is
result = [[1, 2, 3], [7, 8, 10], [15], [20]]
Parameters
----------
cp_idx : `list`
A list of the change point indices.
min_index_distance : `int`
The minimal index distance to be considered separate
Returns
-------
neighbor_cps : `list`
A list of neighbor change points lists. Single change points are put in a list as well.
"""
if min_index_distance <= 0:
raise ValueError("`min_index_distance` must be positive.")
if len(cp_idx) <= 1:
return [cp_idx]
# check if sorted
is_sorted = True
for i in range(1, len(cp_idx)):
if cp_idx[i] < cp_idx[i - 1]:
is_sorted = False
break
# sort if `cp_idx` is not sorted
if not is_sorted:
cp_idx.sort()
warnings.warn("The given `cp_idx` is not sorted. It has been sorted.")
neighbor_cps = []
i = 0
while i < len(cp_idx):
neighbor_cps.append([])
neighbor_cps[-1].append(cp_idx[i])
i += 1
while i < len(cp_idx) and cp_idx[i] < neighbor_cps[-1][-1] + min_index_distance:
neighbor_cps[-1].append(cp_idx[i])
i += 1
return neighbor_cps
def filter_changepoints(cp_blocks, coef, min_index_distance):
"""Filters change points that are too close.
Given the ``cp_block`` from the output of ``find_neighbor_changepoints`` and the corresponding
coefficients, finds the list of change points, one in each neighborhood list.
The algorithm keeps all individual change points. If more than one change points are in the
same block, with the maximum distance less than ``min_index_distance``, then only the one
with the maximum absolute coefficient is retained. If more than one change points are in the
same block, and the block covers a few ``max_index_distance`` length, then a greedy method
is used to select change points. The principle is that, we perform one pass of the change
points, within each ``max_index_distance``, we select one change point with the maximum
absolute coefficients. If the next change point is with in ``max_index_distance`` of the
previous one, the previous one is dropped. A back-tracking is also used to fill possible
change points when a change point is dropped.
Parameters
----------
cp_blocks : `list`
A list of list of change points, output from ``find_neighbor_changepoints``.
coef : `numpy.array`
The estimated coefficients for all potential change points.
Note: ``coef`` is a 1-D array, which is the output from regression model.
min_index_distance : `int`
The minimum index distance between two selected change points.
Note that this parameter is added to safe guard the extreme cases: if all
significant change points are included in the same block, with insignificant
change points connecting them, then we do not want to drop all and just leave
one change points. With this parameter, we can leave more than one change point
from each block, and keep them at least ``min_index_distance`` away.
Returns
-------
changepoint_indices : `list`
The indices of selected change points.
"""
if min_index_distance <= 0:
raise ValueError("`min_index_distance` is the minimum distance between change point"
"indices to consider them separate, and must be positive.")
if min_index_distance == 1:
return [cp for block in cp_blocks for cp in block]
coef = coef.ravel() # makes sure ``coef`` is 1-D array
coef = coef[[i for block in cp_blocks for i in block]] # Only needs the coefs that correspond to selected cp's.
selected_changepoints = []
if cp_blocks == [[]]:
return []
for i, block in enumerate(cp_blocks):
if len(block) == 1:
# if only one cp in a block, leaves it
selected_changepoints.append(block[0])
else:
# needs coefs to decide
coef_start = sum([len(block) for block in cp_blocks[:i]])
coef_block = coef[coef_start: coef_start + len(block)]
if block[-1] - block[0] < min_index_distance:
# If block max distance is less than `min_index_distance`,
# only one cp can be selected,
# select the one with the greatest absolute coef
selected_changepoints.append(block[abs(coef_block).argmax()])
else:
# For longer blocks, the change points with the maximum
# absolute coefficients are selected, while keeping the
# distance beyond ``min_index_distance``.
# This prevents dropping too many change points in a long block.
block_cps = []
start = block[0]
last_coef = 0
while start <= block[-1]:
# gets the current ``min_index_distance`` sized sub-block of cps and coefs
current_sub_block = [cp for cp in block if start <= cp < start + min_index_distance]
if not current_sub_block:
start += min_index_distance
continue
current_cp = current_sub_block[
abs(coef_block[[block.index(cp) for cp in current_sub_block]]).argmax()]
current_cp_idx = block.index(current_cp)
current_coef = coef_block[current_cp_idx]
# the first change point, doesn't have to look back
if start == block[0]:
block_cps.append(current_cp)
else:
# check the distance from the last change point
# if distance is enough, we can fit the new change point
last_cp = block_cps[-1]
if current_cp - last_cp >= min_index_distance:
block_cps.append(current_cp)
# if the distance is not enough and the new cp has a greater absolute coef,
# we have to remove the previous one with less absolute coef
# however, we would like to see if another cp fits in between
elif abs(current_coef) > abs(last_coef):
# checks if an extra change point can fit between last_last_cp and current_cp
if len(block_cps) >= 2:
last_last_cp = block_cps[-2]
else:
# if no last_last_cp, there's not lower bound
last_last_cp = -min_index_distance
# gets the cps that can fit between last_last_cp and current_cp
back_fill_potential_cp = [
cp for cp in block if
last_last_cp + min_index_distance <= cp <= current_cp - min_index_distance]
if back_fill_potential_cp:
# if there is cp that can fit in between, gets the one with max absolute coef
potential_coef = coef[[block.index(cp) for cp in back_fill_potential_cp]]
back_fill_cp = back_fill_potential_cp[abs(potential_coef).argmax()]
# append the cp in between
block_cps.append(back_fill_cp)
# removes the last one and append the new one
block_cps.remove(last_cp)
block_cps.append(current_cp)
# updates last_coef for comparison
last_coef = current_coef
# search ahead
start += min_index_distance
selected_changepoints += block_cps
return selected_changepoints
def get_changes_from_beta(
beta,
seasonality_components_df,
magnitude_only=False):
"""Gets the seasonality magnitude change arrays for each seasonality component from the
estimated regression coefficients.
In total there are::
{sum_{i=1}^{number of components}(2 * order of component i)} * {number of changepoints + 1}
coefficients in ``beta``, where the + 1 counts the overall seasonality. These coefficients
indicate the change in magnitude for each term in each component at each change point.
We can't work on these directly, since the values are positive or negative.
Two options are available to calcumated the change metric, controlled by the parameter
``magnitude_only``.
If ``magnitude_only`` == True, the cumulative sum is taken for every single cos or sin term
(from all components) along the change points. The results are the magnitudes for each cos
or sin term (from all components) at each change point. An L2 norm is taken over the cos and sin
terms' magnitudes within the same component at the same change point. Now for each component
at every change point, we have one L2 norm value that represents the magnitude (no longer
cos or sin level). Then the magnitude changes for the same component between consecutive
change points are computed. This option captures total magnitude changes only.
If ``magnitude_only`` == False, an L2 norm is taken over the cos or sin magnitude changes
in the same component directly. This option captures shape changes as well.
A dictionary is returned with keys equal to the component names, and values are the corresponding
arrays of changes.
Parameters
----------
beta : `np.array`
The estimated regression coefficients.
seasonality_components_df : `pandas.DataFrame`
The df to generate seasonality design matrix, which is compatible with
``seasonality_components_df`` in
`~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints`
magnitude_only : `bool`, default False
Set to True to compute the L2 norms on the seasonality magnitudes, and set to False to compute the
L2 norms on the seasonailty changes.
Returns
-------
seasonality_magnitude : `dict`
Keys are seasonality components, and values are the arrays of changes at each changepoint for the
components.
Examples
--------
# 1 change point, 2 seasonality components: "weekly" has order 1, and "yearly" has order 2.
# so (1 + 2) * 2 * (1 + 1) = 12 coefficients in total.
# the terms above are
# [(weekly_order + yearly_order) * 2_terms_sin_cos] * (overall_seasonality + num_changepoints)
>>> # the initial coefficients are [1, 1, 1, 1, 1, 1], and changes to [2, 0, 2, 2, 2, 0] at the change point
>>> # the change is [1, -1, 1, 1, 1, -1].
>>> beta = np.array([1, 1, 1, 1, 1, 1, # initial coefficients
... 1, -1, 1, 1, 1, -1]) # changes to [2, 0, 2, 2, 2, 0]
>>> seasonality_components_df = pd.DataFrame({
... "name": ["tow", "conti_year"],
... "period": [7.0, 1.0],
... "order": [1, 2],
... "seas_names": ["weekly", "yearly"]})
>>> result = get_changes_from_beta(beta, seasonality_components_df, True)
>>> # when ``magnitude_only`` is set to True, the norm is calculated on the magnitude coefficients
>>> # we have norms = [[sqrt(2), 2], [2, 2 * sqrt(3)]]
>>> # hence the changes at the change point are [2 - sqrt(2), 2 * sqrt(3) - 2]
>>> # the first coefficients is always prepended.
>>> for key, value in result.items():
>>> print(key, value)
weekly [1.41421356 0.58578644]
yearly [2. 1.46410162]
>>> # when ``magnitude_only`` is set to False, the norm is calculated directly on the change coefficients
>>> # we have changes [sqrt(2), 2] at the change point
>>> result = get_changes_from_beta(beta, seasonality_components_df, False)
>>> for key, value in result.items():
>>> print(key, value)
weekly [1.41421356 1.41421356]
yearly [2. 2.]
"""
# gets the number of terms in each component
num_terms = (seasonality_components_df["order"] * 2).tolist()
# gets the names of components
components = seasonality_components_df["seas_names"].tolist()
# reshapes the regression coefficients and computes the magnitude coefficients
# the columns are the terms of different orders for each component
# each row is one change point
beta_mat = beta.reshape(-1, sum(num_terms))
if magnitude_only:
# cumsum gets the coefficient for the term between this changepoint and the next one.
coef_mat = np.cumsum(beta_mat, axis=0)
# computes the change magnitudes of each component at each time point, metric is l2 norm
result = {}
for i in range(len(num_terms)):
start = np.sum(num_terms[:i]).astype(int)
end = np.sum(num_terms[:(i + 1)]).astype(int)
if magnitude_only:
result[components[i]] = np.diff(np.linalg.norm(coef_mat[:, start: end], axis=1), prepend=0)
else:
result[components[i]] = np.linalg.norm(beta_mat[:, start: end], axis=1)
return result
The provided code snippet includes necessary dependencies for implementing the `get_seasonality_changes_from_adaptive_lasso` function. Write a Python function `def get_seasonality_changes_from_adaptive_lasso( x, y, changepoint_dates, initial_coef, seasonality_components_df, min_index_distance=2, regularization_strength=0.6)` to solve the following problem:
Parses the adaptive lasso estimator to get change point dates. The functions calls ``adaptive_lasso_cv`` to selected potential seasonality change points. Then a filter is applied to eliminate change points that are too close. Specifically, in a set of close change points, the one with the largest absolute coefficient will be kept. Parameters ---------- x : `numpy.array` The design matrix. y : `numpy.array` The response vector. changepoint_dates : `pandas.Series` A pandas Series of all potential change point dates that were used to generate ``x``. initial_coef : `str` in ["ridge", "lasso", "old"] or `numpy.array' How to obtain the initial estimator. If a `str` is provided, the corresponding model is trained to obtain the initial estimator. If a `numpy.array` is provided, it is used as the initial estimator. seasonality_components_df : `pandas.DataFrame` The df to generate seasonality design matrix, which is compatible with ``seasonality_components_df`` in `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints` min_index_distance : `int` The minimal index distance that is allowed between two change points. regularization_strength : `float` in [0, 1] The regularization power for change points. Greater values imply fewer change points. 0 indicates all change points, and 1 indicates no change point. Returns ------- result : `dict` The detected seasonality change points result dictionary. Keys are the component names, and values are the corresponding detected change points.
Here is the function:
def get_seasonality_changes_from_adaptive_lasso(
x,
y,
changepoint_dates,
initial_coef,
seasonality_components_df,
min_index_distance=2,
regularization_strength=0.6):
"""Parses the adaptive lasso estimator to get change point dates.
The functions calls ``adaptive_lasso_cv`` to selected potential seasonality change points.
Then a filter is applied to eliminate change points that are too close.
Specifically, in a set of close change points, the one with the largest absolute
coefficient will be kept.
Parameters
----------
x : `numpy.array`
The design matrix.
y : `numpy.array`
The response vector.
changepoint_dates : `pandas.Series`
A pandas Series of all potential change point dates that were used to generate ``x``.
initial_coef : `str` in ["ridge", "lasso", "old"] or `numpy.array'
How to obtain the initial estimator. If a `str` is provided, the corresponding model is trained
to obtain the initial estimator. If a `numpy.array` is provided, it is used as the initial
estimator.
seasonality_components_df : `pandas.DataFrame`
The df to generate seasonality design matrix, which is compatible with
``seasonality_components_df`` in
`~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints`
min_index_distance : `int`
The minimal index distance that is allowed between two change points.
regularization_strength : `float` in [0, 1]
The regularization power for change points. Greater values imply fewer change points.
0 indicates all change points, and 1 indicates no change point.
Returns
-------
result : `dict`
The detected seasonality change points result dictionary. Keys are the component names,
and values are the corresponding detected change points.
"""
intercept, beta = adaptive_lasso_cv(
x=x,
y=y,
initial_coef=initial_coef,
regularization_strength=regularization_strength,
# Typically, seasonality has fewer changepoints than trend. Lower ratio results in higher lambda.
max_min_ratio=1e4)
change_result = get_changes_from_beta(
beta=beta,
seasonality_components_df=seasonality_components_df)
result = dict()
for component, changes in change_result.items():
nonzero_idx = [i for i, val in enumerate(changes) if val != 0]
cp_blocks = find_neighbor_changepoints(
cp_idx=nonzero_idx,
min_index_distance=min_index_distance,
)
cp_idx = filter_changepoints(cp_blocks, changes, min_index_distance)
result[component] = changepoint_dates.iloc[cp_idx].tolist()
return result | Parses the adaptive lasso estimator to get change point dates. The functions calls ``adaptive_lasso_cv`` to selected potential seasonality change points. Then a filter is applied to eliminate change points that are too close. Specifically, in a set of close change points, the one with the largest absolute coefficient will be kept. Parameters ---------- x : `numpy.array` The design matrix. y : `numpy.array` The response vector. changepoint_dates : `pandas.Series` A pandas Series of all potential change point dates that were used to generate ``x``. initial_coef : `str` in ["ridge", "lasso", "old"] or `numpy.array' How to obtain the initial estimator. If a `str` is provided, the corresponding model is trained to obtain the initial estimator. If a `numpy.array` is provided, it is used as the initial estimator. seasonality_components_df : `pandas.DataFrame` The df to generate seasonality design matrix, which is compatible with ``seasonality_components_df`` in `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints` min_index_distance : `int` The minimal index distance that is allowed between two change points. regularization_strength : `float` in [0, 1] The regularization power for change points. Greater values imply fewer change points. 0 indicates all change points, and 1 indicates no change point. Returns ------- result : `dict` The detected seasonality change points result dictionary. Keys are the component names, and values are the corresponding detected change points. |
167,403 | import warnings
from datetime import timedelta
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from pandas.plotting import register_matplotlib_converters
from pandas.tseries.frequencies import to_offset
from sklearn.linear_model import Lasso
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
from greykite.common.constants import CHANGEPOINT_COL_PREFIX
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import add_time_features_df
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import fourier_series_multi_fcn
from greykite.common.features.timeseries_features import get_changepoint_dates_from_changepoints_dict
from greykite.common.features.timeseries_features import get_changepoint_features
from greykite.common.features.timeseries_features import get_changepoint_features_and_values_from_config
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
from greykite.common.python_utils import get_pattern_cols
from greykite.common.python_utils import unique_elements_in_list
np.seterr(divide="ignore")
def build_trend_feature_df_with_changes(
df,
time_col,
origin_for_time_vars=None,
changepoints_dict="auto"):
"""A function to generate trend features from a given time series df.
The trend features include columns of the format max(0, x-c_i), where c_i is the i-th change point value.
If changepoints_dict has "method": "uniform", then n_changepoints change points plus the normal growth term are
generated uniformly over the whole time period. This is recommended.
Parameters
----------
df : `pandas.DataFrame`
The data df.
time_col : `str'
The column name of time column in ``df``, entries can be parsed with pd.to_datetime.
origin_for_time_vars : `float` or `None`, default `None`
Original continuous time value, if not provided, will be parsed from data.
changepoints_dict: `str`: "auto" or `dict`, default "auto"
Change point dictionary, compatible with
`~greykite.common.features.timeseries_features.get_changepoint_features_and_values_from_config`
If not provided, default is 100 change points evenly
distributed over the whole time period.
Returns
-------
df : `pandas.DataFrame`
Change point feature df with n_changepoints + 1 columns generated.
"""
df = df.copy()
# Gets changepoints features from config. Evenly distributed with n_changepoints specified is recommended.
if origin_for_time_vars is None:
origin_for_time_vars = get_default_origin_for_time_vars(df, time_col)
if changepoints_dict == "auto":
changepoints_dict = {
"method": "uniform",
"n_changepoints": 100
}
changepoints = get_changepoint_features_and_values_from_config(
df=df,
time_col=time_col,
changepoints_dict=changepoints_dict,
origin_for_time_vars=origin_for_time_vars)
if changepoints["changepoint_values"] is None:
# allows n_changepoints = 0
changepoint_values = np.array([0])
else:
changepoint_values = np.concatenate([[0], changepoints["changepoint_values"]])
growth_func = changepoints["growth_func"]
features_df = add_time_features_df(
df=df,
time_col=time_col,
conti_year_origin=origin_for_time_vars)
changepoint_dates = get_changepoint_dates_from_changepoints_dict(
changepoints_dict=changepoints_dict,
df=df,
time_col=time_col)
changepoint_dates = [pd.to_datetime(df[time_col].iloc[0])] + changepoint_dates
changepoint_features_df = get_changepoint_features(
features_df,
changepoint_values,
continuous_time_col=TimeFeaturesEnum.ct1.value,
growth_func=growth_func,
changepoint_dates=changepoint_dates)
changepoint_features_df.index = pd.to_datetime(df[time_col])
return changepoint_features_df
def build_seasonality_feature_df_with_changes(
df,
time_col,
origin_for_time_vars=None,
changepoints_dict=None,
fs_components_df=pd.DataFrame({
"name": [
TimeFeaturesEnum.tod.value,
TimeFeaturesEnum.tow.value,
TimeFeaturesEnum.toy.value],
"period": [24.0, 7.0, 1.0],
"order": [3, 3, 5],
"seas_names": ["daily", "weekly", "yearly"]})):
"""A function to generate yearly seasonality features from a given time series df.
The seasonality features include n_changepoints * 2 columns of the format
1{x > c_i} * sin(2 * pi / period * order * x) and 1{x > c_i} * cos(2 * pi / period * order * x),
where c_i is the i-th change point value.
Parameters
----------
df : `pandas.DataFrame`
The data df.
time_col : `str'
The column name of time column in ``df``, entries can be parsed with pd.to_datetime.
origin_for_time_vars : `float` or `None`, default `None`
Original continuous time value, if not provided, will be parsed from data.
changepoints_dict: `dict` or `None`, default `None`
Change point dictionary, compatible with
`~greykite.common.features.timeseries_features.get_changepoint_features_and_values_from_config`
If not provided, default is no change points.
fs_components_df: `pandas.DataFrame`
fs_components config df, compatible with
`~greykite.common.features.timeseries_features.fourier_series_multi_fcn`
Returns
-------
df : `pandas.DataFrame`
Seasonality feature df with [sum_{component_i} (2 * order_of_component_i)] * (num_changepoints + 1)
columns.
Each sum_{component_i} (2 * order_of_component_i) columns form a block. The first block contains the
original seasonality features, which accounts for the overall seasonality magnitudes. Each of the
rest num_changepoints block is a copy of the first block, with rows whose timestamps are before the
corresponding changepoint replaced by zeros. Such blocks only have effect on the seasonality
magnitudes after the corresponding changepoints.
"""
df = df.copy()
# Gets changepoints features from config. Evenly distributed with n_changepoints specified is recommended.
if origin_for_time_vars is None:
origin_for_time_vars = get_default_origin_for_time_vars(df, time_col)
features_df = add_time_features_df(
df=df,
time_col=time_col,
conti_year_origin=origin_for_time_vars)
fs_func = None
fs_cols = []
if fs_components_df is not None:
fs_components_df = fs_components_df[fs_components_df["order"] != 0]
fs_components_df = fs_components_df.reset_index()
if fs_components_df.shape[0] > 0:
fs_func = fourier_series_multi_fcn(
col_names=fs_components_df["name"],
periods=fs_components_df.get("period"),
orders=fs_components_df.get("order"),
seas_names=fs_components_df.get("seas_names")
)
time_features_example_df = build_time_features_df(
df[time_col][:2], # only needs the first two rows to get the column info
conti_year_origin=origin_for_time_vars)
fs = fs_func(time_features_example_df)
fs_cols = fs["cols"]
fs_features = fs_func(features_df)
fs_df = fs_features["df"]
fs_df.index = pd.to_datetime(df[time_col])
# Augments regular Fourier columns to truncated Fourier columns.
if changepoints_dict is not None:
changepoint_dates = get_changepoint_dates_from_changepoints_dict(
changepoints_dict=changepoints_dict,
df=df,
time_col=time_col
)
changepoint_dates = unique_elements_in_list(changepoint_dates)
# The following lines truncates the fourier series at each change point
# For each change point, the values of the fourier series before the change point are
# set to zero. The column name is simply appending `_%Y_%m_%d_%H` after the original column names.
col_names = fs_cols + [f"{col}{date.strftime('_%Y_%m_%d_%H')}" for date in changepoint_dates for col in fs_cols]
fs_truncated_df = pd.concat([fs_df] * (len(changepoint_dates) + 1), axis=1)
fs_truncated_df.columns = col_names
for i, date in enumerate(changepoint_dates):
cols = fs_truncated_df.columns[fs_df.shape[1] * (i + 1):]
fs_truncated_df.loc[(features_df["datetime"] < date).values, cols] = 0
fs_df = fs_truncated_df
return fs_df
class TimeFeaturesEnum(Enum):
"""Time features generated by
`~greykite.common.features.timeseries_features.build_time_features_df`.
The item names are lower-case letters (kept the same as the values) for easier check of existence.
To check if a string s is in this Enum,
use ``s in TimeFeaturesEnum.__dict__["_member_names_"]``.
Direct check of existence ``s in TimeFeaturesEnum`` is deprecated in python 3.8.
"""
# Absolute time features
datetime = "datetime"
date = "date"
year = "year"
year_length = "year_length"
quarter = "quarter"
quarter_start = "quarter_start"
quarter_length = "quarter_length"
month = "month"
month_length = "month_length"
hour = "hour"
minute = "minute"
second = "second"
year_quarter = "year_quarter"
year_month = "year_month"
woy = "woy"
doy = "doy"
doq = "doq"
dom = "dom"
dow = "dow"
str_dow = "str_dow"
str_doy = "str_doy"
is_weekend = "is_weekend"
# Relative time features
year_woy = "year_woy"
month_dom = "month_dom"
year_woy_dow = "year_woy_dow"
woy_dow = "woy_dow"
dow_hr = "dow_hr"
dow_hr_min = "dow_hr_min"
tod = "tod"
tow = "tow"
tom = "tom"
toq = "toq"
toy = "toy"
conti_year = "conti_year"
dow_grouped = "dow_grouped"
# ISO time features
year_iso = "year_iso"
year_woy_iso = "year_woy_iso"
year_woy_dow_iso = "year_woy_dow_iso"
# Continuous time features
ct1 = "ct1"
ct2 = "ct2"
ct3 = "ct3"
ct_sqrt = "ct_sqrt"
ct_root3 = "ct_root3"
us_dst = "us_dst"
eu_dst = "eu_dst"
The provided code snippet includes necessary dependencies for implementing the `estimate_trend_with_detected_changepoints` function. Write a Python function `def estimate_trend_with_detected_changepoints( df, time_col, value_col, changepoints, yearly_seasonality_order=8, estimator="ridge")` to solve the following problem:
Estimates the trend effect with detected change points. Parameters ---------- df : `pandas.DataFrame` The data df. time_col : `str` The column name of the time column in ``df``. value_col : `str` The column name of the value column in ``df``. changepoints : `list` A list of detected trend change points. yearly_seasonality_order : `int` The yearly seasonality order. estimator : `str`, default "ridge" "ols" or "ridge", the estimation model for trend estimation. Returns ------- trend_estimate : `pandas.Series` The estimated trend.
Here is the function:
def estimate_trend_with_detected_changepoints(
df,
time_col,
value_col,
changepoints,
yearly_seasonality_order=8,
estimator="ridge"):
"""Estimates the trend effect with detected change points.
Parameters
----------
df : `pandas.DataFrame`
The data df.
time_col : `str`
The column name of the time column in ``df``.
value_col : `str`
The column name of the value column in ``df``.
changepoints : `list`
A list of detected trend change points.
yearly_seasonality_order : `int`
The yearly seasonality order.
estimator : `str`, default "ridge"
"ols" or "ridge", the estimation model for trend estimation.
Returns
-------
trend_estimate : `pandas.Series`
The estimated trend.
"""
trend_df = build_trend_feature_df_with_changes(
df=df,
time_col=time_col,
changepoints_dict={
"method": "custom",
"dates": changepoints
}
)
if yearly_seasonality_order > 0:
long_seasonality_df = build_seasonality_feature_df_with_changes(
df=df,
time_col=time_col,
fs_components_df=pd.DataFrame({
"name": [TimeFeaturesEnum.conti_year.value],
"period": [1.0],
"order": [yearly_seasonality_order],
"seas_names": ["yearly"]})
)
trend_df = pd.concat([trend_df, long_seasonality_df], axis=1)
estimators = {
"ridge": RidgeCV,
"ols": LinearRegression
}
estimator = estimators.get(estimator)
if estimator is None:
raise ValueError("estimator can only be either 'ridge' or 'ols'.")
non_na_index = ~df[value_col].isnull().values
model = estimator().fit(trend_df.values[non_na_index], df[value_col].values[non_na_index])
# can't simply do .predict, because need to exclude the seasonality terms.
trend_estimate = np.matmul(
trend_df.values[:, :(len(changepoints) + 1)], model.coef_[:(len(changepoints) + 1)]) \
+ model.intercept_
trend_estimate = pd.Series(trend_estimate)
trend_estimate.index = pd.to_datetime(df[time_col])
return trend_estimate | Estimates the trend effect with detected change points. Parameters ---------- df : `pandas.DataFrame` The data df. time_col : `str` The column name of the time column in ``df``. value_col : `str` The column name of the value column in ``df``. changepoints : `list` A list of detected trend change points. yearly_seasonality_order : `int` The yearly seasonality order. estimator : `str`, default "ridge" "ols" or "ridge", the estimation model for trend estimation. Returns ------- trend_estimate : `pandas.Series` The estimated trend. |
167,404 | import warnings
from datetime import timedelta
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from pandas.plotting import register_matplotlib_converters
from pandas.tseries.frequencies import to_offset
from sklearn.linear_model import Lasso
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
from greykite.common.constants import CHANGEPOINT_COL_PREFIX
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import add_time_features_df
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import fourier_series_multi_fcn
from greykite.common.features.timeseries_features import get_changepoint_dates_from_changepoints_dict
from greykite.common.features.timeseries_features import get_changepoint_features
from greykite.common.features.timeseries_features import get_changepoint_features_and_values_from_config
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
from greykite.common.python_utils import get_pattern_cols
from greykite.common.python_utils import unique_elements_in_list
def build_seasonality_feature_df_from_detection_result(
df,
time_col,
seasonality_changepoints,
seasonality_components_df,
include_original_block=True,
include_components=None):
"""Builds seasonality feature df from detected seasonality change points.
The function is an extension of ``build_seasonality_feature_df_with_changes``. It can generate
a seasonality feature df with different change points for different components. These changepoints
are passed through a dictionary, which can be the output of
`~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints`
Parameters
__________
df : `pandas.DataFrame`
The dataframe used to build seasonality feature df.
time_col : `str`
The name of the time column in ``df``.
seasonality_changepoints : `dict`
The seasonality change point dictionary. The keys are seasonality components, and the values
are the corresponding change points given in lists.
For example
"weekly": [Timestamp('2020-01-01 00:00:00'), Timestamp('2021-04-05 00:00:00')]
"yearly": [Timestamp('2020-08-06 00:00:00')]
seasonality_components_df : `pandas.DataFrame`
The seasonality components dataframe that is compatible with
`~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints`
The values in "seas_names" must equal to the keys in ``seasonality_changepoints``.
include_original_block : `bool`, default True
Whether to include the original untruncated block of sin or cos columns for each component. If set to
False, the original seasonality block for each component will be dropped.
include_components : `list` [`str`] or None, default None
The components to be included from the result. If None, all components will be included.
Returns
-------
seasonality_feature_df : `pandas.DataFrame`
The seasonality feature dataframe similar to the output of `build_seasonality_feature_df_with_changes``
but possibly with different changepoints on different components.
"""
seasonality_df = pd.DataFrame()
for component in seasonality_changepoints.keys():
if include_components is None or component in include_components:
seasonality_df_cp = build_seasonality_feature_df_with_changes(
df=df,
time_col=time_col,
changepoints_dict={
"method": "custom",
"dates": seasonality_changepoints[component]
},
fs_components_df=seasonality_components_df[seasonality_components_df["seas_names"] == component]
)
if not include_original_block:
original_block_size = int(2 * seasonality_components_df.loc[
seasonality_components_df["seas_names"] == component, "order"].values[0])
seasonality_df_cp = seasonality_df_cp.iloc[:, original_block_size:]
seasonality_df = pd.concat([seasonality_df, seasonality_df_cp], axis=1)
extra_components = [component for component in seasonality_changepoints if component not in include_components] if include_components is not None else []
if extra_components:
warnings.warn(f"The following seasonality components have detected seasonality changepoints"
f" but these changepoints are not included in the model,"
f" because the seasonality component is not included in the model. {extra_components}")
return seasonality_df
The provided code snippet includes necessary dependencies for implementing the `estimate_seasonality_with_detected_changepoints` function. Write a Python function `def estimate_seasonality_with_detected_changepoints( df, time_col, value_col, seasonality_changepoints, seasonality_components_df, estimator="ols")` to solve the following problem:
Estimates the seasonality effect with detected change points. Parameters ---------- df : `pandas.DataFrame` The data df. time_col : `str` The column name of the time column in ``df``. value_col : `str` The column name of the value column in ``df``. seasonality_changepoints : `dict` The detected seasonality change points dictionary, output from `~greykite.algo.changepoint.adalasso.changepoints_utils.get_seasonality_changes_from_adaptive_lasso` seasonality_components_df : `pandas.DataFrame` The df to generate seasonality design matrix, which is compatible with ``seasonality_components_df`` in `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints` estimator : `str`, default "ols" "ols" or "ridge", the estimation model for seasonality estimation. Returns ------- seasonality_estimate : `pandas.Series` The estimated seasonality.
Here is the function:
def estimate_seasonality_with_detected_changepoints(
df,
time_col,
value_col,
seasonality_changepoints,
seasonality_components_df,
estimator="ols"):
"""Estimates the seasonality effect with detected change points.
Parameters
----------
df : `pandas.DataFrame`
The data df.
time_col : `str`
The column name of the time column in ``df``.
value_col : `str`
The column name of the value column in ``df``.
seasonality_changepoints : `dict`
The detected seasonality change points dictionary, output from
`~greykite.algo.changepoint.adalasso.changepoints_utils.get_seasonality_changes_from_adaptive_lasso`
seasonality_components_df : `pandas.DataFrame`
The df to generate seasonality design matrix, which is compatible with
``seasonality_components_df`` in
`~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints`
estimator : `str`, default "ols"
"ols" or "ridge", the estimation model for seasonality estimation.
Returns
-------
seasonality_estimate : `pandas.Series`
The estimated seasonality.
"""
seasonality_df = build_seasonality_feature_df_from_detection_result(
df=df,
time_col=time_col,
seasonality_changepoints=seasonality_changepoints,
seasonality_components_df=seasonality_components_df
)
estimators = {
"ridge": RidgeCV,
"ols": LinearRegression
}
estimator = estimators.get(estimator)
if estimator is None:
raise ValueError("estimator can only be either 'ridge' or 'ols'.")
non_na_index = ~df[value_col].isnull().values
model = estimator().fit(seasonality_df.values[non_na_index], df[value_col].values[non_na_index])
seasonality_estimate = model.predict(seasonality_df.values)
seasonality_estimate = pd.Series(seasonality_estimate)
seasonality_estimate.index = pd.to_datetime(df[time_col])
return seasonality_estimate | Estimates the seasonality effect with detected change points. Parameters ---------- df : `pandas.DataFrame` The data df. time_col : `str` The column name of the time column in ``df``. value_col : `str` The column name of the value column in ``df``. seasonality_changepoints : `dict` The detected seasonality change points dictionary, output from `~greykite.algo.changepoint.adalasso.changepoints_utils.get_seasonality_changes_from_adaptive_lasso` seasonality_components_df : `pandas.DataFrame` The df to generate seasonality design matrix, which is compatible with ``seasonality_components_df`` in `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints` estimator : `str`, default "ols" "ols" or "ridge", the estimation model for seasonality estimation. Returns ------- seasonality_estimate : `pandas.Series` The estimated seasonality. |
167,405 | import warnings
from datetime import timedelta
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from pandas.plotting import register_matplotlib_converters
from pandas.tseries.frequencies import to_offset
from sklearn.linear_model import Lasso
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
from greykite.common.constants import CHANGEPOINT_COL_PREFIX
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import add_time_features_df
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import fourier_series_multi_fcn
from greykite.common.features.timeseries_features import get_changepoint_dates_from_changepoints_dict
from greykite.common.features.timeseries_features import get_changepoint_features
from greykite.common.features.timeseries_features import get_changepoint_features_and_values_from_config
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
from greykite.common.python_utils import get_pattern_cols
from greykite.common.python_utils import unique_elements_in_list
def build_seasonality_feature_df_with_changes(
df,
time_col,
origin_for_time_vars=None,
changepoints_dict=None,
fs_components_df=pd.DataFrame({
"name": [
TimeFeaturesEnum.tod.value,
TimeFeaturesEnum.tow.value,
TimeFeaturesEnum.toy.value],
"period": [24.0, 7.0, 1.0],
"order": [3, 3, 5],
"seas_names": ["daily", "weekly", "yearly"]})):
"""A function to generate yearly seasonality features from a given time series df.
The seasonality features include n_changepoints * 2 columns of the format
1{x > c_i} * sin(2 * pi / period * order * x) and 1{x > c_i} * cos(2 * pi / period * order * x),
where c_i is the i-th change point value.
Parameters
----------
df : `pandas.DataFrame`
The data df.
time_col : `str'
The column name of time column in ``df``, entries can be parsed with pd.to_datetime.
origin_for_time_vars : `float` or `None`, default `None`
Original continuous time value, if not provided, will be parsed from data.
changepoints_dict: `dict` or `None`, default `None`
Change point dictionary, compatible with
`~greykite.common.features.timeseries_features.get_changepoint_features_and_values_from_config`
If not provided, default is no change points.
fs_components_df: `pandas.DataFrame`
fs_components config df, compatible with
`~greykite.common.features.timeseries_features.fourier_series_multi_fcn`
Returns
-------
df : `pandas.DataFrame`
Seasonality feature df with [sum_{component_i} (2 * order_of_component_i)] * (num_changepoints + 1)
columns.
Each sum_{component_i} (2 * order_of_component_i) columns form a block. The first block contains the
original seasonality features, which accounts for the overall seasonality magnitudes. Each of the
rest num_changepoints block is a copy of the first block, with rows whose timestamps are before the
corresponding changepoint replaced by zeros. Such blocks only have effect on the seasonality
magnitudes after the corresponding changepoints.
"""
df = df.copy()
# Gets changepoints features from config. Evenly distributed with n_changepoints specified is recommended.
if origin_for_time_vars is None:
origin_for_time_vars = get_default_origin_for_time_vars(df, time_col)
features_df = add_time_features_df(
df=df,
time_col=time_col,
conti_year_origin=origin_for_time_vars)
fs_func = None
fs_cols = []
if fs_components_df is not None:
fs_components_df = fs_components_df[fs_components_df["order"] != 0]
fs_components_df = fs_components_df.reset_index()
if fs_components_df.shape[0] > 0:
fs_func = fourier_series_multi_fcn(
col_names=fs_components_df["name"],
periods=fs_components_df.get("period"),
orders=fs_components_df.get("order"),
seas_names=fs_components_df.get("seas_names")
)
time_features_example_df = build_time_features_df(
df[time_col][:2], # only needs the first two rows to get the column info
conti_year_origin=origin_for_time_vars)
fs = fs_func(time_features_example_df)
fs_cols = fs["cols"]
fs_features = fs_func(features_df)
fs_df = fs_features["df"]
fs_df.index = pd.to_datetime(df[time_col])
# Augments regular Fourier columns to truncated Fourier columns.
if changepoints_dict is not None:
changepoint_dates = get_changepoint_dates_from_changepoints_dict(
changepoints_dict=changepoints_dict,
df=df,
time_col=time_col
)
changepoint_dates = unique_elements_in_list(changepoint_dates)
# The following lines truncates the fourier series at each change point
# For each change point, the values of the fourier series before the change point are
# set to zero. The column name is simply appending `_%Y_%m_%d_%H` after the original column names.
col_names = fs_cols + [f"{col}{date.strftime('_%Y_%m_%d_%H')}" for date in changepoint_dates for col in fs_cols]
fs_truncated_df = pd.concat([fs_df] * (len(changepoint_dates) + 1), axis=1)
fs_truncated_df.columns = col_names
for i, date in enumerate(changepoint_dates):
cols = fs_truncated_df.columns[fs_df.shape[1] * (i + 1):]
fs_truncated_df.loc[(features_df["datetime"] < date).values, cols] = 0
fs_df = fs_truncated_df
return fs_df
The provided code snippet includes necessary dependencies for implementing the `get_seasonality_changepoint_df_cols` function. Write a Python function `def get_seasonality_changepoint_df_cols( df, time_col, seasonality_changepoints, seasonality_components_df, include_original_block=True, include_components=None)` to solve the following problem:
Gets the seasonality change point feature df column names. Parameters ---------- df : `pandas.DataFrame` The dataframe used to build seasonality feature df. time_col : `str` The name of the time column in ``df``. seasonality_changepoints : `dict` The seasonality change point dictionary. The keys are seasonality components, and the values are the corresponding change points given in lists. For example "weekly": [Timestamp('2020-01-01 00:00:00'), Timestamp('2021-04-05 00:00:00')] "yearly": [Timestamp('2020-08-06 00:00:00')] seasonality_components_df : `pandas.DataFrame` The seasonality components dataframe that is compatible with `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints` The values in "seas_names" must equal to the keys in ``seasonality_changepoints``. include_original_block : `bool`, default True Whether to include the original untruncated block of sin or cos columns for each component. If set to False, the original seasonality block for each component will be dropped. include_components : `list` [`str`] or None, default None The components to be included from the result. If None, all components will be included. Returns ------- cols : `list` List of column names for seasonality change points df.
Here is the function:
def get_seasonality_changepoint_df_cols(
df,
time_col,
seasonality_changepoints,
seasonality_components_df,
include_original_block=True,
include_components=None):
"""Gets the seasonality change point feature df column names.
Parameters
----------
df : `pandas.DataFrame`
The dataframe used to build seasonality feature df.
time_col : `str`
The name of the time column in ``df``.
seasonality_changepoints : `dict`
The seasonality change point dictionary. The keys are seasonality components, and the values
are the corresponding change points given in lists.
For example
"weekly": [Timestamp('2020-01-01 00:00:00'), Timestamp('2021-04-05 00:00:00')]
"yearly": [Timestamp('2020-08-06 00:00:00')]
seasonality_components_df : `pandas.DataFrame`
The seasonality components dataframe that is compatible with
`~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints`
The values in "seas_names" must equal to the keys in ``seasonality_changepoints``.
include_original_block : `bool`, default True
Whether to include the original untruncated block of sin or cos columns for each component. If set to
False, the original seasonality block for each component will be dropped.
include_components : `list` [`str`] or None, default None
The components to be included from the result. If None, all components will be included.
Returns
-------
cols : `list`
List of column names for seasonality change points df.
"""
# only needs two rows to get the column names, reduces running time.
df = df.iloc[:2, :]
seasonality_cols = []
for component, dates in seasonality_changepoints.items():
if include_components is None or component in include_components:
regular_seasonality_df = build_seasonality_feature_df_with_changes(
df=df,
time_col=time_col,
fs_components_df=seasonality_components_df.loc[seasonality_components_df["seas_names"] == component, :]
)
temp_cols = list(regular_seasonality_df.columns) if include_original_block else []
for date in dates:
temp_cols += [f"{col}{date.strftime('_%Y_%m_%d_%H')}" for col in list(regular_seasonality_df.columns)]
seasonality_cols += temp_cols
return seasonality_cols | Gets the seasonality change point feature df column names. Parameters ---------- df : `pandas.DataFrame` The dataframe used to build seasonality feature df. time_col : `str` The name of the time column in ``df``. seasonality_changepoints : `dict` The seasonality change point dictionary. The keys are seasonality components, and the values are the corresponding change points given in lists. For example "weekly": [Timestamp('2020-01-01 00:00:00'), Timestamp('2021-04-05 00:00:00')] "yearly": [Timestamp('2020-08-06 00:00:00')] seasonality_components_df : `pandas.DataFrame` The seasonality components dataframe that is compatible with `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints` The values in "seas_names" must equal to the keys in ``seasonality_changepoints``. include_original_block : `bool`, default True Whether to include the original untruncated block of sin or cos columns for each component. If set to False, the original seasonality block for each component will be dropped. include_components : `list` [`str`] or None, default None The components to be included from the result. If None, all components will be included. Returns ------- cols : `list` List of column names for seasonality change points df. |
167,406 | import warnings
from datetime import timedelta
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from pandas.plotting import register_matplotlib_converters
from pandas.tseries.frequencies import to_offset
from sklearn.linear_model import Lasso
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
from greykite.common.constants import CHANGEPOINT_COL_PREFIX
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import add_time_features_df
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import fourier_series_multi_fcn
from greykite.common.features.timeseries_features import get_changepoint_dates_from_changepoints_dict
from greykite.common.features.timeseries_features import get_changepoint_features
from greykite.common.features.timeseries_features import get_changepoint_features_and_values_from_config
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
from greykite.common.python_utils import get_pattern_cols
from greykite.common.python_utils import unique_elements_in_list
CHANGEPOINT_COL_PREFIX = "changepoint"
def get_pattern_cols(cols, pos_pattern=None, neg_pattern=None):
"""Get columns names from a list that matches ``pos_pattern``,
but does not match ``neg_pattern``.
If a column name matches both ``pos_pattern`` and ``neg_pattern``, it is excluded.
Parameters
----------
cols : `List` ['str']
Usually column names of a DataFrame.
pos_pattern : regular expression
If column name matches this pattern, it is included in the output.
neg_pattern : regular expression
If column name matches this pattern, it is excluded from the output.
Returns
-------
pattern_cols : `List` ['str']
List of column names that match the pattern.
"""
if pos_pattern is None:
pos_pattern_cols = []
else:
pos_regex = re.compile(pos_pattern)
pos_pattern_cols = [col for col in cols if pos_regex.findall(col)]
if neg_pattern is None:
neg_pattern_cols = []
else:
neg_regex = re.compile(neg_pattern)
neg_pattern_cols = [col for col in cols if neg_regex.findall(col)]
pattern_cols = [col for col in cols if
col in pos_pattern_cols and col not in neg_pattern_cols]
return pattern_cols
The provided code snippet includes necessary dependencies for implementing the `get_trend_changepoint_dates_from_cols` function. Write a Python function `def get_trend_changepoint_dates_from_cols(trend_cols)` to solve the following problem:
Gets the trend changepoint dates from trend changepoint column names. Parameters ---------- trend_cols : `list[`str`]` List of trend changepoint column names. EX. "changepoint2_2018_01_05_00". Returns ------- trend_changepoint_dates : `list[`timestamp`]` List of trend changepoint dates.
Here is the function:
def get_trend_changepoint_dates_from_cols(trend_cols):
"""Gets the trend changepoint dates from trend changepoint column names.
Parameters
----------
trend_cols : `list[`str`]`
List of trend changepoint column names. EX. "changepoint2_2018_01_05_00".
Returns
-------
trend_changepoint_dates : `list[`timestamp`]`
List of trend changepoint dates.
"""
trend_changepoint_dates = []
trend_cols = get_pattern_cols(trend_cols, f"^{CHANGEPOINT_COL_PREFIX}")
if trend_cols:
for col in trend_cols:
date = col.split("_")[1:]
date = date + ['00'] * (6 - len(date)) # 6 means Y m d H M S
date = f'{"-".join(date[:3])} {":".join(date[3:])}' # Y-m-d H:M:S
trend_changepoint_dates.append(pd.to_datetime(date))
return trend_changepoint_dates | Gets the trend changepoint dates from trend changepoint column names. Parameters ---------- trend_cols : `list[`str`]` List of trend changepoint column names. EX. "changepoint2_2018_01_05_00". Returns ------- trend_changepoint_dates : `list[`timestamp`]` List of trend changepoint dates. |
167,407 | import warnings
from datetime import timedelta
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from pandas.plotting import register_matplotlib_converters
from pandas.tseries.frequencies import to_offset
from sklearn.linear_model import Lasso
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
from greykite.common.constants import CHANGEPOINT_COL_PREFIX
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import add_time_features_df
from greykite.common.features.timeseries_features import build_time_features_df
from greykite.common.features.timeseries_features import fourier_series_multi_fcn
from greykite.common.features.timeseries_features import get_changepoint_dates_from_changepoints_dict
from greykite.common.features.timeseries_features import get_changepoint_features
from greykite.common.features.timeseries_features import get_changepoint_features_and_values_from_config
from greykite.common.features.timeseries_features import get_default_origin_for_time_vars
from greykite.common.python_utils import get_pattern_cols
from greykite.common.python_utils import unique_elements_in_list
def check_freq_unit_at_most_day(freq, name):
"""Checks if the ``freq`` parameter passed to a function has unit at most "D"
Parameters
----------
freq : `DateOffset`, `Timedelta` or `str`
The parameter passed as ``freq``.
name : `str`
The name of the parameter ``freq``.
Returns
-------
None
Raises
------
ValueError
Because the input frequency has unit greater than "D".
"""
if (isinstance(freq, str) and
any(char in freq for char in ["W", "M", "Y"])):
raise ValueError(f"In {name}, the maximal unit is 'D', "
"i.e., you may use units no more than 'D' such as"
"'10D', '5H', '100T', '200S'. The reason is that 'W', 'M' "
"or higher has either cycles or indefinite number of days, "
"thus is not parsable by pandas as timedelta.")
The provided code snippet includes necessary dependencies for implementing the `get_yearly_seasonality_changepoint_dates_from_freq` function. Write a Python function `def get_yearly_seasonality_changepoint_dates_from_freq( df, time_col, yearly_seasonality_change_freq, min_training_length="183D")` to solve the following problem:
Gets the yearly seasonality changepoint dates from change frequency. This is an internal function used for varying yearly seasonality effects in `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_trend_changepoints` For a given ``yearly_seasonality_change_freq``, for example "365D", it generates changepoint dates according to this frequency within the timeframe of ``df``. The length of data after the last changepoint date can not be less than ``least_training_length``. Parameters ---------- df : `pandas.DataFrame` The data df. time_col : `str` The column name for time column in ``df``. yearly_seasonality_change_freq : `DateOffset`, `Timedelta` or `str` or `None` How often to change the yearly seasonality model, i.e., how often to place yearly seasonality changepoints. Note that if you use `str` as input, the maximal supported unit is day, i.e., you might use "200D" but not "12M" or "1Y". min_training_length : `DateOffset`, `Timedelta` or `str` or `None`, default "183D" The minimum length between the last changepoint date and the last date of ``df[time_col]``. Changepoints too close to the end will be omitted. Recommended at least half a year. Note that if you use `str` as input, the maximal supported unit is day, i.e., you might use "200D" but not "12M" or "1Y". Returns ------- yearly_seasonality_changepoint_dates : `list` [ `pandas._libs.tslibs.timestamps.Timestamp` ] A list of yearly seasonality changepoint dates.
Here is the function:
def get_yearly_seasonality_changepoint_dates_from_freq(
df,
time_col,
yearly_seasonality_change_freq,
min_training_length="183D"):
"""Gets the yearly seasonality changepoint dates from change frequency.
This is an internal function used for varying yearly seasonality effects in
`~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_trend_changepoints`
For a given ``yearly_seasonality_change_freq``, for example "365D", it generates changepoint
dates according to this frequency within the timeframe of ``df``. The length of data after the last
changepoint date can not be less than ``least_training_length``.
Parameters
----------
df : `pandas.DataFrame`
The data df.
time_col : `str`
The column name for time column in ``df``.
yearly_seasonality_change_freq : `DateOffset`, `Timedelta` or `str` or `None`
How often to change the yearly seasonality model, i.e., how often to place yearly seasonality
changepoints.
Note that if you use `str` as input, the maximal supported unit is day, i.e.,
you might use "200D" but not "12M" or "1Y".
min_training_length : `DateOffset`, `Timedelta` or `str` or `None`, default "183D"
The minimum length between the last changepoint date and the last date of ``df[time_col]``.
Changepoints too close to the end will be omitted. Recommended at least half a year.
Note that if you use `str` as input, the maximal supported unit is day, i.e.,
you might use "200D" but not "12M" or "1Y".
Returns
-------
yearly_seasonality_changepoint_dates : `list` [ `pandas._libs.tslibs.timestamps.Timestamp` ]
A list of yearly seasonality changepoint dates.
"""
if yearly_seasonality_change_freq is None:
return []
check_freq_unit_at_most_day(yearly_seasonality_change_freq, "yearly_seasonality_change_freq")
yearly_seasonality_change_freq = to_offset(yearly_seasonality_change_freq)
if yearly_seasonality_change_freq.delta < timedelta(days=365):
warnings.warn("yearly_seasonality_change_freq is less than a year. It might be too short "
"to fit accurate yearly seasonality.")
check_freq_unit_at_most_day(min_training_length, "least_training_length")
if min_training_length is not None:
min_training_length = to_offset(min_training_length)
else:
min_training_length = to_offset("0D")
first_day_in_df = pd.to_datetime(df[time_col].iloc[0])
last_day_in_df = pd.to_datetime(df[time_col].iloc[-1])
yearly_seasonality_changepoint_dates = list(pd.date_range(
start=first_day_in_df,
end=last_day_in_df - min_training_length,
freq=yearly_seasonality_change_freq))[1:] # do not include the start date
if len(yearly_seasonality_changepoint_dates) == 0:
warnings.warn("No yearly seasonality changepoint added. Either data length is too short "
"or yearly_seasonality_change_freq is too long.")
return yearly_seasonality_changepoint_dates | Gets the yearly seasonality changepoint dates from change frequency. This is an internal function used for varying yearly seasonality effects in `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_trend_changepoints` For a given ``yearly_seasonality_change_freq``, for example "365D", it generates changepoint dates according to this frequency within the timeframe of ``df``. The length of data after the last changepoint date can not be less than ``least_training_length``. Parameters ---------- df : `pandas.DataFrame` The data df. time_col : `str` The column name for time column in ``df``. yearly_seasonality_change_freq : `DateOffset`, `Timedelta` or `str` or `None` How often to change the yearly seasonality model, i.e., how often to place yearly seasonality changepoints. Note that if you use `str` as input, the maximal supported unit is day, i.e., you might use "200D" but not "12M" or "1Y". min_training_length : `DateOffset`, `Timedelta` or `str` or `None`, default "183D" The minimum length between the last changepoint date and the last date of ``df[time_col]``. Changepoints too close to the end will be omitted. Recommended at least half a year. Note that if you use `str` as input, the maximal supported unit is day, i.e., you might use "200D" but not "12M" or "1Y". Returns ------- yearly_seasonality_changepoint_dates : `list` [ `pandas._libs.tslibs.timestamps.Timestamp` ] A list of yearly seasonality changepoint dates. |
167,408 | import warnings
from datetime import timedelta
from typing import List
from typing import Optional
import numpy as np
import pandas as pd
from pandas.tseries.frequencies import to_offset
from sklearn.base import RegressorMixin
from sklearn.exceptions import ConvergenceWarning
from sklearn.linear_model import LassoCV
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
from greykite.algo.changepoint.adalasso.changepoints_utils import build_seasonality_feature_df_with_changes
from greykite.algo.changepoint.adalasso.changepoints_utils import build_trend_feature_df_with_changes
from greykite.algo.changepoint.adalasso.changepoints_utils import check_freq_unit_at_most_day
from greykite.algo.changepoint.adalasso.changepoints_utils import combine_detected_and_custom_trend_changepoints
from greykite.algo.changepoint.adalasso.changepoints_utils import compute_fitted_components
from greykite.algo.changepoint.adalasso.changepoints_utils import compute_min_changepoint_index_distance
from greykite.algo.changepoint.adalasso.changepoints_utils import estimate_seasonality_with_detected_changepoints
from greykite.algo.changepoint.adalasso.changepoints_utils import estimate_trend_with_detected_changepoints
from greykite.algo.changepoint.adalasso.changepoints_utils import get_changepoint_dates_from_changepoints_dict
from greykite.algo.changepoint.adalasso.changepoints_utils import get_seasonality_changes_from_adaptive_lasso
from greykite.algo.changepoint.adalasso.changepoints_utils import get_trend_changes_from_adaptive_lasso
from greykite.algo.changepoint.adalasso.changepoints_utils import get_yearly_seasonality_changepoint_dates_from_freq
from greykite.algo.changepoint.adalasso.changepoints_utils import plot_change
from greykite.algo.changepoint.shift_detection.shift_detector import ShiftDetection
from greykite.common.constants import TimeFeaturesEnum
from greykite.common.features.timeseries_features import get_evenly_spaced_changepoints_dates
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.common.logging import pprint
from greykite.common.python_utils import ignore_warnings
class ChangepointDetector:
"""A class to implement change point detection.
Currently supports long-term change point detection only. Input is a dataframe with time_col
indicating the column of time info (the format should be able to be parsed by pd.to_datetime),
and value_col indicating the column of observed time series values.
Attributes
----------
original_df : `pandas.DataFrame`
The original data df, used to retrieve original observations, if aggregation is used in
fitting change points.
time_col : `str`
The column name for time column.
value_col : `str`
The column name for value column.
trend_potential_changepoint_n: `int`
The number of change points that are evenly distributed over the time period.
yearly_seasonality_order : `int`
The yearly seasonality order used when fitting trend.
y : `pandas.Series`
The observations after aggregation.
trend_df : `pandas.DataFrame`
The augmented df of the original_df, including regressors of trend change points and
Fourier series for yearly seasonality.
trend_model : `sklearn.base.RegressionMixin`
The fitted trend model.
trend_coef : `numpy.array`
The estimated trend coefficients.
trend_intercept : `float`
The estimated trend intercept.
adaptive_lasso_coef : `list`
The list of length two, first element is estimated trend coefficients, and second element
is intercept, both estimated by adaptive lasso.
trend_changepoints : `list`
The list of detected trend change points, parsable by pd.to_datetime
trend_estimation : `pd.Series`
The estimated trend with detected trend change points.
seasonality_df : `pandas.DataFrame`
The augmented df of ``original_df``, including regressors of seasonality change points with
different Fourier series frequencies.
seasonality_changepoints : `dict`
The dictionary of detected seasonality change points for each component.
Keys are component names, and values are list of change points.
seasonality_estimation : `pandas.Series`
The estimated seasonality with detected seasonality change points.
The series has the same length as ``original_df``. Index is timestamp, and values
are the estimated seasonality at each timestamp.
The seasonality estimation is the estimated of seasonality effect with trend estimated
by `~greykite.algo.changepoint.adalasso.changepoints_utils.estimate_trend_with_detected_changepoints`
removed.
Methods
-------
find_trend_changepoints : callable
Finds the potential trend change points for a given time series df.
plot : callable
Plot the results after implementing find_trend_changepoints.
"""
def __init__(self):
self.original_df: Optional[pd.DataFrame] = None
self.time_col: Optional[str] = None
self.value_col: Optional[str] = None
self.trend_potential_changepoint_n: Optional[int] = None
self.yearly_seasonality_order: Optional[int] = None
self.y: Optional[pd.Series, pd.DataFrame] = None
self.trend_df: Optional[pd.Series, pd.DataFrame] = None
self.trend_model: Optional[RegressorMixin] = None
self.trend_coef: Optional[np.ndarray] = None
self.trend_intercept: Optional[float] = None
self.adaptive_lasso_coef: Optional[List] = None
self.trend_changepoints: Optional[List] = None
self.trend_estimation: Optional[pd.Series] = None
self.seasonality_df: Optional[pd.DataFrame] = None
self.seasonality_changepoints: Optional[dict] = None
self.seasonality_estimation: Optional[pd.Series] = None
self.shift_detector: Optional[ShiftDetection] = None
self.level_shift_df: Optional[pd.DataFrame] = None
def find_trend_changepoints(
self,
df,
time_col,
value_col,
shift_detector=None,
yearly_seasonality_order=8,
yearly_seasonality_change_freq=None,
resample_freq="D",
trend_estimator="ridge",
adaptive_lasso_initial_estimator="ridge",
regularization_strength=None,
actual_changepoint_min_distance="30D",
potential_changepoint_distance=None,
potential_changepoint_n=100,
potential_changepoint_n_max=None,
no_changepoint_distance_from_begin=None,
no_changepoint_proportion_from_begin=0.0,
no_changepoint_distance_from_end=None,
no_changepoint_proportion_from_end=0.0,
fast_trend_estimation=True):
"""Finds trend change points automatically by adaptive lasso.
The algorithm does an aggregation with a user-defined frequency, defaults daily.
If ``potential_changepoint_distance`` is not given, ``potential_changepoint_n``
potential change points are evenly distributed over the time period, else
``potential_changepoint_n`` is overridden by::
total_time_length / ``potential_changepoint_distance``
Users can specify either ``no_changepoint_proportion_from_end`` to specify what proportion
from the end of data they do not want changepoints, or ``no_changepoint_distance_from_end``
(overrides ``no_changepoint_proportion_from_end``) to specify how long from the end they
do not want change points.
Then all potential change points will be selected by adaptive lasso, with the initial
estimator specified by ``adaptive_lasso_initial_estimator``. If user specifies
``regularization_strength``, then the adaptive lasso will be run with a single tuning
parameter calculated based on user provided prior, else a cross-validation will be run to
automatically select the tuning parameter.
A yearly seasonality is also fitted at the same time, preventing trend from catching
yearly periodical changes.
A rule-based guard function is applied at the end to ensure change points are not
too close, as specified by ``actual_changepoint_min_distance``.
Parameters
----------
df: `pandas.DataFrame`
The data df
time_col : `str`
Time column name in ``df``
value_col : `str`
Value column name in ``df``
shift_detector: `greykite.algo.changepoint.shift_detection.shift_detector.ShiftDetection`
An instance of ShiftDetection for identifying level shifts and computing regressors. Level
shift points will be considered as regressors when selecting change points by adaptive lasso.
yearly_seasonality_order : `int`, default 8
Fourier series order to capture yearly seasonality.
yearly_seasonality_change_freq : `DateOffset`, `Timedelta` or `str` or `None`, default `None`
How often to change the yearly seasonality model. Set to `None` to disable this feature.
This is useful if you have more than 2.5 years of data and the detected trend without this
feature is inaccurate because yearly seasonality changes over the training period.
Modeling yearly seasonality separately over the each period can prevent trend changepoints
from fitting changes in yearly seasonality. For example, if you have 2.5 years of data and
yearly seasonality increases in magnitude after the first year, setting this parameter to
"365D" will model each year's yearly seasonality differently and capture both shapes.
However, without this feature, both years will have the same yearly seasonality, roughly
the average effect across the training set.
Note that if you use `str` as input, the maximal supported unit is day, i.e.,
you might use "200D" but not "12M" or "1Y".
resample_freq : `DateOffset`, `Timedelta`, `str` or None, default "D".
The frequency to aggregate data.
Coarser aggregation leads to fitting longer term trends.
If None, no aggregation will be done.
trend_estimator : `str` in ["ridge", "lasso" or "ols"], default "ridge".
The estimator to estimate trend. The estimated trend is only for plotting purposes.
'ols' is not recommended when ``yearly_seasonality_order`` is specified other than 0,
because significant over-fitting will happen.
In this case, the given value is overridden by "ridge".
adaptive_lasso_initial_estimator : `str` in ["ridge", "lasso" or "ols"], default "ridge".
The initial estimator to compute adaptive lasso weights
regularization_strength : `float` in [0, 1] or `None`
The regularization for change points. Greater value implies fewer change points.
0 indicates all change points, and 1 indicates no change point.
If `None`, the turning parameter will be selected by cross-validation.
If a value is given, it will be used as the tuning parameter.
actual_changepoint_min_distance : `DateOffset`, `Timedelta` or `str`, default "30D"
The minimal distance allowed between detected change points. If consecutive change points
are within this minimal distance, the one with smaller absolute change coefficient will
be dropped.
Note: maximal unit is 'D', i.e., you may use units no more than 'D' such as
'10D', '5H', '100T', '200S'. The reason is that 'W', 'M' or higher has either
cycles or indefinite number of days, thus is not parsable by pandas as timedelta.
potential_changepoint_distance : `DateOffset`, `Timedelta`, `str` or None, default None
The distance between potential change points.
If provided, will override the parameter ``potential_changepoint_n``.
Note: maximal unit is 'D', i.e., you may only use units no more than 'D' such as
'10D', '5H', '100T', '200S'. The reason is that 'W', 'M' or higher has either
cycles or indefinite number of days, thus is not parsable by pandas as timedelta.
potential_changepoint_n : `int`, default 100
Number of change points to be evenly distributed, recommended 1-2 per month, based
on the training data length.
potential_changepoint_n_max : `int` or None, default None
The maximum number of potential changepoints.
This parameter is effective when user specifies ``potential_changepoint_distance``,
and the number of potential changepoints in the training data is more than ``potential_changepoint_n_max``,
then it is equivalent to specifying ``potential_changepoint_n = potential_changepoint_n_max``,
and ignoring ``potential_changepoint_distance``.
no_changepoint_distance_from_begin : `DateOffset`, `Timedelta`, `str` or None, default None
The length of time from the beginning of training data, within which no change point will be placed.
If provided, will override the parameter ``no_changepoint_proportion_from_begin``.
Note: maximal unit is 'D', i.e., you may only use units no more than 'D' such as
'10D', '5H', '100T', '200S'. The reason is that 'W', 'M' or higher has either
cycles or indefinite number of days, thus is not parsable by pandas as timedelta.
no_changepoint_proportion_from_begin : `float` in [0, 1], default 0.0.
``potential_changepoint_n`` change points will be placed evenly over the whole training period,
however, change points that are located within the first ``no_changepoint_proportion_from_begin``
proportion of training period will not be used for change point detection.
no_changepoint_distance_from_end : `DateOffset`, `Timedelta`, `str` or None, default None
The length of time from the end of training data, within which no change point will be placed.
If provided, will override the parameter ``no_changepoint_proportion_from_end``.
Note: maximal unit is 'D', i.e., you may only use units no more than 'D' such as
'10D', '5H', '100T', '200S'. The reason is that 'W', 'M' or higher has either
cycles or indefinite number of days, thus is not parsable by pandas as timedelta.
no_changepoint_proportion_from_end : `float` in [0, 1], default 0.0.
``potential_changepoint_n`` change points will be placed evenly over the whole training period,
however, change points that are located within the last ``no_changepoint_proportion_from_end``
proportion of training period will not be used for change point detection.
fast_trend_estimation : `bool`, default True
If True, the trend estimation is not refitted on the original data,
but is a linear interpolation of the fitted trend from the resampled time series.
If False, the trend estimation is refitted on the original data.
Return
------
result : `dict`
result dictionary with keys:
``"trend_feature_df"`` : `pandas.DataFrame`
The augmented df for change detection, in other words, the design matrix for
the regression model. Columns:
- 'changepoint0': regressor for change point 0, equals the continuous time
of the observation minus the continuous time for time of origin.
- ...
- 'changepoint{potential_changepoint_n}': regressor for change point
{potential_changepoint_n}, equals the continuous time of the observation
minus the continuous time of the {potential_changepoint_n}th change point.
- 'cos1_conti_year_yearly': cosine yearly seasonality regressor of first order.
- 'sin1_conti_year_yearly': sine yearly seasonality regressor of first order.
- ...
- 'cos{yearly_seasonality_order}_conti_year_yearly' : cosine yearly seasonality
regressor of {yearly_seasonality_order}th order.
- 'sin{yearly_seasonality_order}_conti_year_yearly' : sine yearly seasonality
regressor of {yearly_seasonality_order}th order.
``"trend_changepoints"`` : `list`
The list of detected change points.
``"changepoints_dict"`` : `dict`
The change point dictionary that is compatible as an input with
`~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast`
``"trend_estimation"`` : `pandas.Series`
The estimated trend with detected trend change points.
"""
# Checks parameter rationality
if potential_changepoint_n < 0:
raise ValueError("potential_changepoint_n can not be negative. "
"A large number such as 100 is recommended")
if yearly_seasonality_order < 0:
raise ValueError("year_seasonality_order can not be negative. "
"A number less than or equal to 10 is recommended")
if df.dropna().shape[0] < 5:
raise ValueError("Change point detector does not work for less than "
"5 observations. Please increase sample size.")
if no_changepoint_proportion_from_begin < 0 or no_changepoint_proportion_from_begin > 1:
raise ValueError("no_changepoint_proportion_from_begin needs to be between 0 and 1.")
if no_changepoint_proportion_from_end < 0 or no_changepoint_proportion_from_end > 1:
raise ValueError("no_changepoint_proportion_from_end needs to be between 0 and 1.")
if no_changepoint_distance_from_begin is not None:
check_freq_unit_at_most_day(no_changepoint_distance_from_begin, "no_changepoint_distance_from_begin")
data_length = pd.to_datetime(df[time_col].iloc[-1]) - pd.to_datetime(df[time_col].iloc[0])
no_changepoint_proportion_from_begin = to_offset(no_changepoint_distance_from_begin).delta / data_length
no_changepoint_proportion_from_begin = min(no_changepoint_proportion_from_begin, 1)
if no_changepoint_distance_from_end is not None:
check_freq_unit_at_most_day(no_changepoint_distance_from_end, "no_changepoint_distance_from_end")
data_length = pd.to_datetime(df[time_col].iloc[-1]) - pd.to_datetime(df[time_col].iloc[0])
no_changepoint_proportion_from_end = to_offset(no_changepoint_distance_from_end).delta / data_length
no_changepoint_proportion_from_end = min(no_changepoint_proportion_from_end, 1)
if potential_changepoint_distance is not None:
check_freq_unit_at_most_day(potential_changepoint_distance, "potential_changepoint_distance")
data_length = pd.to_datetime(df[time_col].iloc[-1]) - pd.to_datetime(df[time_col].iloc[0])
potential_changepoint_n = data_length // to_offset(potential_changepoint_distance).delta
if potential_changepoint_n_max is not None:
if potential_changepoint_n_max <= 0:
raise ValueError("potential_changepoint_n_max must be a positive integer.")
if potential_changepoint_n > potential_changepoint_n_max:
log_message(
message=f"Number of potential changepoints is capped by 'potential_changepoint_n_max' "
f"as {potential_changepoint_n_max}. The 'potential_changepoint_distance' "
f"{potential_changepoint_distance} is ignored. "
f"The original number of changepoints was {potential_changepoint_n}.",
level=LoggingLevelEnum.INFO
)
potential_changepoint_n = potential_changepoint_n_max
if regularization_strength is not None and (regularization_strength < 0 or regularization_strength > 1):
raise ValueError("regularization_strength must be between 0.0 and 1.0.")
df = df.copy()
self.trend_potential_changepoint_n = potential_changepoint_n
self.time_col = time_col
self.value_col = value_col
self.original_df = df
self.shift_detector = shift_detector
# If a shift detector object is passed to the constructor, we're making Changepoint cognizant of level shifts
# and it will handle the level shifts as independent regressors.
if self.shift_detector is not None:
self.level_shift_cols, self.level_shift_df = self.shift_detector.detect(
df.copy(),
time_col=time_col,
value_col=value_col,
forecast_horizon=0
)
# Resamples df to get a coarser granularity to get rid of shorter seasonality.
# The try except below speeds up unnecessary datetime transformation.
if resample_freq is not None:
try:
df_resample = df.resample(resample_freq, on=time_col).mean().reset_index()
except TypeError:
df[time_col] = pd.to_datetime(df[time_col])
df_resample = df.resample(resample_freq, on=time_col).mean().reset_index()
else:
df[time_col] = pd.to_datetime(df[time_col])
df_resample = df.copy()
# The ``df.resample`` function creates NA when the original df has a missing observation
# or its value is NA.
# The estimation algorithm does not allow NA, so we drop those rows.
df_resample = df_resample.dropna()
self.original_df[time_col] = df[time_col]
# Prepares response df.
y = df_resample[value_col]
y.index = df_resample[time_col]
self.y = y
# Prepares trend feature df.
# Potential changepoints are placed uniformly among rows without a missing value, after resampling.
trend_df = build_trend_feature_df_with_changes(
df=df_resample,
time_col=time_col,
changepoints_dict={
"method": "uniform",
"n_changepoints": potential_changepoint_n
}
)
# Gets changepoint features only in range filtered by ``no_changepoint_proportion_from_begin`` and
# ``no_changepoint_proportion_from_end`` of time period.
n_changepoints_within_range_begin = int(potential_changepoint_n * no_changepoint_proportion_from_begin)
n_changepoints_within_range_end = int(potential_changepoint_n * (1 - no_changepoint_proportion_from_end))
if n_changepoints_within_range_begin < n_changepoints_within_range_end:
trend_df = trend_df.iloc[:, [0] + list(range(n_changepoints_within_range_begin + 1, n_changepoints_within_range_end + 1))]
else:
# Linear growth term only.
trend_df = trend_df.iloc[:, [0]]
# Builds yearly seasonality feature df
if yearly_seasonality_order is not None and yearly_seasonality_order > 0:
self.yearly_seasonality_order = yearly_seasonality_order
# Gets yearly seasonality changepoints, allowing varying yearly seasonality coefficients
# to capture yearly seasonality shape change.
yearly_seasonality_changepoint_dates = get_yearly_seasonality_changepoint_dates_from_freq(
df=df,
time_col=time_col,
yearly_seasonality_change_freq=yearly_seasonality_change_freq)
long_seasonality_df = build_seasonality_feature_df_with_changes(
df=df_resample,
time_col=time_col,
changepoints_dict=dict(
method="custom",
dates=yearly_seasonality_changepoint_dates),
fs_components_df=pd.DataFrame({
"name": [TimeFeaturesEnum.conti_year.value],
"period": [1.0],
"order": [yearly_seasonality_order],
"seas_names": ["yearly"]})
)
trend_df = pd.concat([trend_df, long_seasonality_df], axis=1)
# Augment the trend_df with the additional level shift regressors.
if self.shift_detector is not None and len(self.level_shift_cols) > 0:
# Rename each column to have level shift prefixed in name.
pad_char, pad_size = 0, 4 # Left pad the levelshift regressors with 0s for sorting.
new_col_names = {col_name: f"levelshift_{ndx:{pad_char}{pad_size}}_{col_name}" for ndx, col_name in enumerate(self.level_shift_cols)}
self.level_shift_df.rename(columns=new_col_names, inplace=True)
# Save regressors for concatenation to trend_df.
time_col_and_regressor_cols = [time_col] + sorted(new_col_names.values())
levelshift_regressors_df = self.level_shift_df[time_col_and_regressor_cols]
# Resample level shift df according to resample frequency
levelshift_regressors_df_copy = levelshift_regressors_df.copy()
if resample_freq is not None:
levelshift_regressors_df_resample = levelshift_regressors_df_copy.resample(resample_freq, on=time_col).mean().reset_index()
else:
levelshift_regressors_df_resample = levelshift_regressors_df_copy
# Set time column to be the index of the dataframe for level shift regressors.
levelshift_regressors_df_resample.set_index(time_col, inplace=True)
# Concatenate regressors column-wise.
trend_df = pd.concat([trend_df, levelshift_regressors_df_resample], axis=1)
trend_df.index = df_resample[time_col]
self.trend_df = trend_df
# Estimates trend.
if trend_estimator not in ["ridge", "lasso", "ols"]:
warnings.warn("trend_estimator not in ['ridge', 'lasso', 'ols'], "
"estimating using ridge")
trend_estimator = 'ridge'
if trend_estimator == 'ols' and yearly_seasonality_order > 0:
warnings.warn("trend_estimator = 'ols' with year_seasonality_order > 0 may create "
"over-fitting, trend_estimator has been set to 'ridge'.")
trend_estimator = 'ridge'
fit_algorithm_dict = {
"ridge": RidgeCV,
"lasso": LassoCV,
"ols": LinearRegression
}
trend_model = fit_algorithm_dict[trend_estimator]().fit(trend_df.values, y.values)
self.trend_model = trend_model
self.trend_coef, self.trend_intercept = trend_model.coef_.ravel(), trend_model.intercept_.ravel()
# Fetches change point dates for reference as datetime format.
changepoint_dates = get_evenly_spaced_changepoints_dates(
df=df_resample,
time_col=time_col,
n_changepoints=potential_changepoint_n
)
# Gets the changepoint dates filtered by ``no_changepoint_proportion_from_begin`` and ``no_changepoint_proportion_from_end``.
if n_changepoints_within_range_begin < n_changepoints_within_range_end:
changepoint_dates = changepoint_dates.iloc[[0] + list(range(n_changepoints_within_range_begin + 1, n_changepoints_within_range_end + 1))]
else:
# Linear growth term only.
changepoint_dates = changepoint_dates.iloc[[0]]
# Calculates the minimal allowed change point index distance.
min_changepoint_index_distance = compute_min_changepoint_index_distance(
df=df_resample,
time_col=time_col,
n_changepoints=potential_changepoint_n,
min_distance_between_changepoints=actual_changepoint_min_distance
)
# Uses adaptive lasso to select change points.
if adaptive_lasso_initial_estimator not in ['ridge', 'lasso', 'ols']:
warnings.warn("adaptive_lasso_initial_estimator not in ['ridge', 'lasso', 'ols'], "
"estimating with ridge")
adaptive_lasso_initial_estimator = "ridge"
if adaptive_lasso_initial_estimator == trend_estimator:
# When ``adaptive_lasso_initial_estimator`` is the same as ``trend_estimator``, the
# estimated trend coefficients will be used to calculate the weights. The
# ``get_trend_changes_from_adaptive_lasso`` function recognizes ``initial_coef`` as
# `numpy.array` and calculates the weights directly.
trend_changepoints, self.adaptive_lasso_coef = get_trend_changes_from_adaptive_lasso(
x=trend_df.values,
y=y.values,
changepoint_dates=changepoint_dates,
initial_coef=self.trend_coef,
min_index_distance=min_changepoint_index_distance,
regularization_strength=regularization_strength
)
else:
# When ``adaptive_lasso_initial_estimator`` is different from ``trend_estimator``, the
# ``adaptive_lasso_initial_estimator`` as a `str` will be passed. The
# ``get_trend_changes_from_adaptive_lasso`` function recognizes ``initial_coef`` as
# `str` and calculates the initial estimator with the corresponding estimator first
# then calculates the weights.
trend_changepoints, self.adaptive_lasso_coef = get_trend_changes_from_adaptive_lasso(
x=trend_df.values,
y=y.values,
changepoint_dates=changepoint_dates,
initial_coef=adaptive_lasso_initial_estimator,
min_index_distance=min_changepoint_index_distance,
regularization_strength=regularization_strength
)
# Checks if the beginning date is picked as a change point. If yes, drop it, because we
# always include the growth term in our model.
trend_changepoints = [cp for cp in trend_changepoints if cp > max(df_resample[time_col][0], df[time_col][0])]
self.trend_changepoints = trend_changepoints
# logging
log_message(f"The detected trend change points are\n{trend_changepoints}", LoggingLevelEnum.INFO)
# Creates changepoints_dict for silverkite to use.
changepoints_dict = {
"method": "custom",
"dates": trend_changepoints
}
# Computes trend estimates for seasonality use.
if fast_trend_estimation:
# Fast calculation of trend estimation.
# Do not fit trend again on the original df.
# This is much faster when the original df has small frequencies.
# Uses linear interpolation on the trend fitted with the resampled df.
trend_estimation = np.matmul(
trend_df.values[:, :(len(trend_changepoints) + 1)],
trend_model.coef_[:(len(trend_changepoints) + 1)]
) + trend_model.intercept_
trend_estimation = pd.DataFrame({
time_col: df_resample[time_col],
"trend": trend_estimation
})
trend_estimation = trend_estimation.merge(
df[[time_col]],
on=time_col,
how="right"
)
trend_estimation["trend"].interpolate(inplace=True)
trend_estimation.index = df[time_col]
trend_estimation = trend_estimation["trend"]
else:
trend_estimation = estimate_trend_with_detected_changepoints(
df=df,
time_col=time_col,
value_col=value_col,
changepoints=trend_changepoints
)
self.trend_estimation = trend_estimation
result = {
"trend_feature_df": trend_df,
"trend_changepoints": trend_changepoints,
"changepoints_dict": changepoints_dict,
"trend_estimation": trend_estimation
}
return result
def find_seasonality_changepoints(
self,
df,
time_col,
value_col,
seasonality_components_df=pd.DataFrame({
"name": [
TimeFeaturesEnum.tod.value,
TimeFeaturesEnum.tow.value,
TimeFeaturesEnum.conti_year.value],
"period": [24.0, 7.0, 1.0],
"order": [3, 3, 5],
"seas_names": ["daily", "weekly", "yearly"]}),
resample_freq="H",
regularization_strength=0.6,
actual_changepoint_min_distance="30D",
potential_changepoint_distance=None,
potential_changepoint_n=50,
no_changepoint_distance_from_end=None,
no_changepoint_proportion_from_end=0.0,
trend_changepoints=None):
"""Finds the seasonality change points (defined as the time points where seasonality
magnitude changes, i.e., the time series becomes "fatter" or "thinner".)
Subtracts the estimated trend from the original time series first,
then uses regression-based regularization methods to select important seasonality
change points. Regressors are built from truncated Fourier series.
If you have run ``find_trend_changepoints`` before running ``find_seasonality_changepoints``
with the same df, the estimated trend will be automatically used for removing trend in
``find_seasonality_changepoints``.
Otherwise, ``find_trend_changepoints`` will be run automatically with the same parameters
as you passed to ``find_seasonality_changepoints``. If you do not want to use the same
parameters, run ``find_trend_changepoints`` with your desired parameter before calling
``find_seasonality_changepoints``.
The algorithm does an aggregation with a user-defined frequency, default hourly.
The regression features consists of ``potential_changepoint_n`` + 1 blocks of
predictors. The first block consists of Fourier series according to
``seasonality_components_df``, and other blocks are a copy of the first block
truncated at the corresponding potential change point.
If ``potential_changepoint_distance`` is not given, ``potential_changepoint_n``
potential change points are evenly distributed over the time period, else
``potential_changepoint_n`` is overridden by::
total_time_length / ``potential_changepoint_distance``
Users can specify either ``no_changepoint_proportion_from_end`` to specify what proportion
from the end of data they do not want changepoints, or ``no_changepoint_distance_from_end``
(overrides ``no_changepoint_proportion_from_end``) to specify how long from the end they
do not want change points.
Then all potential change points will be selected by adaptive lasso, with the initial
estimator specified by ``adaptive_lasso_initial_estimator``. The regularization strength
is specified by ``regularization_strength``, which lies between 0 and 1.
A rule-based guard function is applied at the end to ensure change points are not
too close, as specified by ``actual_changepoint_min_distance``.
Parameters
----------
df: `pandas.DataFrame`
The data df
time_col : `str`
Time column name in ``df``
value_col : `str`
Value column name in ``df``
seasonality_components_df : `pandas.DataFrame`
The df to generate seasonality design matrix, which is compatible with
``seasonality_components_df`` in
`~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints`
resample_freq : `DateOffset, Timedelta or str`, default "H".
The frequency to aggregate data.
Coarser aggregation leads to fitting longer term trends.
regularization_strength : `float` in [0, 1] or `None`, default 0.6.
The regularization for change points. Greater value implies fewer change points.
0 indicates all change points, and 1 indicates no change point.
If `None`, the turning parameter will be selected by cross-validation.
If a value is given, it will be used as the tuning parameter.
Here "None" is not recommended, because seasonality change has different levels,
and automatic selection by cross-validation may produce more change points than
desired. Practically, 0.6 is a good choice for most cases. Tuning around
0.6 is recommended.
actual_changepoint_min_distance : `DateOffset`, `Timedelta` or `str`, default "30D"
The minimal distance allowed between detected change points. If consecutive change points
are within this minimal distance, the one with smaller absolute change coefficient will
be dropped.
Note: maximal unit is 'D', i.e., you may use units no more than 'D' such as
'10D', '5H', '100T', '200S'. The reason is that 'W', 'M' or higher has either
cycles or indefinite number of days, thus is not parsable by pandas as timedelta.
potential_changepoint_distance : `DateOffset`, `Timedelta`, `str` or None, default None
The distance between potential change points.
If provided, will override the parameter ``potential_changepoint_n``.
Note: maximal unit is 'D', i.e., you may only use units no more than 'D' such as
'10D', '5H', '100T', '200S'. The reason is that 'W', 'M' or higher has either
cycles or indefinite number of days, thus is not parsable by pandas as timedelta.
potential_changepoint_n : `int`, default 50
Number of change points to be evenly distributed, recommended 1 per month, based
on the training data length.
no_changepoint_distance_from_end : `DateOffset`, `Timedelta`, `str` or None, default None
The length of time from the end of training data, within which no change point will be placed.
If provided, will override the parameter ``no_changepoint_proportion_from_end``.
Note: maximal unit is 'D', i.e., you may only use units no more than 'D' such as
'10D', '5H', '100T', '200S'. The reason is that 'W', 'M' or higher has either
cycles or indefinite number of days, thus is not parsable by pandas as timedelta.
no_changepoint_proportion_from_end : `float` in [0, 1], default 0.0.
``potential_changepoint_n`` change points will be placed evenly over the whole training period,
however, only change points that are not located within the last ``no_changepoint_proportion_from_end``
proportion of training period will be used for change point detection.
trend_changepoints : `list` or None
A list of user specified trend change points, used to estimated the trend to be removed
from the time series before detecting seasonality change points. If provided, the algorithm
will not check existence of detected trend change points or run ``find_trend_changepoints``,
but will use these change points directly for trend estimation.
Return
------
result : `dict`
result dictionary with keys:
``"seasonality_feature_df"`` : `pandas.DataFrame`
The augmented df for seasonality changepoint detection, in other words, the design matrix for
the regression model. Columns:
- "cos1_tod_daily": cosine daily seasonality regressor of first order at change point 0.
- "sin1_tod_daily": sine daily seasonality regressor of first order at change point 0.
- ...
- "cos1_conti_year_yearly": cosine yearly seasonality regressor of first order at
change point 0.
- "sin1_conti_year_yearly": sine yearly seasonality regressor of first order at
change point 0.
- ...
- "cos{daily_seasonality_order}_tod_daily_cp{potential_changepoint_n}" : cosine
daily seasonality regressor of {yearly_seasonality_order}th order at change point
{potential_changepoint_n}.
- "sin{daily_seasonality_order}_tod_daily_cp{potential_changepoint_n}" : sine
daily seasonality regressor of {yearly_seasonality_order}th order at change point
{potential_changepoint_n}.
- ...
- "cos{yearly_seasonality_order}_conti_year_yearly_cp{potential_changepoint_n}" : cosine
yearly seasonality regressor of {yearly_seasonality_order}th order at change point
{potential_changepoint_n}.
- "sin{yearly_seasonality_order}_conti_year_yearly_cp{potential_changepoint_n}" : sine
yearly seasonality regressor of {yearly_seasonality_order}th order at change point
{potential_changepoint_n}.
``"seasonality_changepoints"`` : `dict`[`list`[`datetime`]]
The dictionary of detected seasonality change points for each component.
Keys are component names, and values are list of change points.
``"seasonality_estimation"`` : `pandas.Series`
The estimated seasonality with detected seasonality change points.
The series has the same length as ``original_df``. Index is timestamp, and values
are the estimated seasonality at each timestamp.
The seasonality estimation is the estimated of seasonality effect with trend estimated
by `~greykite.algo.changepoint.adalasso.changepoints_utils.estimate_trend_with_detected_changepoints`
removed.
``"seasonality_components_df`` : `pandas.DataFrame`
The processed ``seasonality_components_df``. Daily component row is removed if
inferred frequency or aggregation frequency is at least one day.
"""
# Checks parameter rationality.
if potential_changepoint_n < 0:
raise ValueError("potential_changepoint_n can not be negative. "
"A large number such as 50 is recommended")
if df.dropna().shape[0] < 5:
raise ValueError("Change point detector does not work for less than "
"5 observations. Please increase sample size.")
if no_changepoint_proportion_from_end < 0 or no_changepoint_proportion_from_end > 1:
raise ValueError("``no_changepoint_proportion_from_end`` needs to be between 0 and 1.")
if no_changepoint_distance_from_end is not None:
check_freq_unit_at_most_day(no_changepoint_distance_from_end, "no_changepoint_distance_from_end")
data_length = pd.to_datetime(df[time_col].iloc[-1]) - pd.to_datetime(df[time_col].iloc[0])
no_changepoint_proportion_from_end = to_offset(no_changepoint_distance_from_end).delta / data_length
if potential_changepoint_distance is not None:
check_freq_unit_at_most_day(potential_changepoint_distance, "potential_changepoint_distance")
data_length = pd.to_datetime(df[time_col].iloc[-1]) - pd.to_datetime(df[time_col].iloc[0])
potential_changepoint_n = data_length // to_offset(potential_changepoint_distance).delta
if regularization_strength is None:
warnings.warn("regularization_strength is set to None. This will trigger cross-validation to "
"select the tuning parameter which might result in too many change points. "
"Keep the default value or tuning around it is recommended.")
if regularization_strength is not None and (regularization_strength < 0 or regularization_strength > 1):
raise ValueError("regularization_strength must be between 0.0 and 1.0.")
df[time_col] = pd.to_datetime(df[time_col])
# If user provides a list of trend change points, these points will be used to estimate trend.
if trend_changepoints is not None:
trend_estimation = estimate_trend_with_detected_changepoints(
df=df,
time_col=time_col,
value_col=value_col,
changepoints=trend_changepoints
)
self.trend_changepoints = trend_changepoints
self.trend_estimation = trend_estimation
self.original_df = df
self.time_col = time_col
self.value_col = value_col
self.y = df[value_col]
self.y.index = df[time_col]
# If user doesn't provide trend change points, the trend change points will be found automatically.
else:
# Checks if trend change point is available.
# Runs trend change point detection with default value if not.
compare_df = df.copy()
if time_col != self.time_col or value_col != self.value_col:
compare_df.rename({time_col: self.time_col, value_col: self.value_col}, axis=1, inplace=True)
if (self.original_df is not None
and self.original_df[[self.time_col, self.value_col]].equals(
compare_df[[self.time_col, self.value_col]])
and self.trend_estimation is not None):
# If the passed df is the same as ``self.original_df``, then the previous
# ``self.trend_estimation`` is to be subtracted from the time series.
trend_estimation = self.trend_estimation
warnings.warn("Trend changepoints are already identified, using past trend estimation. "
"If you would like to run trend change point detection again, "
"please call ``find_trend_changepoints`` with desired parameters "
"before calling ``find_seasonality_changepoints``.")
else:
# If the passed df is different from ``self.original_df``, then trend change point
# detection algorithm is run first, and trend estimation is calculated afterward.
# In this case, the parameters passed to ``find_seasonality_changepoints`` are also
# passed to ``find_trend_changepoint``.
# If you do not want the parameters passed, run ``find_trend_changepoints`` with
# desired parameters before calling ``find_seasonality_changepoints``.
trend_result = self.find_trend_changepoints(
df=df,
time_col=time_col,
value_col=value_col,
actual_changepoint_min_distance=actual_changepoint_min_distance,
no_changepoint_distance_from_end=no_changepoint_distance_from_end,
no_changepoint_proportion_from_end=no_changepoint_proportion_from_end
)
warnings.warn(f"Trend changepoints are not identified for the input dataframe, "
f"triggering trend change point detection with parameters"
f"actual_changepoint_min_distance={actual_changepoint_min_distance}\n"
f"no_changepoint_proportion_from_end={no_changepoint_proportion_from_end}\n"
f"no_changepoint_distance_from_end={no_changepoint_distance_from_end}\n"
f" Found trend change points\n{self.trend_changepoints}\n"
"If you would like to run trend change point detection with customized "
"parameters, please call ``find_trend_changepoints`` with desired parameters "
"before calling ``find_seasonality_changepoints``.")
trend_estimation = trend_result["trend_estimation"]
# Splits trend effects from time series.
df_without_trend = df.copy()
df_without_trend[value_col] -= trend_estimation.values
# Aggregates df.
df_resample = df_without_trend.resample(resample_freq, on=time_col).mean().reset_index()
df_resample = df_resample.dropna()
# Removes daily component from seasonality_components_df if data has minimum freq daily.
freq_at_least_day = (min(np.diff(df_resample[time_col]).astype("timedelta64[s]")) >= timedelta(days=1))
if (freq_at_least_day
and "daily" in seasonality_components_df["seas_names"].tolist()):
warnings.warn("Inferred minimum data frequency is at least 1 day, daily component is "
"removed from seasonality_components_df.")
seasonality_components_df = seasonality_components_df.loc[
seasonality_components_df["seas_names"] != "daily"]
# Builds seasonality feature df.
seasonality_df = build_seasonality_feature_df_with_changes(
df=df_resample,
time_col=time_col,
fs_components_df=seasonality_components_df,
changepoints_dict={
"method": "uniform",
"n_changepoints": potential_changepoint_n
}
)
# Eliminates change points from the end
# the generated seasonality_df has {``potential_changepoint_n`` + 1} blocks, where there
# are {sum_i(order of component i) * 2} columns consisting of the cosine and sine functions
# for each order for each component.
# The selection below selects the first {``n_changepoints_within_range`` + 1} columns,
# which corresponds to the regular block (first block) and the blocks that correspond
# to the change points that are within range.
n_changepoints_within_range = int(potential_changepoint_n * (1 - no_changepoint_proportion_from_end))
orders = seasonality_components_df["order"].tolist()
seasonality_df = seasonality_df.iloc[:, :(n_changepoints_within_range + 1) * sum(orders) * 2]
self.seasonality_df = seasonality_df
# Fetches change point dates for reference as datetime format.
changepoint_dates = get_evenly_spaced_changepoints_dates(
df=df,
time_col=time_col,
n_changepoints=potential_changepoint_n
)
# Gets the changepoint dates that are not within ``no_changepoint_proportion_from_end``.
changepoint_dates = changepoint_dates.iloc[0: n_changepoints_within_range + 1]
# Calculates the minimal allowed change point index distance.
min_changepoint_index_distance = compute_min_changepoint_index_distance(
df=df_resample,
time_col=time_col,
n_changepoints=potential_changepoint_n,
min_distance_between_changepoints=actual_changepoint_min_distance
)
seasonality_changepoints = get_seasonality_changes_from_adaptive_lasso(
x=seasonality_df.values,
y=df_resample[value_col].values,
changepoint_dates=changepoint_dates,
initial_coef="lasso",
seasonality_components_df=seasonality_components_df,
min_index_distance=min_changepoint_index_distance,
regularization_strength=regularization_strength
)
# Checks if the beginning date is picked as a change point. If yes, drop it, because we
# always include the overall seasonality term in our model.
for key in seasonality_changepoints.keys():
if df_resample[time_col][0] in seasonality_changepoints[key]:
seasonality_changepoints[key] = seasonality_changepoints[key][1:]
self.seasonality_changepoints = seasonality_changepoints
# logging
log_message(f"The detected seasonality changepoints are\n"
f"{pprint(seasonality_changepoints)}", LoggingLevelEnum.INFO)
# Performs a seasonality estimation for plotting purposes.
seasonality_estimation = estimate_seasonality_with_detected_changepoints(
df=df_without_trend,
time_col=time_col,
value_col=value_col,
seasonality_changepoints=seasonality_changepoints,
seasonality_components_df=seasonality_components_df
)
self.seasonality_estimation = seasonality_estimation
result = {
"seasonality_feature_df": seasonality_df,
"seasonality_changepoints": seasonality_changepoints,
"seasonality_estimation": seasonality_estimation,
"seasonality_components_df": seasonality_components_df
}
return result
def plot(
self,
observation=True,
observation_original=True,
trend_estimate=True,
trend_change=True,
yearly_seasonality_estimate=False,
adaptive_lasso_estimate=False,
seasonality_change=False,
seasonality_change_by_component=True,
seasonality_estimate=False,
plot=True):
"""Makes a plot to show the observations/estimations/change points.
In this function, component parameters specify if each component in the plot is
included or not. These are `bool` variables.
For those components that are set to True, their values will be replaced by the
corresponding data. Other components values will be set to None. Then these variables
will be fed into
`~greykite.algo.changepoint.adalasso.changepoints_utils.plot_change`
Parameters
----------
observation : `bool`
Whether to include observation
observation_original : `bool`
Set True to plot original observations, and False to plot aggregated observations.
No effect is ``observation`` is False
trend_estimate : `bool`
Set True to add trend estimation.
trend_change : `bool`
Set True to add change points.
yearly_seasonality_estimate : `bool`
Set True to add estimated yearly seasonality.
adaptive_lasso_estimate : `bool`
Set True to add adaptive lasso estimated trend.
seasonality_change : `bool`
Set True to add seasonality change points.
seasonality_change_by_component : `bool`
If true, seasonality changes will be plotted separately for different components,
else all will be in the same symbol.
No effect if ``seasonality_change`` is False
seasonality_estimate : `bool`
Set True to add estimated seasonality.
The seasonality if plotted around trend, so the actual seasonality shown is
trend estimation + seasonality estimation.
plot : `bool`, default True
Set to True to display the plot, and set to False to return the plotly figure object.
Returns
-------
None (if ``plot`` == True)
The function shows a plot.
fig : `plotly.graph_objects.Figure`
The plot object.
"""
# Adds observation
if observation:
if observation_original:
observation = self.original_df[self.value_col]
observation.index = self.original_df[self.time_col]
else:
observation = self.y
else:
observation = None
# Adds trend estimation
if trend_estimate:
trend_estimate = compute_fitted_components(
x=self.trend_df,
coef=self.trend_coef,
regex='^changepoint',
include_intercept=True,
intercept=self.trend_intercept
)
else:
trend_estimate = None
# Adds trend change points
if trend_change:
if self.trend_changepoints is None:
warnings.warn("You haven't run trend change point detection algorithm yet. "
"Please call find_trend_changepoints first.")
trend_change = self.trend_changepoints
else:
trend_change = None
# Adds yearly seasonality estimates
if yearly_seasonality_estimate:
yearly_seasonality_estimate = compute_fitted_components(
x=self.trend_df,
coef=self.trend_coef,
regex='^.*yearly.*$',
include_intercept=False
)
else:
yearly_seasonality_estimate = None
# Adds adaptive lasso trend estimates
if adaptive_lasso_estimate and self.adaptive_lasso_coef is not None:
adaptive_lasso_estimate = compute_fitted_components(
x=self.trend_df,
coef=self.adaptive_lasso_coef[1],
regex='^changepoint',
include_intercept=True,
intercept=self.adaptive_lasso_coef[0])
else:
adaptive_lasso_estimate = None
# Adds seasonality change points
if seasonality_change:
if self.seasonality_changepoints is None:
warnings.warn("You haven't run seasonality change point detection algorithm yet. "
"Please call find_seasonality_changepoints first.")
if seasonality_change_by_component:
seasonality_change = self.seasonality_changepoints
else:
seasonality_change = []
for key in self.seasonality_changepoints.keys():
seasonality_change += self.seasonality_changepoints[key]
else:
seasonality_change = None
# Adds seasonality estimates
if seasonality_estimate:
if self.seasonality_estimation is None:
warnings.warn("You haven't run seasonality change point detection algorithm yet. "
"Please call find_seasonality_changepoints first.")
seasonality_estimate = None
else:
seasonality_estimate = self.seasonality_estimation + self.trend_estimation
else:
seasonality_estimate = None
fig = plot_change(
observation=observation,
trend_estimate=trend_estimate,
trend_change=trend_change,
year_seasonality_estimate=yearly_seasonality_estimate,
adaptive_lasso_estimate=adaptive_lasso_estimate,
seasonality_change=seasonality_change,
seasonality_estimate=seasonality_estimate,
yaxis=self.value_col
)
if fig is not None and len(fig.data) > 0:
if plot:
fig.show()
else:
return fig
else:
warnings.warn("Figure is empty, at least one component has to be true.")
return None
def get_changepoints_dict(df, time_col, value_col, changepoints_dict):
"""The functions takes the ``changepoints_dict`` dictionary and returns the processed
``changepoints_dict``.
If "method" == "auto", the change point detection algorithm is run and the function returns
the ``changepoints_dict`` with "method"="custom" and automatically detected change points.
If "method" == "custom" or "uniform", the original ``changepoints_dict`` is returned.
Parameters
----------
df : `pandas.DataFrame`
The dataframe used to do change point detection.
time_col : `str`
The column name of time in ``df``.
value_col : `str`
The column name of values in ``df``.
changepoints_dict : `dict`
The ``changepoints_dict`` parameter that is fed into
`~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast` or
`~greykite.algo.forecast.silverkite.forecast_simple_silverkite.forecast_simple_silverkite`
It must have keys:
`"method"` : `str`, equals "custom", "uniform" or "auto"
Depending on `"method"`, it must have keys:
`"n_changepoints"` : `int`, when "method" == "uniform".
`"dates"` : `Iterable[Union[int, float, str, datetime]]`, when "method" == "custom"
When `"method"` == "auto", it can have optional keys that matches the parameters in
`~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_trend_changepoints`,
except ``df``, ``time_col`` and ``value_col``, and extra keys "dates", "combine_changepoint_min_distance"
and "keep_detected", which correspond to the three parameters "custom_changepoint_dates", "min_distance"
and "keep_detected" in `~greykite.algo.changepoint.adalasso.changepoints_utils.combine_detected_and_custom_trend_changepoints`.
In all three "method" cases, it can have optional keys:
"continuous_time_col": ``str`` or ``None``
Column to apply `growth_func` to, to generate changepoint features
Typically, this should match the growth term in the model
"growth_func": ``callable`` or ``None``
Growth function (scalar -> scalar). Changepoint features are created
by applying `growth_func` to "continuous_time_col" with offsets.
If None, uses identity function to use `continuous_time_col` directly
as growth term.
Returns
-------
changepoints_dict : `dict`
If "method" == "custom" or "method" == "uniform", the return is the original dictionary.
If "method" == "auto", the return is the dictionary with "method" = "custom" and
"dates" = detected_changepoints. Change point detection related keys and values are used
for change point detection, other keys and values will be included in the return dictionary.
changepoint_detector : `ChangepointDetector` or `None`
The ChangepointDetector class used for automatically trend changepoint detection if "method" == "auto",
otherwise None.
"""
if (changepoints_dict is not None
and "method" in changepoints_dict.keys()
and changepoints_dict["method"] == "auto"):
changepoint_detection_args = {
"df": df,
"time_col": time_col,
"value_col": value_col
}
changepoint_detection_keys = [
"yearly_seasonality_order",
"yearly_seasonality_change_freq",
"resample_freq",
"trend_estimator",
"adaptive_lasso_initial_estimator",
"regularization_strength",
"actual_changepoint_min_distance",
"potential_changepoint_distance",
"potential_changepoint_n",
"potential_changepoint_n_max",
"no_changepoint_distance_from_begin",
"no_changepoint_proportion_from_end",
"no_changepoint_distance_from_end",
"no_changepoint_proportion_from_end",
"shift_detector"
]
changepoints_dict_keys = [
"continuous_time_col",
"growth_func"
]
for key in changepoint_detection_keys:
if key in changepoints_dict.keys():
changepoint_detection_args[key] = changepoints_dict[key]
model = ChangepointDetector()
result = model.find_trend_changepoints(**changepoint_detection_args)
new_changepoints_dict = result["changepoints_dict"]
custom_changepoint_keys = []
if "dates" in changepoints_dict:
# Here we reuse the key "dates" which is used in "method"=="custom" as additional custom dates
# when "method"=="auto" to avoid having too many keys.
# Gets the custom changepoints.
custom_changepoints = changepoints_dict["dates"]
df_dates = pd.to_datetime(df[time_col])
min_date = min(df_dates)
max_date = max(df_dates)
custom_changepoints = pd.to_datetime(custom_changepoints)
custom_changepoints = [cp for cp in custom_changepoints if min_date < cp < max_date]
min_distance = changepoints_dict.get("combine_changepoint_min_distance", None)
# If ``combine_changepoint_min_distance`` is not set, try to set is with ``actual_changepoint_min_distance``.
if min_distance is None:
min_distance = changepoints_dict.get("actual_changepoint_min_distance", None)
# If ``keep_detected`` is not set, the default is False to keep custom changepoints.
keep_detected = changepoints_dict.get("keep_detected", False)
# Checks if custom changepoints are provided.
# If provided, combines the detected changepoints and custom changepoints.
custom_changepoint_keys = ["dates"]
if custom_changepoints is not None:
# Keys used in adding custom changepoints
custom_changepoint_keys = [
"dates",
"combine_changepoint_min_distance",
"keep_detected"
]
combined_changepoints = combine_detected_and_custom_trend_changepoints(
detected_changepoint_dates=new_changepoints_dict["dates"],
custom_changepoint_dates=custom_changepoints,
min_distance=min_distance,
keep_detected=keep_detected
)
# Logs info if the detected changepoints are altered.
if not set(combined_changepoints) == set(new_changepoints_dict["dates"]):
log_message(f"Custom trend changepoints have been added to the detected trend changepoints."
f" The final trend changepoints are {combined_changepoints}",
LoggingLevelEnum.INFO)
new_changepoints_dict["dates"] = combined_changepoints
for key in changepoints_dict_keys:
if key in changepoints_dict.keys():
new_changepoints_dict[key] = changepoints_dict[key]
unused_keys = [key for key in changepoints_dict.keys()
if key not in ["method"] + changepoints_dict_keys + changepoint_detection_keys + custom_changepoint_keys]
if unused_keys:
warnings.warn(f"The following keys in ``changepoints_dict`` are not recognized\n"
f"{unused_keys}")
return new_changepoints_dict, model
else:
return changepoints_dict, None
The provided code snippet includes necessary dependencies for implementing the `get_seasonality_changepoints` function. Write a Python function `def get_seasonality_changepoints( df, time_col, value_col, trend_changepoints_dict=None, trend_changepoint_dates=None, seasonality_changepoints_dict=None)` to solve the following problem:
Automatically detects seasonality change points. The function first converts changepoints_dict if "method" == "auto", then extracts trend changepoint dates from the dictionary and feeds them into ``find_seasonality_changepoints``. With the detected seasonality change points, the detection result dictionary is returned. Parameters ---------- df : `pandas.DataFrame` The data df. time_col : `str` The column name for time in ``df``. value_col : `str` The column name for value in ``df``. trend_changepoints_dict : `dict` or `None`, default `None` The ``changepoints_dict`` parameter in `~greykite.algo.changepoint.adalasso.changepoint_detector.get_changepoints_dict` trend_changepoint_dates : `list` or `None`, default `None` List of trend change point dates. The dates need to be parsable ty `pandas.to_datetime`. If given, trend change point detection will not be run and ``trend_changepoints_dict`` will have no effect. seasonality_changepoints_dict : `dict` or `None`, default `None` The keys are the parameter names of `~greykite.algo.changepoint.adalasso.changepoint_detector.find_seasonality_changepoints` The values are the corresponding desired values. Note ``df``, ``time_col``, ``value_col`` and ``trend_changepoints`` are auto populated, and do not need to be provided. Returns ------- result : `dict` The detected seasonality change points result dictionary as returned by `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints`.
Here is the function:
def get_seasonality_changepoints(
df,
time_col,
value_col,
trend_changepoints_dict=None,
trend_changepoint_dates=None,
seasonality_changepoints_dict=None):
"""Automatically detects seasonality change points.
The function first converts changepoints_dict if "method" == "auto", then extracts trend
changepoint dates from the dictionary and feeds them into ``find_seasonality_changepoints``.
With the detected seasonality change points, the detection result dictionary is returned.
Parameters
----------
df : `pandas.DataFrame`
The data df.
time_col : `str`
The column name for time in ``df``.
value_col : `str`
The column name for value in ``df``.
trend_changepoints_dict : `dict` or `None`, default `None`
The ``changepoints_dict`` parameter in
`~greykite.algo.changepoint.adalasso.changepoint_detector.get_changepoints_dict`
trend_changepoint_dates : `list` or `None`, default `None`
List of trend change point dates. The dates need to be parsable ty `pandas.to_datetime`.
If given, trend change point detection will not be run and ``trend_changepoints_dict``
will have no effect.
seasonality_changepoints_dict : `dict` or `None`, default `None`
The keys are the parameter names of
`~greykite.algo.changepoint.adalasso.changepoint_detector.find_seasonality_changepoints`
The values are the corresponding desired values.
Note ``df``, ``time_col``, ``value_col`` and ``trend_changepoints`` are auto populated,
and do not need to be provided.
Returns
-------
result : `dict`
The detected seasonality change points result dictionary as returned by
`~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints`.
"""
if trend_changepoint_dates is None:
# Runs trend change point detection algorithm if "method" == "auto", and returns
# changepoints_dict with "method" == "custom";
# Returns the original changepoints_dict if "method" == "uniform" or "custom";
# Returns None if the original changepoints_dict is None.
trend_changepoints_dict, _ = get_changepoints_dict(
df=df,
time_col=time_col,
value_col=value_col,
changepoints_dict=trend_changepoints_dict
)
# Extracts change point dates from the changepoints_dict.
# Returns None if the original changepoints_dict is None.
trend_changepoint_dates = get_changepoint_dates_from_changepoints_dict(
changepoints_dict=trend_changepoints_dict,
df=df,
time_col=time_col
)
# Prepares arguments for ``find_seasonality_changepoints`` function.
seasonality_changepoint_detection_args = {
"df": df,
"time_col": time_col,
"value_col": value_col
}
seasonality_changepoint_detection_keys = [
"seasonality_components_df",
"resample_freq",
"regularization_strength",
"actual_changepoint_min_distance",
"potential_changepoint_distance",
"potential_changepoint_n",
"no_changepoint_distance_from_end",
"no_changepoint_proportion_from_end"
]
if seasonality_changepoints_dict is not None:
for key in seasonality_changepoint_detection_keys:
if key in seasonality_changepoints_dict.keys():
seasonality_changepoint_detection_args[key] = seasonality_changepoints_dict[key]
seasonality_changepoint_detection_args["trend_changepoints"] = trend_changepoint_dates
# Runs ``find_seasonality_changepoints``.
cd = ChangepointDetector()
result = cd.find_seasonality_changepoints(**seasonality_changepoint_detection_args)
# Builds seasonality features with change points.
return result | Automatically detects seasonality change points. The function first converts changepoints_dict if "method" == "auto", then extracts trend changepoint dates from the dictionary and feeds them into ``find_seasonality_changepoints``. With the detected seasonality change points, the detection result dictionary is returned. Parameters ---------- df : `pandas.DataFrame` The data df. time_col : `str` The column name for time in ``df``. value_col : `str` The column name for value in ``df``. trend_changepoints_dict : `dict` or `None`, default `None` The ``changepoints_dict`` parameter in `~greykite.algo.changepoint.adalasso.changepoint_detector.get_changepoints_dict` trend_changepoint_dates : `list` or `None`, default `None` List of trend change point dates. The dates need to be parsable ty `pandas.to_datetime`. If given, trend change point detection will not be run and ``trend_changepoints_dict`` will have no effect. seasonality_changepoints_dict : `dict` or `None`, default `None` The keys are the parameter names of `~greykite.algo.changepoint.adalasso.changepoint_detector.find_seasonality_changepoints` The values are the corresponding desired values. Note ``df``, ``time_col``, ``value_col`` and ``trend_changepoints`` are auto populated, and do not need to be provided. Returns ------- result : `dict` The detected seasonality change points result dictionary as returned by `~greykite.algo.changepoint.adalasso.changepoint_detector.ChangepointDetector.find_seasonality_changepoints`. |
167,409 | from greykite.detection.common.ad_evaluation import soft_f1_score
from greykite.detection.common.ad_evaluation import soft_precision_score
from greykite.detection.common.ad_evaluation import soft_recall_score
from greykite.detection.detector.ad_utils import partial_return
from greykite.detection.detector.config import F1
from greykite.detection.detector.config import PRECISION
from greykite.detection.detector.config import RECALL
from greykite.detection.detector.detector import build_anomaly_percent_reward
from greykite.detection.detector.reward import Reward
OBJECTIVE_FUNC_MAP = {
F1: calc_soft_f1,
PRECISION: calc_soft_precision,
RECALL: calc_soft_recall
}
F1 = "F1"
RECALL = "RECALL"
PRECISION = "PRECISION"
def build_anomaly_percent_reward(anomaly_percent_dict):
"""This builds an reward function given an expected anomaly percent range.
This is the expected percent of anomalies in the data by user.
This is useful when the user does now know which points are anomalies,
but has some idea about what percent of data are anomalies.
The reward function constructed here will penalize for being far from the
center of the range specified by the user (``anomaly_percent_dict["range"]``)
and it will add an extra penalty for being outside that interval. The penalty
is specified in``anomaly_percent_dict["penalty"]``.
Parameters
----------
anomaly_percent_dict : `dict` or None, default None
If not None, a dictionary with items:
- ``"range"`` : `tuple`
We expect a tuple with two elements.
- ``"penalty"`` : `float`
A real number to specify the penalty of being outside the range
specified by user. It should be typically a negative value and it
could be set to ``float("-inf")`` to make this reward a restriction
while using it along with other rewards.
The dictionary is used to construct an reward which will be the reward in
the optimization is no reward is passed to the ``Detector`` class below.
If another reward is passed then this will be added to the passed reward.
The constructed reward based on ``anomaly_percent_dict`` penalizes
by the distance between the center of the ``"range"`` and predicted anomaly
percent as long as the predicted is within range.
For values outside the range an extra penalty given in`"penalty"`
will be applied.
If `"penalty"` is None, it will be set to -1.
If None, the default ``DEFAULT_ANOMALY_PERCENT_DICT`` will be used.
Returns
-------
result : `~greykite.detection.detector.reward.Reward`
The reward which reflects the information given in the input.
"""
min_percent = anomaly_percent_dict["range"][0]
max_percent = anomaly_percent_dict["range"][1]
target_percent = (min_percent + max_percent) / 2.0
def reward_func(data):
percent_anomaly = 100 * np.mean(data.y_pred)
diff = abs(percent_anomaly - target_percent) / 100.0
# `-diff` will be returned because we assume higher is better
return -diff
# Below intends to calculate which diffs using the above reward
# function transalte to the `percent_anomaly` being outside the
# specified range in `anomaly_percent_dict`
# Considering the above `reward_func` measures the diff from the mid-point
# of the range: we can deduce that maximum diff which still remains in
# the range is the length of the range.
# since the`reward_func` also divides the diff by 100, we also divide by
# 100.
max_acceptable_diff = (max_percent - min_percent) / (2 * 100.0)
penalty = anomaly_percent_dict["penalty"]
if penalty is None:
penalty = -1
# Below `min_unpenalized=-max_acceptable_diff` will ensure that `percent_anomaly`
# which is outside the specified range in `anomaly_percent_reward` will be
# penalized by an extra penalty
# with default -1, if not provided in `anomaly_percent_dict`
anomaly_percent_reward = Reward(
reward_func=reward_func,
min_unpenalized=-max_acceptable_diff,
max_unpenalized=float("inf"),
penalize_method=PenalizeMethod.ADDITIVE.value,
penalty=penalty)
return anomaly_percent_reward
class Reward:
"""Reward class which is to support very flexible set of rewards
used in optimization where an objective is to be optimized.
The main method for this class is `apply` which
is used when the reward is to be applied to data.
No assumption is made on the arguments of `apply` to keep this class very
generic.
This class enables two powerful mechanisms:
- taking a simple `reward_func` and construct a penalized version of that
- starting from existing objectives building more complex ones by adding /
multiplying / dividing them or use same operations with numbers.
Using these two mechanisms can enable use to support multi-objective problems.
For examples, in the context of anomaly detection if recall is to be optimized
subject to precision being at least 80 percent, then use can enable that by
def recall(y_true, y_pred):
# recall function implementation
...
def precision(y_true, y_pred):
# precision function implementation
...
reward =
Reward(reward_func=recall) +
Reward(
reward_func=precision,
min_unpenalized_metric=0.8,
max_unpenalized_metric=None,
penalty=-inf)
where the second part will cause the total sum of the objectives to be -inf
whenever precision is not in the desired range.
Also note that the "+" operation is defined in this class using the dunder
method `__add__`.
One can also combine objectives to achieve more complex objectives from existing ones. For example F1 can be easily expressed in terms of
precision and recall:
rec_obj = Reward(reward_func=recall)
prec_obj =Reward(reward_func=precision)
f1_obj = (2 * rec_obj * prec_obj) / (rec_obj + prec_obj)
The penalize mechanism on its own is useful for example in the context of
anomaly detection without labels, where we only have an idea about the
expected anomaly percentage in the data. In such a case an objective can be
constructed for optimization. See
`~greykite.detection.detector.detector.Detector`
init to see a construction of such an objective.
Parameters
----------
reward_func : callable
The reward function which will be used as the staring point and augmented
with extra logic depending on other input.
min_unpenalized : `float`, default `float("-inf")`
The minimum value of the reward function (`reward_func`) which will
remain un-penalized.
max_unpenalized : `float`, default `float("inf")`
The maximum value of the reward function (`reward_func`) which will
remain un-penalized.
penalize_method : `str`, default `PenalizeMethod.ADDITIVE.value`
The logic of using the penalty. The possibilities are given in
`~greykite.detection.detector.constants.PenalizeMethod`
penalty : `float` or None, default None
The penalty amount. If None, it will be mapped to 0 for additive and
1 for multiplicative.
Attributes
----------
None
"""
def __init__(
self,
reward_func,
min_unpenalized=float("-inf"),
max_unpenalized=float("inf"),
penalize_method=PenalizeMethod.ADDITIVE.value,
penalty=None):
self.reward_func = reward_func
self.min_unpenalized = min_unpenalized
self.max_unpenalized = max_unpenalized
self.penalize_method = penalize_method
if penalty is None:
if penalize_method == PenalizeMethod.ADDITIVE.value:
penalty = 0
else:
penalty = 1
self.penalty = penalty
def apply(
self,
*args,
**kwargs):
obj_value = self.reward_func(
*args,
**kwargs)
if (
obj_value > self.max_unpenalized or
obj_value < self.min_unpenalized):
if self.penalize_method == PenalizeMethod.ADDITIVE.value:
obj_value += self.penalty
elif self.penalize_method == PenalizeMethod.MULTIPLICATIVE.value:
obj_value *= self.penalty
elif self.penalize_method == PenalizeMethod.PENALTY_ONLY.value:
obj_value = self.penalty
elif self.penalize_method is None:
obj_value = self.penalty
else:
raise ValueError(
f"penalize_method {self.penalize_method.value} does not exist")
return obj_value
def __add__(self, other):
"""Addition of objects or an object with a number (scalar)."""
if isinstance(other, numbers.Number):
def reward_func(*args, **kwargs):
return (
self.apply(*args, **kwargs) +
other)
else:
def reward_func(*args, **kwargs):
return (
self.apply(*args, **kwargs) +
other.apply(*args, **kwargs))
return Reward(reward_func=reward_func)
def __mul__(self, other):
"""Multiplication of objects or an object with a number."""
if isinstance(other, numbers.Number):
def reward_func(*args, **kwargs):
return (
self.apply(*args, **kwargs) *
other)
else:
def reward_func(*args, **kwargs):
return (
self.apply(*args, **kwargs) *
other.apply(*args, **kwargs))
return Reward(reward_func=reward_func)
def __truediv__(self, other):
"""Division of objects or an object with a number."""
if isinstance(other, numbers.Number):
def reward_func(*args, **kwargs):
return (
self.apply(*args, **kwargs) /
other)
else:
def reward_func(*args, **kwargs):
return (
self.apply(*args, **kwargs) /
other.apply(*args, **kwargs))
return Reward(reward_func=reward_func)
# Below defines the above operators from right
# Addition and multiplication operators are commutative
# Division is an exception
def __radd__(self, other):
"""Right addition."""
return self.__add__(other)
def __rmul__(self, other):
"""Right multiplication."""
return self.__mul__(other)
def __rtruediv__(self, other):
"""Right division."""
if isinstance(other, numbers.Number):
def reward_func(*args, **kwargs):
return (
other /
self.apply(*args, **kwargs))
else:
def reward_func(*args, **kwargs):
return (
other.apply(*args, **kwargs) /
self.apply(*args, **kwargs))
return Reward(reward_func=reward_func)
def __str__(self):
"""Print method."""
reward_func_content = inspect.getsource(self.reward_func)
return (
f"\n reward_func:\n {reward_func_content} \n"
f"min_unpenalized: {self.min_unpenalized} \n"
f"max_unpenalized: {self.max_unpenalized} \n"
f"penalize_method: {self.penalize_method} \n"
f"penalty: {self.penalty} \n")
The provided code snippet includes necessary dependencies for implementing the `config_to_reward` function. Write a Python function `def config_to_reward(ad_config)` to solve the following problem:
Uses information in `ADConfig` to construct a reward function. The constructed reward function will be the sum of various rewards related to the objective and other information given in `ADConfig`. The relevant fields in `ADConfig` are: - target_anomaly_percent: An `anomaly_percent_range` will be created here with penalty of -1 for not hitting that range. The range will be the given `target_anomaly_percent` plus / minus 10 percent. - soft_window_size: This is used as a parameter in calculating objective and target_precision / target_recall (below). - objective: It is either of `F1`, `RECALL` and `PRECISION`. Soft versions will be used if `soft_window_size` is not None. - target_precision: This is the minimal precision we aim for. Any precision below this will be penalized by -1. - target_recall This is the minimal recall we aim for. Any recall below this will be penalized by -1. Parameters ---------- ad_config : `~greykite.detection.detector.config.ADConfig` See the linked dataclass (`ADConfig`) for details. Returns ------- result : `~greykite.detection.detector.reward.Reward` See the linked class (`Reward`) for details.
Here is the function:
def config_to_reward(ad_config):
"""Uses information in `ADConfig` to construct a reward function.
The constructed reward function will be the sum of various rewards
related to the objective and other information given in `ADConfig`.
The relevant fields in `ADConfig` are:
- target_anomaly_percent:
An `anomaly_percent_range` will be created here with penalty of -1
for not hitting that range. The range will be the given `target_anomaly_percent`
plus / minus 10 percent.
- soft_window_size:
This is used as a parameter in calculating objective and target_precision / target_recall (below).
- objective:
It is either of `F1`, `RECALL` and `PRECISION`.
Soft versions will be used if `soft_window_size` is not None.
- target_precision:
This is the minimal precision we aim for.
Any precision below this will be penalized by -1.
- target_recall
This is the minimal recall we aim for.
Any recall below this will be penalized by -1.
Parameters
----------
ad_config : `~greykite.detection.detector.config.ADConfig`
See the linked dataclass (`ADConfig`) for details.
Returns
-------
result : `~greykite.detection.detector.reward.Reward`
See the linked class (`Reward`) for details.
"""
# We initialize the reward function to return 0 regradless of input.
# This will be then added to other rewards based on `ADConfig`.
def reward_func(data):
return 0
reward = Reward(reward_func=reward_func)
if ad_config.target_anomaly_percent is not None:
anomaly_percent_upper = min(1.1 * ad_config.target_anomaly_percent, 100)
anomaly_percent_lower = max(0.9 * ad_config.target_anomaly_percent, 0)
anomaly_percent_range = (anomaly_percent_lower, anomaly_percent_upper)
anomaly_percent_dict = {
"range": anomaly_percent_range, "penalty": -1}
anomaly_percent_reward = build_anomaly_percent_reward(
anomaly_percent_dict)
reward = reward + anomaly_percent_reward
# Handles objective.
# Determine soft evaluation window.
window = 0
if ad_config.soft_window_size is not None:
window = ad_config.soft_window_size
if ad_config.objective in [F1, PRECISION, RECALL]:
def reward_func(data):
obj = OBJECTIVE_FUNC_MAP[ad_config.objective](
y_true=data.y_true,
y_pred=data.y_pred,
window=window)
if obj is not None:
return obj
return 0
reward = reward + Reward(reward_func=reward_func)
if ad_config.target_precision is not None:
def reward_func(data):
precision = OBJECTIVE_FUNC_MAP[PRECISION](
y_true=data.y_true,
y_pred=data.y_pred,
window=window)
if precision is not None:
return precision
return 0
reward = reward + Reward(
reward_func=reward_func,
min_unpenalized=ad_config.target_precision,
penalty=-1)
if ad_config.target_recall is not None:
def reward_func(data):
recall = OBJECTIVE_FUNC_MAP[RECALL](
y_true=data.y_true,
y_pred=data.y_pred,
window=window)
if recall is not None:
return recall
return 0
reward = reward + Reward(
reward_func=reward_func,
min_unpenalized=ad_config.target_recall,
penalty=-1)
return reward | Uses information in `ADConfig` to construct a reward function. The constructed reward function will be the sum of various rewards related to the objective and other information given in `ADConfig`. The relevant fields in `ADConfig` are: - target_anomaly_percent: An `anomaly_percent_range` will be created here with penalty of -1 for not hitting that range. The range will be the given `target_anomaly_percent` plus / minus 10 percent. - soft_window_size: This is used as a parameter in calculating objective and target_precision / target_recall (below). - objective: It is either of `F1`, `RECALL` and `PRECISION`. Soft versions will be used if `soft_window_size` is not None. - target_precision: This is the minimal precision we aim for. Any precision below this will be penalized by -1. - target_recall This is the minimal recall we aim for. Any recall below this will be penalized by -1. Parameters ---------- ad_config : `~greykite.detection.detector.config.ADConfig` See the linked dataclass (`ADConfig`) for details. Returns ------- result : `~greykite.detection.detector.reward.Reward` See the linked class (`Reward`) for details. |
167,410 | from functools import reduce
import pandas as pd
from greykite.common.constants import ANOMALY_COL
from greykite.common.constants import END_TIME_COL
from greykite.common.constants import START_TIME_COL
from greykite.common.constants import TIME_COL
from greykite.common.features.outlier import ZScoreOutlierDetector
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.detection.detector.constants import Z_SCORE_CUTOFF
The provided code snippet includes necessary dependencies for implementing the `partial_return` function. Write a Python function `def partial_return(func, k)` to solve the following problem:
For a given function ``func`` which returns multiple outputs accessible by ``[]`` e.g. python list or dictionary, it construct a new function which only returns part of the output given in position `k` where key can be a key or other index. Parameters ---------- func : callable A function which returns multiple output accessible by ``[]`` k : `int` or `str` A key or index which is implemented by ``[]`` on output of the input function ``func`` Returns ------- result : callable A function which only returns part of what the input ``func`` returns given in position ``[k]``. In the case that the key does not exist or index is out of bound, it returns None.
Here is the function:
def partial_return(func, k):
"""For a given function ``func`` which returns multiple outputs accessible by
``[]`` e.g. python list or dictionary, it construct a new function which only
returns part of the output given in position `k` where key can be a key or
other index.
Parameters
----------
func : callable
A function which returns multiple output accessible by ``[]``
k : `int` or `str`
A key or index which is implemented by ``[]`` on output of the
input function ``func``
Returns
-------
result : callable
A function which only returns part of what the input ``func`` returns given
in position ``[k]``. In the case that the key does not exist or index is
out of bound, it returns None.
"""
def func_k(*args, **kwargs):
res = func(*args, **kwargs)
# If result is a dictionary we check if key `k` exist,
# If so return the value for that key.
if type(res) == dict:
if k in res.keys():
return res[k]
# This is for the non-dict case eg `list`, `pandas.Series`, `np.array`.
# In this case we check if `k` is an `integer` and `res` has sufficient length.
# If so, we return the k-th element.
elif type(k) == int and len(res) > k:
return res[k]
# Otherwise it returns None.
return None
return func_k | For a given function ``func`` which returns multiple outputs accessible by ``[]`` e.g. python list or dictionary, it construct a new function which only returns part of the output given in position `k` where key can be a key or other index. Parameters ---------- func : callable A function which returns multiple output accessible by ``[]`` k : `int` or `str` A key or index which is implemented by ``[]`` on output of the input function ``func`` Returns ------- result : callable A function which only returns part of what the input ``func`` returns given in position ``[k]``. In the case that the key does not exist or index is out of bound, it returns None. |
167,411 | from functools import reduce
import pandas as pd
from greykite.common.constants import ANOMALY_COL
from greykite.common.constants import END_TIME_COL
from greykite.common.constants import START_TIME_COL
from greykite.common.constants import TIME_COL
from greykite.common.features.outlier import ZScoreOutlierDetector
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.detection.detector.constants import Z_SCORE_CUTOFF
The provided code snippet includes necessary dependencies for implementing the `vertical_concat_dfs` function. Write a Python function `def vertical_concat_dfs( df_list, join_cols, common_value_cols=[], different_value_cols=[])` to solve the following problem:
For a given set of datarfames with same columns in ``df_dict``, it will concat them vertically by using ``join_cols`` as joining columns. For ``common_value_cols`` it only extract the columns from the first dataframe. For ``different_value_cols`` it will extract them for each df and concat them horizontally. The new column names will have an added index based on their order in ``df_list``. Parameters ---------- df_list : `list` [`pandas.DataFrame`] A list of dataframes which are to be concatenated. join_cols : `list` [`str`] The list of columns which are to be used for joining. common_value_cols : `list` [`str`], default ``[]`` The list of column names for which we assume the values are the same across dataframes in ``df_list``. For these columns only data is pulled from the first dataframe appearing in ``df_list`.` different_value_cols : `list` [`str`], default ``[]`` The list of columns which are assumed to have potentially different values across dataframes. Returns ------- result : `pd.DataFrame` The resulting concatenated dataframe.
Here is the function:
def vertical_concat_dfs(
df_list,
join_cols,
common_value_cols=[],
different_value_cols=[]):
"""For a given set of datarfames with same columns
in ``df_dict``, it will concat them vertically by using
``join_cols`` as joining columns.
For ``common_value_cols`` it only extract the columns from the first
dataframe.
For ``different_value_cols`` it will extract them for each
df and concat them horizontally. The new column names will
have an added index based on their order in ``df_list``.
Parameters
----------
df_list : `list` [`pandas.DataFrame`]
A list of dataframes which are to be concatenated.
join_cols : `list` [`str`]
The list of columns which are to be used for joining.
common_value_cols : `list` [`str`], default ``[]``
The list of column names for which we assume the values are the
same across dataframes in ``df_list``. For these columns only data
is pulled from the first dataframe appearing in ``df_list`.`
different_value_cols : `list` [`str`], default ``[]``
The list of columns which are assumed to have potentially different
values across dataframes.
Returns
-------
result : `pd.DataFrame`
The resulting concatenated dataframe.
"""
new_df_list = []
for i, df in enumerate(df_list):
df = df.copy()
# only keeps the `common_value_cols` from the first df
if i != 0:
for col in common_value_cols:
del df[col]
for col in different_value_cols:
df[f"{col}{i}"] = df[col]
del df[col]
new_df_list.append(df)
concat_df = reduce(
lambda left, right: pd.merge(left, right, on=join_cols),
new_df_list)
return concat_df | For a given set of datarfames with same columns in ``df_dict``, it will concat them vertically by using ``join_cols`` as joining columns. For ``common_value_cols`` it only extract the columns from the first dataframe. For ``different_value_cols`` it will extract them for each df and concat them horizontally. The new column names will have an added index based on their order in ``df_list``. Parameters ---------- df_list : `list` [`pandas.DataFrame`] A list of dataframes which are to be concatenated. join_cols : `list` [`str`] The list of columns which are to be used for joining. common_value_cols : `list` [`str`], default ``[]`` The list of column names for which we assume the values are the same across dataframes in ``df_list``. For these columns only data is pulled from the first dataframe appearing in ``df_list`.` different_value_cols : `list` [`str`], default ``[]`` The list of columns which are assumed to have potentially different values across dataframes. Returns ------- result : `pd.DataFrame` The resulting concatenated dataframe. |
167,412 | from functools import reduce
import pandas as pd
from greykite.common.constants import ANOMALY_COL
from greykite.common.constants import END_TIME_COL
from greykite.common.constants import START_TIME_COL
from greykite.common.constants import TIME_COL
from greykite.common.features.outlier import ZScoreOutlierDetector
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.detection.detector.constants import Z_SCORE_CUTOFF
The provided code snippet includes necessary dependencies for implementing the `add_new_params_to_records` function. Write a Python function `def add_new_params_to_records( new_params, records=None)` to solve the following problem:
For a list of records (each being a `dict`) and a set of parameters each having a list of potential values, it expands each record in all possible ways based on all possible values for each param in ``new_params``. Then it returns all possible augmented records in a list. Parameters ---------- new_params : `dict` {`str`: `list`} A dictionary with keys representing (new) variables and values for each key being the possible values for that variable. records : `list` [`dict`] or None, default None List of existing records which are to be augmented with all possible combinations of the new variables. If None, it is assigned to ``[{}]`` which means we start from an empty record. Returns ------- expanded_records : `list` [`dict`] The resulting list of augmented records.
Here is the function:
def add_new_params_to_records(
new_params,
records=None):
"""For a list of records (each being a `dict`) and a set of parameters
each having a list of potential values, it expands each record in all possible
ways based on all possible values for each param in ``new_params``.
Then it returns all possible augmented records in a list.
Parameters
----------
new_params : `dict` {`str`: `list`}
A dictionary with keys representing (new) variables and values for each
key being the possible values for that variable.
records : `list` [`dict`] or None, default None
List of existing records which are to be augmented with all possible
combinations of the new variables. If None, it is assigned to ``[{}]``
which means we start from an empty record.
Returns
-------
expanded_records : `list` [`dict`]
The resulting list of augmented records.
"""
if records is None:
records = [{}]
def add_new_param_values(name, values, records):
# `records` is a list and it is copied so that its not altered
# Note that `deepcopy` is not possible for lists
# Therefore inside the for loop we copy each param (`dict`)
records = records.copy()
expanded_records = []
for param in records:
for v in values:
# Copies to avoid over-write
expanded_param = param.copy()
expanded_param.update({name: v})
expanded_records.append(expanded_param)
return expanded_records
expanded_records = records.copy()
for name, values in new_params.items():
expanded_records = add_new_param_values(
name=name,
values=values,
records=expanded_records)
return expanded_records | For a list of records (each being a `dict`) and a set of parameters each having a list of potential values, it expands each record in all possible ways based on all possible values for each param in ``new_params``. Then it returns all possible augmented records in a list. Parameters ---------- new_params : `dict` {`str`: `list`} A dictionary with keys representing (new) variables and values for each key being the possible values for that variable. records : `list` [`dict`] or None, default None List of existing records which are to be augmented with all possible combinations of the new variables. If None, it is assigned to ``[{}]`` which means we start from an empty record. Returns ------- expanded_records : `list` [`dict`] The resulting list of augmented records. |
167,413 | from functools import reduce
import pandas as pd
from greykite.common.constants import ANOMALY_COL
from greykite.common.constants import END_TIME_COL
from greykite.common.constants import START_TIME_COL
from greykite.common.constants import TIME_COL
from greykite.common.features.outlier import ZScoreOutlierDetector
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.detection.detector.constants import Z_SCORE_CUTOFF
TIME_COL = "ts"
START_TIME_COL = "start_time"
END_TIME_COL = "end_time"
ANOMALY_COL = "is_anomaly"
The provided code snippet includes necessary dependencies for implementing the `get_anomaly_df` function. Write a Python function `def get_anomaly_df( df, time_col=TIME_COL, anomaly_col=ANOMALY_COL)` to solve the following problem:
Computes anomaly dataframe from a labeled ``df``. Parameters ---------- df : `pandas.DataFrame` A data frame which includes minimally - the timestamp column (``time_col``) - the anomaly column (``anomaly_col``). time_col : `str` or None The column name of timestamps in ``df``. If None, it is set to `~greykite.common.constants.TIME_COL`. anomaly_col : `str` or None The column name of anomaly labels in ``df``. ``True`` indicates anomalous data. ``False`` indicates non-anomalous data. If None, it is set to `~greykite.detection.detector.constants.ANOMALY_COL`. Returns ------- anomaly_df : `pandas.DataFrame` The dataframe that contains anomaly info. It should have - the anomaly start column "start_time" `~greykite.detection.detector.constants.ANOMALY_START_TIME`. - the anomaly end column "end_time" `~greykite.detection.detector.constants.ANOMALY_END_TIME`. Both should be inclusive.
Here is the function:
def get_anomaly_df(
df,
time_col=TIME_COL,
anomaly_col=ANOMALY_COL):
"""Computes anomaly dataframe from a labeled ``df``.
Parameters
----------
df : `pandas.DataFrame`
A data frame which includes minimally
- the timestamp column (``time_col``)
- the anomaly column (``anomaly_col``).
time_col : `str` or None
The column name of timestamps in ``df``.
If None, it is set to
`~greykite.common.constants.TIME_COL`.
anomaly_col : `str` or None
The column name of anomaly labels in ``df``.
``True`` indicates anomalous data.
``False`` indicates non-anomalous data.
If None, it is set to
`~greykite.detection.detector.constants.ANOMALY_COL`.
Returns
-------
anomaly_df : `pandas.DataFrame`
The dataframe that contains anomaly info.
It should have
- the anomaly start column "start_time"
`~greykite.detection.detector.constants.ANOMALY_START_TIME`.
- the anomaly end column "end_time"
`~greykite.detection.detector.constants.ANOMALY_END_TIME`.
Both should be inclusive.
"""
# Copies `df` by resetting the index to avoid alteration to input df
df = df.reset_index(drop=True)
# When all rows are True/ anomalies
if df[anomaly_col].all():
start_index = [0]
end_index = [df.index[-1]]
# When all rows are False/ not anomalies
elif not df[anomaly_col].any():
start_index = []
end_index = []
else:
df[anomaly_col] = df[anomaly_col].astype(int)
df[f"{anomaly_col}_diff"] = df[anomaly_col].diff()
start_index = df.index[df[f"{anomaly_col}_diff"] == 1.0].tolist()
end_index = df.index[df[f"{anomaly_col}_diff"] == -1.0].tolist()
end_index = [index-1 for index in end_index] # to make end points inclusive
# The first entry of df is an anomaly
if df.iloc[0][anomaly_col]:
start_index.insert(0, 0)
# The last entry of df is an anomaly
if df.iloc[df.index[-1]][anomaly_col]:
end_index.append(df.index[-1])
anomaly_df = pd.DataFrame({
START_TIME_COL: df.iloc[start_index][time_col].values,
END_TIME_COL: df.iloc[end_index][time_col].values
})
return anomaly_df | Computes anomaly dataframe from a labeled ``df``. Parameters ---------- df : `pandas.DataFrame` A data frame which includes minimally - the timestamp column (``time_col``) - the anomaly column (``anomaly_col``). time_col : `str` or None The column name of timestamps in ``df``. If None, it is set to `~greykite.common.constants.TIME_COL`. anomaly_col : `str` or None The column name of anomaly labels in ``df``. ``True`` indicates anomalous data. ``False`` indicates non-anomalous data. If None, it is set to `~greykite.detection.detector.constants.ANOMALY_COL`. Returns ------- anomaly_df : `pandas.DataFrame` The dataframe that contains anomaly info. It should have - the anomaly start column "start_time" `~greykite.detection.detector.constants.ANOMALY_START_TIME`. - the anomaly end column "end_time" `~greykite.detection.detector.constants.ANOMALY_END_TIME`. Both should be inclusive. |
167,414 | from functools import reduce
import pandas as pd
from greykite.common.constants import ANOMALY_COL
from greykite.common.constants import END_TIME_COL
from greykite.common.constants import START_TIME_COL
from greykite.common.constants import TIME_COL
from greykite.common.features.outlier import ZScoreOutlierDetector
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.detection.detector.constants import Z_SCORE_CUTOFF
class LoggingLevelEnum(Enum):
"""Valid types of logging levels available to use."""
CRITICAL = 50
ERROR = 40
WARNING = 30
INFO = 20
DEBUG = 10
NOTSET = 0
def log_message(message, level=LoggingLevelEnum.INFO):
"""Adds a message to logger.
Parameters
----------
message : `any`
The message to be added to logger.
level : `Enum`
One of the levels in the `~greykite.common.enums.LoggingLevelEnum`.
"""
if level.name not in list(LoggingLevelEnum.__members__):
raise ValueError(f"{level} not found, it must be a member of the LoggingLevelEnum class.")
logger.log(level.value, message)
The provided code snippet includes necessary dependencies for implementing the `optimize_df_with_constraints` function. Write a Python function `def optimize_df_with_constraints( df, objective_col, constraint_col, constraint_value)` to solve the following problem:
Function that solves the following constrained optimization problem. maximize ``df``[``objective_col``] subject to ``df``[``constraint_col``] >= ``constraint_value``. However, unlike traditional constrained optimization, which returns None when no values satisfy the constraint, this function maximizes ``df``[``constraint_col``]. Note that in this case, since the constraint is not satisfied, this will get as close as possible to the ``constraint_value``. To understand the reasoning behind this choice, it is helpful to think about ``objective_col`` as precision and ``constraint_col`` as recall. Thus, the optimization problem becomes: maximize precision subject to recall >= target_recall. The algorithm proceeds as follows: 1. Find rows which satisfy ``df``[``constraint_col``] >= ``constraint_value``. 1.1. If such rows exist, find rows that have highest ``df``[``objective_col``]. 1.1.1. Find rows that have highest ``df``[``constraint_col``]. 1.1.2. Among these, find row that maximize ``df``[``objective_col``]. This solves for multiple ties, if any. 1.2. If no such rows exist, 1.2.1. Find rows that maximizes ``df``[``constraint_col``]. 1.2.2. Among these, find row that maximize ``df``[``objective_col``]. This solves for multiple ties, if any. 2. Return corresponding ``df`` row. Parameters ---------- df : `pandas.DataFrame` A data frame which includes minimally - the objective column (``objective_col``) - the constraint column (``constraint_col``). objective_col : `str` The column name of the variable to be optimized. constraint_col : `str` The column name of the constraint variable. constraint_value : `float` The value of the constraint. Returns ------- optimal_dict : `dict` The row of the ``df`` which is the optimal of the corresponding optimization problem..
Here is the function:
def optimize_df_with_constraints(
df,
objective_col,
constraint_col,
constraint_value):
"""Function that solves the following constrained optimization problem.
maximize ``df``[``objective_col``]
subject to ``df``[``constraint_col``] >= ``constraint_value``.
However, unlike traditional constrained optimization, which returns None when no
values satisfy the constraint, this function maximizes ``df``[``constraint_col``].
Note that in this case, since the constraint is not satisfied, this will get
as close as possible to the ``constraint_value``.
To understand the reasoning behind this choice, it is helpful to think
about ``objective_col`` as precision and ``constraint_col`` as recall. Thus,
the optimization problem becomes:
maximize precision subject to recall >= target_recall.
The algorithm proceeds as follows:
1. Find rows which satisfy ``df``[``constraint_col``] >= ``constraint_value``.
1.1. If such rows exist, find rows that have highest ``df``[``objective_col``].
1.1.1. Find rows that have highest ``df``[``constraint_col``].
1.1.2. Among these, find row that maximize ``df``[``objective_col``].
This solves for multiple ties, if any.
1.2. If no such rows exist,
1.2.1. Find rows that maximizes ``df``[``constraint_col``].
1.2.2. Among these, find row that maximize ``df``[``objective_col``].
This solves for multiple ties, if any.
2. Return corresponding ``df`` row.
Parameters
----------
df : `pandas.DataFrame`
A data frame which includes minimally
- the objective column (``objective_col``)
- the constraint column (``constraint_col``).
objective_col : `str`
The column name of the variable to be optimized.
constraint_col : `str`
The column name of the constraint variable.
constraint_value : `float`
The value of the constraint.
Returns
-------
optimal_dict : `dict`
The row of the ``df`` which is the optimal of the
corresponding optimization problem..
"""
df = df.copy()
constraint_match_indices = df[constraint_col] >= constraint_value
if constraint_match_indices.any():
log_message(f"Values satisfying the constraint are found.\n"
f"Solving the following optimization problem:\n"
f"Maximize {objective_col} subject to {constraint_col} >= {constraint_value}.",
LoggingLevelEnum.INFO)
df = df[constraint_match_indices]
df = df[df[objective_col] == max(df[objective_col])]
df = df[df[constraint_col] == max(df[constraint_col])]
else:
log_message(f"No values satisfy the constraint.\n"
f"Maximizing ``constraint_col`` ({constraint_col}) so that it is as "
f"close as possible to the ``constraint_value`` ({constraint_value}).",
LoggingLevelEnum.INFO)
df = df[df[constraint_col] == max(df[constraint_col])]
df = df[df[objective_col] == max(df[objective_col])]
return df.iloc[-1].to_dict() | Function that solves the following constrained optimization problem. maximize ``df``[``objective_col``] subject to ``df``[``constraint_col``] >= ``constraint_value``. However, unlike traditional constrained optimization, which returns None when no values satisfy the constraint, this function maximizes ``df``[``constraint_col``]. Note that in this case, since the constraint is not satisfied, this will get as close as possible to the ``constraint_value``. To understand the reasoning behind this choice, it is helpful to think about ``objective_col`` as precision and ``constraint_col`` as recall. Thus, the optimization problem becomes: maximize precision subject to recall >= target_recall. The algorithm proceeds as follows: 1. Find rows which satisfy ``df``[``constraint_col``] >= ``constraint_value``. 1.1. If such rows exist, find rows that have highest ``df``[``objective_col``]. 1.1.1. Find rows that have highest ``df``[``constraint_col``]. 1.1.2. Among these, find row that maximize ``df``[``objective_col``]. This solves for multiple ties, if any. 1.2. If no such rows exist, 1.2.1. Find rows that maximizes ``df``[``constraint_col``]. 1.2.2. Among these, find row that maximize ``df``[``objective_col``]. This solves for multiple ties, if any. 2. Return corresponding ``df`` row. Parameters ---------- df : `pandas.DataFrame` A data frame which includes minimally - the objective column (``objective_col``) - the constraint column (``constraint_col``). objective_col : `str` The column name of the variable to be optimized. constraint_col : `str` The column name of the constraint variable. constraint_value : `float` The value of the constraint. Returns ------- optimal_dict : `dict` The row of the ``df`` which is the optimal of the corresponding optimization problem.. |
167,415 | from functools import reduce
import pandas as pd
from greykite.common.constants import ANOMALY_COL
from greykite.common.constants import END_TIME_COL
from greykite.common.constants import START_TIME_COL
from greykite.common.constants import TIME_COL
from greykite.common.features.outlier import ZScoreOutlierDetector
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.detection.detector.constants import Z_SCORE_CUTOFF
The provided code snippet includes necessary dependencies for implementing the `validate_volatility_features` function. Write a Python function `def validate_volatility_features( volatility_features_list, valid_features=None)` to solve the following problem:
Removes duplicate values from ``volatility_features_list`` and validates the features against ``valid_features``. Parameters ---------- volatility_features_list: `list` [`list` [`str`]] Lists of volatility features used to optimize anomaly detection performance. Valid volatility feature column names are either columns of ``df`` or belong to `~greykite.common.constants.TimeFeaturesEnum`. valid_features: `list` [`str`] or None ``volatility_features_list`` is validated against this list. Returns ------- validated_features_list: `list` [`list` [`str`]] List of validated volatility features.
Here is the function:
def validate_volatility_features(
volatility_features_list,
valid_features=None):
"""Removes duplicate values from ``volatility_features_list``
and validates the features against ``valid_features``.
Parameters
----------
volatility_features_list: `list` [`list` [`str`]]
Lists of volatility features used to optimize anomaly detection performance.
Valid volatility feature column names are
either columns of ``df`` or belong to
`~greykite.common.constants.TimeFeaturesEnum`.
valid_features: `list` [`str`] or None
``volatility_features_list`` is validated against this list.
Returns
-------
validated_features_list: `list` [`list` [`str`]]
List of validated volatility features.
"""
# Removes duplicates
validated_features_list = []
for features in volatility_features_list:
# Removes duplicates within a set of features
features = list(dict.fromkeys(features))
# Removes duplicates among the feature sets
if features not in validated_features_list:
validated_features_list.append(features)
# Checks features against the provided features in ``valid_features``
if valid_features is not None:
all_features = sum(validated_features_list, [])
unique_features = set(all_features)
missing_features = unique_features - set(valid_features)
if missing_features:
raise ValueError(f"Unknown feature(s) ({missing_features}) in `volatility_features_list`. "
f"Valid features are: [{valid_features}].")
return validated_features_list | Removes duplicate values from ``volatility_features_list`` and validates the features against ``valid_features``. Parameters ---------- volatility_features_list: `list` [`list` [`str`]] Lists of volatility features used to optimize anomaly detection performance. Valid volatility feature column names are either columns of ``df`` or belong to `~greykite.common.constants.TimeFeaturesEnum`. valid_features: `list` [`str`] or None ``volatility_features_list`` is validated against this list. Returns ------- validated_features_list: `list` [`list` [`str`]] List of validated volatility features. |
167,416 | from functools import reduce
import pandas as pd
from greykite.common.constants import ANOMALY_COL
from greykite.common.constants import END_TIME_COL
from greykite.common.constants import START_TIME_COL
from greykite.common.constants import TIME_COL
from greykite.common.features.outlier import ZScoreOutlierDetector
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.detection.detector.constants import Z_SCORE_CUTOFF
def get_timestamp_ceil(ts, freq):
"""Returns the smallest timestamp that is greater than or equal to `ts`
and is also a multiple of the `freq`.
Assume hourly frequency i.e. `freq` = "H". Then
If `ts` = 1:30, this function returns 2:00.
If `ts` = 1:00, this function returns 1:00.
Parameters
----------
ts: `str`
Timestamp in `str` format.
freq: `str`
Pandas timeseries frequency string.
Returns
-------
dt_ceil: `pd.Timestamp`
The smallest timestamp that is greater than or equal to `ts`
and is also a multiple of the `freq`.
"""
dt = pd.to_datetime(ts)
try:
return dt.ceil(freq=freq)
# `pd.Timestamp.ceil` raises a ValueError when `freq` is a non-fixed frequency
# e.g. weekly ("W-MON"), business day ("B) or monthly ("M")
except ValueError:
return dt.to_period(freq).to_timestamp(how="E").normalize()
The provided code snippet includes necessary dependencies for implementing the `get_timestamp_floor` function. Write a Python function `def get_timestamp_floor(ts, freq)` to solve the following problem:
Returns the largest timestamp that is smaller than or equal to `ts` and is also a multiple of the `freq`. Assume hourly frequency i.e. `freq` = "H". Then If `ts` = 1:30, this function returns 1:00. If `ts` = 1:00, this function returns 1:00. Parameters ---------- ts: `str` Timestamp in `str` format. freq: `str` Pandas timeseries frequency string. Returns ------- dt_floor: `pd.Timestamp` The largest timestamp that is smaller than or equal to `ts` and is also a multiple of the `freq`.
Here is the function:
def get_timestamp_floor(ts, freq):
"""Returns the largest timestamp that is smaller than or equal to `ts`
and is also a multiple of the `freq`.
Assume hourly frequency i.e. `freq` = "H". Then
If `ts` = 1:30, this function returns 1:00.
If `ts` = 1:00, this function returns 1:00.
Parameters
----------
ts: `str`
Timestamp in `str` format.
freq: `str`
Pandas timeseries frequency string.
Returns
-------
dt_floor: `pd.Timestamp`
The largest timestamp that is smaller than or equal to `ts`
and is also a multiple of the `freq`.
"""
dt_ceil = get_timestamp_ceil(ts, freq)
# If input `ts` is not on the `freq` offset, `dt_ceil` > `ts`.
# e.g. Assume `freq` = "H". If `ts` = 1:30, then `dt_ceil` = 2:00.
# Then `dt_ceil` is reduced one `freq` offset to get `dt_floor`.
if dt_ceil > pd.to_datetime(ts):
return dt_ceil - pd.tseries.frequencies.to_offset(freq)
else:
return dt_ceil | Returns the largest timestamp that is smaller than or equal to `ts` and is also a multiple of the `freq`. Assume hourly frequency i.e. `freq` = "H". Then If `ts` = 1:30, this function returns 1:00. If `ts` = 1:00, this function returns 1:00. Parameters ---------- ts: `str` Timestamp in `str` format. freq: `str` Pandas timeseries frequency string. Returns ------- dt_floor: `pd.Timestamp` The largest timestamp that is smaller than or equal to `ts` and is also a multiple of the `freq`. |
167,417 | from functools import reduce
import pandas as pd
from greykite.common.constants import ANOMALY_COL
from greykite.common.constants import END_TIME_COL
from greykite.common.constants import START_TIME_COL
from greykite.common.constants import TIME_COL
from greykite.common.features.outlier import ZScoreOutlierDetector
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
from greykite.detection.detector.constants import Z_SCORE_CUTOFF
def get_canonical_anomaly_df(
anomaly_df,
freq,
start_time_col=START_TIME_COL,
end_time_col=END_TIME_COL):
"""Validates and merges overlapping anomaly periods in anomaly dataframe.
Also standardizes column names.
For example, consider the following input ``anomaly_df``:
start_time end_time
"2020-01-01" "2020-01-02"
"2020-01-03" "2020-01-05"
For a daily dataset i.e. ``freq = "D"``, the end time "2020-01-02" and start time
"2020-01-03" are consecutive. Hence, in the output the ``anomaly_df`` is converted to
start_time end_time
"2020-01-01" "2020-01-05"
However, for an hourly dataset i.e. ``freq = "H"`` the end time "2020-01-02" and start time
"2020-01-03" are not consecutive. Hence, the output is the same as the input ``anomaly_df``.
Parameters
---------
anomaly_df : `pandas.DataFrame`
The dataframe that contains anomaly info.
It should at least have
- the anomaly start column ``start_time_col``
- the anomaly end column ``end_time_col``
Both are assumed to be inclusive of the start and end times.
freq : `str`
Frequency of the timeseries represented in ``anomaly_df``.
This is used to determine if the timestamps in the ``anomaly_df`` are consecutive.
start_time_col : `str` or None
The column name containing anomaly start timestamps in ``anomaly_df``.
If None, it is set to
`~greykite.detection.detector.constants.START_TIME_COL`.
end_time_col : `str` or None
The column name containing anomaly end timestamps in ``anomaly_df``.
If None, it is set to
`~greykite.detection.detector.constants.END_TIME_COL`.
Returns
-------
anomaly_df : `pandas.DataFrame`
Standardized anomaly dataframe.
It should have
- the anomaly start column "start_time"
`~greykite.detection.detector.constants.ANOMALY_START_TIME`.
- the anomaly end column "end_time"
`~greykite.detection.detector.constants.ANOMALY_END_TIME`.
Both should be inclusive.
The anomaly periods are non-overlapping and sorted from earliest to latest.
"""
df = anomaly_df.copy()
df[start_time_col] = pd.to_datetime(df[start_time_col])
df[end_time_col] = pd.to_datetime(df[end_time_col])
df = df.sort_values(by=[start_time_col]).reset_index(drop=True)
row_num = df.shape[0]-1
for row in range(row_num):
start_time = df[start_time_col][row]
end_time = df[end_time_col][row]
if start_time > end_time:
raise ValueError(f"Anomaly 'start_time' ({start_time}) is after the anomaly 'end_time' ({end_time}).")
# Merges anomalies
next_start_time = df[start_time_col][row+1]
next_end_time = df[end_time_col][row+1]
num_periods = (next_start_time.to_period(freq=freq) - end_time.to_period(freq=freq)).n
# Start times and end times are inclusive for anomaly df. Hence, the anomaly periods should
# be merged if the number of periods between the anomalies are less than 1.
# e.g. The anomaly periods ["2020-01-01", "2020-01-02"] and ["2020-01-03", "2020-01-04"]
# should be merged into a single anomaly period ["2020-01-01", "2020-01-04"].
if num_periods <= 1:
df[start_time_col][row+1] = start_time
if next_end_time < end_time:
df[end_time_col][row+1] = end_time
df = df.drop_duplicates(
subset=[start_time_col],
keep="last"
).rename({
start_time_col: START_TIME_COL,
end_time_col: END_TIME_COL
}, axis=1).reset_index(drop=True)
return df
START_TIME_COL = "start_time"
END_TIME_COL = "end_time"
class ZScoreOutlierDetector(BaseOutlierDetector):
"""This is a class for detecting one-dimensional outliers using z-score (based on the normal distribution).
See https://en.wikipedia.org/wiki/Standard_score as a reference.
This is a child of `~greykite.common.features.outlier.ZScoreOutlierDetector`,
which already implements a few processing steps which are useful across
various outlier detection methods:
- `remove_na`: removing NAs
- `trim`: trimming the data. This is useful for example when using z-score
- `diff_from_baseline`: fitting a simple baseline and differencing the input from baseline.
For this method:
- `DetectionResult.scores` are defined as:
The difference of the value with trimmed mean divided by the trimmed standard deviation
- `DetectionResult.is_outlier` are defined as: scores which are off by more than `z_score_cutoff`.
Parameters
----------
z_score_cutoff : `float`, default `Z_SCORE_CUTOFF`
The normal distribution cut-off used to decide outliers.
Attribute
---------
fitted_param: `dict` or None, default None
This is updated after `self.fit` is run on data.
This dictionary stores:
- "trimmed_mean": `float`
Trimmed mean of the input fit data (after trimming).
- "trimmed_sd": `float`
Trimmed standard deviation of the input fit data (after trimming).
Other Parameters and Attributes:
See `~greykite.common.features.outlier.BaseOutlierDetector` docstring.
"""
def __init__(
self,
z_score_cutoff=Z_SCORE_CUTOFF,
trim_percent=TRIM_PERCENT,
diff_method=MOVING_MEDIAN):
"""See class attributes for details on parameters / attributes."""
self.z_score_cutoff = z_score_cutoff
super().__init__(
trim_percent=trim_percent,
diff_method=diff_method)
def fit_logic(self, y_ready_to_fit):
"""The logic of the fit.
This is an abstract method of the base class:
`~greykite.common.features.outlier.BaseOutlierDetector`
and it is implemented for z-score here.
Parameters
----------
y_ready_to_fit: `pandas.series`
The series which is used for fitting.
Returns
-------
None.
Updates
self.fitted_param: `dict`
Parameters of the z-score model.
- "trimmed_mean"
- "trimmed_sd"
self.lower_bound: `float`
The lower bound to decide if a point is an outlier.
self.lower_bound: `float`
The upper bound to decide is a point is an outlier.
Indirectly updates (via `self.fit` method of the parent class):
self.y_diffed: `pandas.Series` or None, default None
self.y_na_removed: `pandas.Series` or None, default None
self.y_trimmed: `pandas.Series` or None, default None
self.y_ready_to_fit: `pandas.Series` or None, default None
"""
# Calculates z-scores and identifies points with:"
# Pseudo code: abs(z-score) > `Z_SCORE_CUTOFF` as outliers.
trimmed_mean = np.mean(y_ready_to_fit)
trimmed_sd = np.std(y_ready_to_fit)
self.lower_bound = trimmed_mean - trimmed_sd * self.z_score_cutoff
self.upper_bound = trimmed_mean + trimmed_sd * self.z_score_cutoff
self.fitted_param = {
"trimmed_mean": trimmed_mean,
"trimmed_sd": trimmed_sd}
def detect_logic(self, y_new):
"""The logic of outlier detection, after `fit` is done.
This method uses the fit information to decide which points are
outliers and what should be their score.
This is an abstract method of the base class:
`~greykite.common.features.outlier.BaseOutlierDetector`
and it is implemented for z-score here.
For this method: scores are defined as the mean difference divided by the standard deviation
(as prescribed z-score).
Parameters
----------
y_new: `pandas.series`
A series of floats. This is the input series to be labeled.
Returns
-------
result: `~greykite.common.features.outlier.DetectionResult`
Includes the outlier detection results (see the data class attributes).
"""
scores = pd.Series([0] * len(y_new), dtype=float)
is_outlier = pd.Series([False] * len(y_new))
# If trimmed sd is zero or not defined, we will not detect any outlier and return.
if not (self.fitted_param["trimmed_sd"] > 0):
return DetectionResult(scores=scores, is_outlier=is_outlier)
scores = (y_new - self.fitted_param["trimmed_mean"]) / self.fitted_param["trimmed_sd"]
# Boolean series to denote outliers.
is_outlier = np.abs(scores) > self.z_score_cutoff
return DetectionResult(scores=scores, is_outlier=is_outlier)
Z_SCORE_CUTOFF = 20.0
The provided code snippet includes necessary dependencies for implementing the `get_anomaly_df_from_outliers` function. Write a Python function `def get_anomaly_df_from_outliers( df, time_col, value_col, freq, z_score_cutoff=Z_SCORE_CUTOFF, trim_percent=1.0)` to solve the following problem:
This function identifies extreme values as outliers based on z-scores. A normal distribution will be fit on ``value_col`` of input df, and the time points with corresponding values that satisfy abs(z-scores) > ``Z_SCORE_CUTOFF`` will be considered as outliers. The function will then construct ``anomaly_df`` based on identified outliers. If trimming is specified via ``trim_percent`` to be non-zero, data is trimmed in symmetric fashion (removes high and low values) before calculating mean and variance of the standard normal. This is done to deal with large outliers. Parameters ---------- df : `pandas.DataFrame` The dataframe with ``time_col`` and ``value_col``. time_col : `str` The column name of timestamps in ``df``. value_col : `str` The column name of values in ``df`` on which z-scores will be calculated to identify outliers. freq : `str` Pandas timeseries frequency string, e.g. "H", "D", etc. See https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases. z_score_cutoff : `float`, default ``Z_SCORE_CUTOFF`` Z score cutoff for outlier detection. trim_percent : `float`, default 1.0 Trimming percent for calculating the variance. The function first removes this amount of data in symmetric fashion from both ends and then it calculates the mean and the variance. Returns ------- anomaly_df : `pandas.DataFrame` The dataframe that contains anomaly info based on identified outliers. It should have - the anomaly start column "start_time" `~greykite.common.constants.START_TIME_COL`. - the anomaly end column "end_time" `~greykite.common.constants.END_TIME_COL. Both are inclusive.
Here is the function:
def get_anomaly_df_from_outliers(
df,
time_col,
value_col,
freq,
z_score_cutoff=Z_SCORE_CUTOFF,
trim_percent=1.0):
"""This function identifies extreme values as outliers based on z-scores.
A normal distribution will be fit on ``value_col`` of input df,
and the time points with corresponding values that satisfy abs(z-scores) >
``Z_SCORE_CUTOFF`` will be considered as outliers.
The function will then construct ``anomaly_df`` based on identified outliers.
If trimming is specified via ``trim_percent`` to be non-zero,
data is trimmed in symmetric fashion (removes high and low values) before
calculating mean and variance of the standard normal.
This is done to deal with large outliers.
Parameters
----------
df : `pandas.DataFrame`
The dataframe with ``time_col`` and ``value_col``.
time_col : `str`
The column name of timestamps in ``df``.
value_col : `str`
The column name of values in ``df`` on which z-scores will be calculated to identify outliers.
freq : `str`
Pandas timeseries frequency string, e.g. "H", "D", etc.
See https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases.
z_score_cutoff : `float`, default ``Z_SCORE_CUTOFF``
Z score cutoff for outlier detection.
trim_percent : `float`, default 1.0
Trimming percent for calculating the variance.
The function first removes this amount of data in symmetric fashion from
both ends and then it calculates the mean and the variance.
Returns
-------
anomaly_df : `pandas.DataFrame`
The dataframe that contains anomaly info based on identified outliers.
It should have
- the anomaly start column "start_time"
`~greykite.common.constants.START_TIME_COL`.
- the anomaly end column "end_time"
`~greykite.common.constants.END_TIME_COL.
Both are inclusive.
"""
if df.empty:
return None
if time_col not in df.columns:
raise ValueError(f"`df` does not have `time_col` with name {time_col}.")
if value_col not in df.columns:
raise ValueError(f"`df` does not have `value_col` with name {value_col}.")
df[time_col] = pd.to_datetime(df[time_col])
# Calculates z-scores after trimming (if trimming is not 0)
# and identifies points with abs(z-score) > `Z_SCORE_CUTOFF` as outliers.
detect_outlier = ZScoreOutlierDetector(
diff_method=None,
trim_percent=trim_percent,
z_score_cutoff=z_score_cutoff)
detect_outlier.fit(df[value_col])
fitted = detect_outlier.fitted
cond_outlier = fitted.is_outlier
# Extracts time points when outliers occur.
outlier_points = df.loc[cond_outlier, time_col].reset_index(drop=True)
anomaly_df = pd.DataFrame(columns=[START_TIME_COL, END_TIME_COL])
if len(outlier_points) > 0:
anomaly_df[START_TIME_COL] = outlier_points
anomaly_df[END_TIME_COL] = anomaly_df[START_TIME_COL]
anomaly_df = get_canonical_anomaly_df(
anomaly_df=anomaly_df,
freq=freq)
return anomaly_df | This function identifies extreme values as outliers based on z-scores. A normal distribution will be fit on ``value_col`` of input df, and the time points with corresponding values that satisfy abs(z-scores) > ``Z_SCORE_CUTOFF`` will be considered as outliers. The function will then construct ``anomaly_df`` based on identified outliers. If trimming is specified via ``trim_percent`` to be non-zero, data is trimmed in symmetric fashion (removes high and low values) before calculating mean and variance of the standard normal. This is done to deal with large outliers. Parameters ---------- df : `pandas.DataFrame` The dataframe with ``time_col`` and ``value_col``. time_col : `str` The column name of timestamps in ``df``. value_col : `str` The column name of values in ``df`` on which z-scores will be calculated to identify outliers. freq : `str` Pandas timeseries frequency string, e.g. "H", "D", etc. See https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases. z_score_cutoff : `float`, default ``Z_SCORE_CUTOFF`` Z score cutoff for outlier detection. trim_percent : `float`, default 1.0 Trimming percent for calculating the variance. The function first removes this amount of data in symmetric fashion from both ends and then it calculates the mean and the variance. Returns ------- anomaly_df : `pandas.DataFrame` The dataframe that contains anomaly info based on identified outliers. It should have - the anomaly start column "start_time" `~greykite.common.constants.START_TIME_COL`. - the anomaly end column "end_time" `~greykite.common.constants.END_TIME_COL. Both are inclusive. |
167,418 | import json
from dataclasses import dataclass
from typing import Any
from typing import List
from typing import Optional
from greykite.common.python_utils import assert_equal
from greykite.framework.templates.autogen.forecast_config import from_bool
from greykite.framework.templates.autogen.forecast_config import from_float
from greykite.framework.templates.autogen.forecast_config import from_int
from greykite.framework.templates.autogen.forecast_config import from_list_float
from greykite.framework.templates.autogen.forecast_config import from_list_list_str
from greykite.framework.templates.autogen.forecast_config import from_none
from greykite.framework.templates.autogen.forecast_config import from_str
from greykite.framework.templates.autogen.forecast_config import from_union
class ADConfig:
"""Config for providing parameters to the Anomaly Detection library."""
volatility_features_list: Optional[List[List[str]]] = None
"""Set of volatility features used to optimize anomaly detection performance."""
coverage_grid: Optional[List[float]] = None
"""A set of coverage values to optimize anomaly detection performance.
Optimum coverage is chosen among this list."""
ape_grid: Optional[List[float]] = None
"""A set of absolute percentage error (APE) threshold values to optimize anomaly detection performance."""
sape_grid: Optional[List[float]] = None
"""A set of symmetric absolute percentage error (SAPE) threshold values to optimize anomaly detection performance."""
min_admissible_value: Optional[float] = None
"""Lowest admissible value for the obtained confidence intervals."""
max_admissible_value: Optional[float] = None
"""Highest admissible value for the obtained confidence intervals."""
objective: Optional[str] = None
"""The main objective for optimization. It can be either of: F1, PRECISION or RECALL."""
target_precision: Optional[float] = None
"""Minimum precision to achieve during AD optimization in a labeled data."""
target_recall: Optional[float] = None
"""Minimum recall to achieve during AD optimization in a labeled data."""
soft_window_size: Optional[int] = None
"""Window size for soft precision, recall and f1 in a labeled data."""
target_anomaly_percent: Optional[float] = None
"""Desired anomaly percent during AD optimization of an unlabeled data (0-100 scale)."""
variance_scaling: Optional[bool] = None
"""The variance scaling method in ridge / linear regression takes into account
(1) the degrees of freedom of the model; (2) the standard error from the coefficients,
hence will provide more accurate variance estimate / prediction intervals."""
def from_dict(obj: Any) -> 'ADConfig':
"""Converts a dictionary to the corresponding instance of the `ADConfig` class.
Raises ValueError if the input is not a dictionary.
"""
if not isinstance(obj, dict):
raise ValueError(f"The input ({obj}) is not a dictionary.")
volatility_features_list = from_union([from_list_list_str, from_none], obj.get("volatility_features_list"))
coverage_grid = from_union([from_list_float, from_none], obj.get("coverage_grid"))
ape_grid = from_union([from_list_float, from_none], obj.get("ape_grid"))
sape_grid = from_union([from_list_float, from_none], obj.get("sape_grid"))
min_admissible_value = from_union([from_float, from_none], obj.get("min_admissible_value"))
max_admissible_value = from_union([from_float, from_none], obj.get("max_admissible_value"))
objective = from_union([from_str, from_none], obj.get("objective"))
target_precision = from_union([from_float, from_none], obj.get("target_precision"))
target_recall = from_union([from_float, from_none], obj.get("target_recall"))
soft_window_size = from_union([from_int, from_none], obj.get("soft_window_size"))
target_anomaly_percent = from_union([from_float, from_none], obj.get("target_anomaly_percent"))
variance_scaling = from_union([from_bool, from_none], obj.get("variance_scaling"))
return ADConfig(
volatility_features_list=volatility_features_list,
coverage_grid=coverage_grid,
ape_grid=ape_grid,
sape_grid=sape_grid,
min_admissible_value=min_admissible_value,
max_admissible_value=max_admissible_value,
objective=objective,
target_precision=target_precision,
target_recall=target_recall,
soft_window_size=soft_window_size,
target_anomaly_percent=target_anomaly_percent,
variance_scaling=variance_scaling
)
def to_dict(self) -> dict:
"""Converts an instance of the `ADConfig` class to its dictionary format."""
result = dict()
result["volatility_features_list"] = from_union(
[from_list_list_str, from_none],
self.volatility_features_list)
result["coverage_grid"] = from_union(
[from_list_float, from_none],
self.coverage_grid)
result["ape_grid"] = from_union(
[from_list_float, from_none],
self.ape_grid)
result["sape_grid"] = from_union(
[from_list_float, from_none],
self.sape_grid)
result["min_admissible_value"] = from_union(
[from_float, from_none],
self.min_admissible_value)
result["max_admissible_value"] = from_union(
[from_float, from_none],
self.max_admissible_value)
result["objective"] = from_union(
[from_str, from_none],
self.objective)
result["target_precision"] = from_union(
[from_float, from_none],
self.target_precision)
result["target_recall"] = from_union(
[from_float, from_none],
self.target_recall)
result["soft_window_size"] = from_union(
[from_int, from_none],
self.soft_window_size)
result["target_anomaly_percent"] = from_union(
[from_float, from_none],
self.target_anomaly_percent)
result["variance_scaling"] = from_union(
[from_bool, from_none],
self.variance_scaling)
return result
def from_json(obj: Any) -> 'ADConfig':
"""Converts a json string to the corresponding instance of the `ADConfig` class.
Raises ValueError if the input is not a json string.
"""
try:
ad_dict = json.loads(obj)
except Exception:
raise ValueError(f"The input ({obj}) is not a json string.")
return ADConfig.from_dict(ad_dict)
def to_json(self) -> str:
"""Converts an instance of the `ADConfig` class to its json string format."""
ad_dict = self.to_dict()
return json.dumps(ad_dict)
def assert_equal(
actual,
expected,
ignore_list_order=False,
rel=1e-5,
dict_path="",
ignore_keys=None,
**kwargs):
"""Generic equality function that raises an ``AssertionError`` if the objects are not equal.
Notes
-----
Works with pandas.DataFrame, pandas.Series, numpy.ndarray, str, int, float,
bool, None, or a dictionary or list of such items, with arbitrary nesting
of dictionaries and lists.
Does not check equivalence of functions, or work with nested numpy arrays.
Parameters
----------
actual : `pandas.DataFrame`, `pandas.Series`, `numpy.array`, `str`, `int`,
`float`, `bool`, `None`, or a dictionary or list of such items
Actual value.
expected : `pandas.DataFrame`, `pandas.Series`, `numpy.array`, `str`, `int`,
`float`, `bool`, `None`, or a dictionary or list of such items
Expected value to compare against.
ignore_list_order : `bool`, optional, default False
If True, lists are considered equal if they contain the same elements. This option is valid
only if the list can be sorted (all elements can be compared to each other).
If False, lists are considered equal if they contain the same elements in the same order.
rel : `float`, optional, default 1e-5
To check int and float, passed to ``rel`` argument of `pytest.approx`.
To check numpy arrays, passed to ``rtol`` argument of
`numpy.testing.assert_allclose`.
To check pandas dataframe, series, and index, passed to ``rtol`` argument of
`pandas.testing.assert_frame_equal`, `pandas.testing.assert_series_equal`,
`pandas.testing.assert_index_equal`.
dict_path : `str`, optional, default ""
Location within nested dictionary of the original call to this function.
User should not set this parameter.
ignore_keys : `dict`, optional, default None
Keys to ignore in equality comparison. This only applies if
`expected` is a dictionary.
Does not compare the values of these keys. However,
still returns false if the key is not present.
Can be a nested dictionary. Terminal keys are those whose values should
not be compared.
If the expected value is an nested dictionary, this dictionary can
also be nested, with the same structure.
For example, if expected:
expected = {
"k1": {
"k1": 1,
"k2": [1, 2, 3],
}
"k2": {
"k1": "abc"
}
}
Then the following ``ignore_keys`` will ignore
dict["k1"]["k1"] and dict["k2"]["k1"] in the comparison.
ignore_keys = {
"k1": {
"k1": False # The value can be anything, the keys determine what's ignored
},
"k2": {
"k1": "skip" # The value can be anything, the keys determine what's ignored
}
}
This ``ignore_keys`` will ignore
dict["k1"] and dict["k2"]["k1"] in the comparison. "k1" is
ignored entirely because its value is not a dictionary.
ignore_keys = {
"k1": None # The value can be anything, the keys determine what's ignored
"k2": {
"k1": None
}
}
kwargs : keyword args, optional
Keyword args to pass to `pandas.testing.assert_frame_equal`,
`pandas.testing.assert_series_equal`.
Raises
------
AssertionError
If actual does not match expected.
"""
# a message to add to all error messages
location = f"dictionary location: {dict_path}"
message = "" if dict_path == "" else f"Error at {location}.\n"
if expected is None:
if actual is not None:
raise AssertionError(f"{message}Actual should be None, found {actual}.")
elif isinstance(expected, pd.DataFrame):
if not isinstance(actual, pd.DataFrame):
raise AssertionError(f"{message}Actual should be a pandas DataFrame, found {actual}.")
# leverages pandas assert function and add `message` to the error
try:
assert_frame_equal(
actual,
expected,
rtol=rel,
**kwargs)
except AssertionError as e:
import sys
raise type(e)(f"{e}{message}").with_traceback(sys.exc_info()[2])
elif isinstance(expected, pd.Series):
if not isinstance(actual, pd.Series):
raise AssertionError(f"{message}Actual should be a pandas Series, found {actual}.")
try:
assert_series_equal(
actual,
expected,
rtol=rel,
**kwargs)
except AssertionError as e:
import sys
raise type(e)(f"{message}{e}").with_traceback(sys.exc_info()[2])
elif isinstance(expected, pd.Index):
if not isinstance(actual, pd.Index):
raise AssertionError(f"{message}Actual should be a pandas Index, found {actual}.")
try:
assert_index_equal(
actual,
expected,
rtol=rel,
**kwargs)
except AssertionError as e:
import sys
raise type(e)(f"{message}{e}").with_traceback(sys.exc_info()[2])
elif isinstance(expected, np.ndarray):
if not isinstance(actual, np.ndarray):
raise AssertionError(f"{message}Actual should be a numpy array, found {actual}.")
np.testing.assert_allclose(
actual,
expected,
rtol=rel,
err_msg=message)
elif isinstance(expected, (list, tuple)):
if not isinstance(actual, (list, tuple)):
raise AssertionError(f"{message}Actual should be a list or tuple, found {actual}.")
if not len(actual) == len(expected):
raise AssertionError(f"{message}Lists have different length. "
f"Actual: {actual}. Expected: {expected}.")
if ignore_list_order:
# order doesn't matter
actual = sorted(actual)
expected = sorted(expected)
# element-wise comparison
if ignore_keys is not None:
warnings.warn(f"At {location}. `ignore_keys` is {ignore_keys}, but found a list. "
f"No keys will be ignored")
for (item_actual, item_expected) in zip(actual, expected):
assert_equal(
item_actual,
item_expected,
ignore_list_order=ignore_list_order,
rel=rel,
dict_path=dict_path,
ignore_keys=None,
**kwargs)
elif isinstance(expected, dict):
# dictionaries are equal if their keys and values are equal
if not isinstance(actual, dict):
raise AssertionError(f"{message}Actual should be a dict, found {actual}.")
# checks the keys
if not actual.keys() == expected.keys():
raise AssertionError(f"{message}Dict keys do not match. "
f"Actual: {actual.keys()}. Expected: {expected.keys()}.")
# check the next level of nesting, if not ignored by `ignore_keys`
for k, expected_item in expected.items():
if ignore_keys is not None and k in ignore_keys.keys():
if isinstance(ignore_keys[k], dict):
# specific keys within the value are ignored
new_ignore_keys = ignore_keys[k]
else:
# the entire value is ignored
continue
else:
# the key is not ignored, so its value should be fully compared
new_ignore_keys = None
# appends the key to the path
new_path = f"{dict_path}['{k}']" if dict_path != "" else f"dict['{k}']"
assert_equal(
actual[k],
expected_item,
ignore_list_order=ignore_list_order,
rel=rel,
dict_path=new_path,
ignore_keys=new_ignore_keys,
**kwargs)
elif isinstance(expected, (int, float)):
if not isinstance(actual, (int, float)):
raise AssertionError(f"{message}Actual should be numeric, found {actual}.")
if not math.isclose(actual, expected, rel_tol=rel, abs_tol=0.0):
raise AssertionError(f"{message}Actual does not match expected. "
f"Actual: {actual}. Expected: {expected}.")
else:
if actual != expected:
raise AssertionError(f"{message}Actual does not match expected. "
f"Actual: {actual}. Expected: {expected}.")
The provided code snippet includes necessary dependencies for implementing the `assert_equal_ad_config` function. Write a Python function `def assert_equal_ad_config( ad_config_1: ADConfig, ad_config_2: ADConfig)` to solve the following problem:
Asserts equality between two instances of `ADConfig`. Raises a ValueError in case of a parameter mismatch. Parameters ---------- ad_config_1: `ADConfig` First instance of the :class:`~greykite.detection.detector.config.ADConfig` for comparing. ad_config_2: `ADConfig` Second instance of the :class:`~greykite.detection.detector.config.ADConfig` for comparing. Raises ------- AssertionError If `ADConfig`s do not match, else returns None.
Here is the function:
def assert_equal_ad_config(
ad_config_1: ADConfig,
ad_config_2: ADConfig):
"""Asserts equality between two instances of `ADConfig`.
Raises a ValueError in case of a parameter mismatch.
Parameters
----------
ad_config_1: `ADConfig`
First instance of the
:class:`~greykite.detection.detector.config.ADConfig` for comparing.
ad_config_2: `ADConfig`
Second instance of the
:class:`~greykite.detection.detector.config.ADConfig` for comparing.
Raises
-------
AssertionError
If `ADConfig`s do not match, else returns None.
"""
if not isinstance(ad_config_1, ADConfig):
raise ValueError(f"The input ({ad_config_1}) is not a member of 'ADConfig' class.")
if not isinstance(ad_config_2, ADConfig):
raise ValueError(f"The input ({ad_config_2}) is not a member of 'ADConfig' class.")
assert_equal(ad_config_1.to_dict(), ad_config_2.to_dict()) | Asserts equality between two instances of `ADConfig`. Raises a ValueError in case of a parameter mismatch. Parameters ---------- ad_config_1: `ADConfig` First instance of the :class:`~greykite.detection.detector.config.ADConfig` for comparing. ad_config_2: `ADConfig` Second instance of the :class:`~greykite.detection.detector.config.ADConfig` for comparing. Raises ------- AssertionError If `ADConfig`s do not match, else returns None. |
167,419 | import functools
import warnings
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from sklearn import metrics
from greykite.detection.common.ad_evaluation_utils import compute_range_based_score
from greykite.detection.common.ad_evaluation_utils import prepare_anomaly_ranges
INPUT_COL_NAME = "input_col"
The provided code snippet includes necessary dependencies for implementing the `validate_categorical_input` function. Write a Python function `def validate_categorical_input(score_func)` to solve the following problem:
Decorator function to validate categorical scoring function input, and unifies the input type to pandas.Series.
Here is the function:
def validate_categorical_input(score_func):
"""Decorator function to validate categorical scoring function input,
and unifies the input type to pandas.Series.
"""
@functools.wraps(score_func)
def score_func_wrapper(
y_true: Union[list, np.array, pd.Series, pd.DataFrame],
y_pred: Union[list, np.array, pd.Series, pd.DataFrame],
*args,
**kwargs) -> np.array:
actual = pd.DataFrame(y_true).reset_index(drop=True)
pred = pd.DataFrame(y_pred).reset_index(drop=True)
if actual.shape[-1] != 1 or pred.shape[-1] != 1:
raise ValueError(f"The input for scoring must be 1-D array, found {actual.shape} and {pred.shape}")
if actual.shape != pred.shape:
raise ValueError(f"The input lengths must be the same, found {actual.shape} and {pred.shape}")
actual.columns = [INPUT_COL_NAME]
pred.columns = [INPUT_COL_NAME]
# Drop rows with NA values in either actual or pred
merged_df = pd.concat([actual, pred], axis=1).dropna()
actual = merged_df.iloc[:, [0]]
pred = merged_df.iloc[:, [1]]
category_in_actual_set = set(actual[INPUT_COL_NAME])
category_in_pred_set = set(pred[INPUT_COL_NAME])
pred_minus_actual = category_in_pred_set.difference(category_in_actual_set)
if pred_minus_actual:
warnings.warn(f"The following categories do not appear in y_true column, "
f"the recall may be undefined.\n{pred_minus_actual}")
actual_minus_pred = category_in_actual_set.difference(category_in_pred_set)
if actual_minus_pred:
warnings.warn(f"The following categories do not appear in y_pred column, "
f"the precision may be undefined.\n{actual_minus_pred}")
# Adds a list wrapper below since `sklearn >= 1.1` restricts the input types and shapes.
return score_func(
y_true=list(actual[INPUT_COL_NAME].reset_index(drop=True)),
y_pred=list(pred[INPUT_COL_NAME].reset_index(drop=True)),
*args,
**kwargs
)
return score_func_wrapper | Decorator function to validate categorical scoring function input, and unifies the input type to pandas.Series. |
167,420 | import functools
import warnings
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from sklearn import metrics
from greykite.detection.common.ad_evaluation_utils import compute_range_based_score
from greykite.detection.common.ad_evaluation_utils import prepare_anomaly_ranges
The provided code snippet includes necessary dependencies for implementing the `f1_score` function. Write a Python function `def f1_score( y_true, y_pred, sample_weight=None)` to solve the following problem:
Computes the F1 scores for two arrays. Parameters ---------- y_true : array-like, 1-D The actual categories. y_pred : array-like, 1-D The predicted categories. sample_weight : array-like, 1-D The sample weight. Returns ------- recall : `dict` The recall score for different categories. The keys are the categories, and the values are the recalls.
Here is the function:
def f1_score(
y_true,
y_pred,
sample_weight=None):
"""Computes the F1 scores for two arrays.
Parameters
----------
y_true : array-like, 1-D
The actual categories.
y_pred : array-like, 1-D
The predicted categories.
sample_weight : array-like, 1-D
The sample weight.
Returns
-------
recall : `dict`
The recall score for different categories.
The keys are the categories, and the values are the recalls.
"""
actual_category = pd.unique(y_true)
pred_category = pd.unique(y_pred)
labels = pd.unique(np.concatenate([actual_category, pred_category]))
f1s_array = metrics.f1_score(
y_true=y_true,
y_pred=y_pred,
average=None,
labels=labels,
sample_weight=sample_weight,
zero_division=0
)
f1_scores = {}
for label, f1 in zip(labels, f1s_array):
f1_scores[label] = f1
return f1_scores | Computes the F1 scores for two arrays. Parameters ---------- y_true : array-like, 1-D The actual categories. y_pred : array-like, 1-D The predicted categories. sample_weight : array-like, 1-D The sample weight. Returns ------- recall : `dict` The recall score for different categories. The keys are the categories, and the values are the recalls. |
167,421 | import functools
import warnings
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from sklearn import metrics
from greykite.detection.common.ad_evaluation_utils import compute_range_based_score
from greykite.detection.common.ad_evaluation_utils import prepare_anomaly_ranges
The provided code snippet includes necessary dependencies for implementing the `matthews_corrcoef` function. Write a Python function `def matthews_corrcoef( y_true, y_pred, sample_weight=None)` to solve the following problem:
Computes the Matthews correlation coefficient for two arrays. The statistic is also known as the phi coefficient. The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1 (inclusive). One can interpret this coefficient as follows: - +1 represents a perfect prediction. - 0 represents an average random prediction. - -1 represents an inverse prediction. For more information, please consult the `wiki page <https://en.wikipedia.org/wiki/Phi_coefficient>`_. Parameters ---------- y_true : array-like, 1-D The actual categories. y_pred : array-like, 1-D The predicted categories. sample_weight : array-like, 1-D or None, default None The sample weight. Returns ------- result : `float` The Matthews correlation coefficient.
Here is the function:
def matthews_corrcoef(
y_true,
y_pred,
sample_weight=None):
"""Computes the Matthews correlation coefficient for two arrays.
The statistic is also known as the phi coefficient.
The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications.
It takes into account true and false positives and negatives and is generally regarded as a balanced measure
which can be used even if the classes are of very different sizes.
The MCC is in essence a correlation coefficient value between -1 and +1 (inclusive).
One can interpret this coefficient as follows:
- +1 represents a perfect prediction.
- 0 represents an average random prediction.
- -1 represents an inverse prediction.
For more information, please consult the `wiki page <https://en.wikipedia.org/wiki/Phi_coefficient>`_.
Parameters
----------
y_true : array-like, 1-D
The actual categories.
y_pred : array-like, 1-D
The predicted categories.
sample_weight : array-like, 1-D or None, default None
The sample weight.
Returns
-------
result : `float`
The Matthews correlation coefficient.
"""
return metrics.matthews_corrcoef(
y_true=y_true,
y_pred=y_pred,
sample_weight=sample_weight) | Computes the Matthews correlation coefficient for two arrays. The statistic is also known as the phi coefficient. The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1 (inclusive). One can interpret this coefficient as follows: - +1 represents a perfect prediction. - 0 represents an average random prediction. - -1 represents an inverse prediction. For more information, please consult the `wiki page <https://en.wikipedia.org/wiki/Phi_coefficient>`_. Parameters ---------- y_true : array-like, 1-D The actual categories. y_pred : array-like, 1-D The predicted categories. sample_weight : array-like, 1-D or None, default None The sample weight. Returns ------- result : `float` The Matthews correlation coefficient. |
167,422 | import functools
import warnings
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from sklearn import metrics
from greykite.detection.common.ad_evaluation_utils import compute_range_based_score
from greykite.detection.common.ad_evaluation_utils import prepare_anomaly_ranges
The provided code snippet includes necessary dependencies for implementing the `informedness_statistic` function. Write a Python function `def informedness_statistic( y_true, y_pred, sample_weight=None)` to solve the following problem:
Computes the Informedness also known as the Youden's J statistic for two arrays. Youden's J statistic is defined as J = sensitivity + specificity - 1 for a binary output. Informedness is its generalization to the multiclass case and estimates the probability of an informed decision. Note that in binary classification, we have: - sensitivity: recall of the positive class. - specificity: recall of the negative class. The index gives equal weight to false positive and false negative values. In other words, all algorithms with the same value of the index give the same proportion of total misclassified results. Its value ranges from -1 through +1 (inclusive). One can interpret this statistic as follows: - +1 represents that there are no false positives or false negatives, i.e. the algorithm is perfect. - 0 respresents when an algorithm gives the same proportion of positive results with and without an anomaly, i.e the test is useless. - -1 represents that the classification yields only false positives and false negatives. It's an inverse prediction. For more information, please consult the `wiki page <https://en.wikipedia.org/wiki/Youden%27s_J_statistic>`_. Parameters ---------- y_true : array-like, 1-D The actual categories. y_pred : array-like, 1-D The predicted categories. sample_weight : array-like, 1-D or None, default None The sample weight. Returns ------- result : `float` The informedness statistic.
Here is the function:
def informedness_statistic(
y_true,
y_pred,
sample_weight=None):
"""Computes the Informedness also known as the Youden's J statistic for two arrays.
Youden's J statistic is defined as J = sensitivity + specificity - 1 for a binary output.
Informedness is its generalization to the multiclass case and estimates the probability of an informed decision.
Note that in binary classification, we have:
- sensitivity: recall of the positive class.
- specificity: recall of the negative class.
The index gives equal weight to false positive and false negative values.
In other words, all algorithms with the same value of the index give the same proportion of total misclassified results.
Its value ranges from -1 through +1 (inclusive).
One can interpret this statistic as follows:
- +1 represents that there are no false positives or false negatives, i.e. the algorithm is perfect.
- 0 respresents when an algorithm gives the same proportion of positive results with and without an anomaly, i.e the test is useless.
- -1 represents that the classification yields only false positives and false negatives. It's an inverse prediction.
For more information, please consult the `wiki page <https://en.wikipedia.org/wiki/Youden%27s_J_statistic>`_.
Parameters
----------
y_true : array-like, 1-D
The actual categories.
y_pred : array-like, 1-D
The predicted categories.
sample_weight : array-like, 1-D or None, default None
The sample weight.
Returns
-------
result : `float`
The informedness statistic.
"""
return metrics.balanced_accuracy_score(
y_true=y_true,
y_pred=y_pred,
sample_weight=sample_weight,
adjusted=True) | Computes the Informedness also known as the Youden's J statistic for two arrays. Youden's J statistic is defined as J = sensitivity + specificity - 1 for a binary output. Informedness is its generalization to the multiclass case and estimates the probability of an informed decision. Note that in binary classification, we have: - sensitivity: recall of the positive class. - specificity: recall of the negative class. The index gives equal weight to false positive and false negative values. In other words, all algorithms with the same value of the index give the same proportion of total misclassified results. Its value ranges from -1 through +1 (inclusive). One can interpret this statistic as follows: - +1 represents that there are no false positives or false negatives, i.e. the algorithm is perfect. - 0 respresents when an algorithm gives the same proportion of positive results with and without an anomaly, i.e the test is useless. - -1 represents that the classification yields only false positives and false negatives. It's an inverse prediction. For more information, please consult the `wiki page <https://en.wikipedia.org/wiki/Youden%27s_J_statistic>`_. Parameters ---------- y_true : array-like, 1-D The actual categories. y_pred : array-like, 1-D The predicted categories. sample_weight : array-like, 1-D or None, default None The sample weight. Returns ------- result : `float` The informedness statistic. |
167,423 | import functools
import warnings
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from sklearn import metrics
from greykite.detection.common.ad_evaluation_utils import compute_range_based_score
from greykite.detection.common.ad_evaluation_utils import prepare_anomaly_ranges
The provided code snippet includes necessary dependencies for implementing the `confusion_matrix` function. Write a Python function `def confusion_matrix( y_true, y_pred, sample_weight=None)` to solve the following problem:
Computes the confusion matrix for two arrays. Parameters ---------- y_true : array-like, 1-D The actual categories. y_pred : array-like, 1-D The predicted categories. sample_weight : array-like, 1-D The sample weight. Returns ------- confusion_matrix : `pandas.DataFrame` The confusion matrix.
Here is the function:
def confusion_matrix(
y_true,
y_pred,
sample_weight=None):
"""Computes the confusion matrix for two arrays.
Parameters
----------
y_true : array-like, 1-D
The actual categories.
y_pred : array-like, 1-D
The predicted categories.
sample_weight : array-like, 1-D
The sample weight.
Returns
-------
confusion_matrix : `pandas.DataFrame`
The confusion matrix.
"""
actual_category = pd.unique(y_true)
pred_category = pd.unique(y_pred)
all_category = pd.unique(np.concatenate([actual_category, pred_category]))
matrix = metrics.confusion_matrix(
y_true=y_true,
y_pred=y_pred,
labels=all_category,
sample_weight=sample_weight
)
matrix = pd.DataFrame(matrix)
matrix.index = pd.MultiIndex.from_arrays([["Actual"] * len(all_category), matrix.index])
matrix.columns = pd.MultiIndex.from_arrays([["Pred"] * len(all_category), matrix.columns])
return matrix | Computes the confusion matrix for two arrays. Parameters ---------- y_true : array-like, 1-D The actual categories. y_pred : array-like, 1-D The predicted categories. sample_weight : array-like, 1-D The sample weight. Returns ------- confusion_matrix : `pandas.DataFrame` The confusion matrix. |
167,424 | import functools
import warnings
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from sklearn import metrics
from greykite.detection.common.ad_evaluation_utils import compute_range_based_score
from greykite.detection.common.ad_evaluation_utils import prepare_anomaly_ranges
def soft_recall_score(
y_true,
y_pred,
window):
"""Computes the soft recall score for two classes, usually labeled 1 and 0 to denote
an anomaly/ alert and not an anomaly/ alert, for `y_true` and `y_pred` respectively.
soft_recall(window) is defined as the proportion of anomalies that were correctly
alerted within the window size. Mathematically,
soft_precision(window) = TruePositive(window)/ sum_i (y_true_i == 1),
where
TruePositive(window) = sum_i(y_true_i == 1, max(y_pred_{i-window}, ..., y_pred_{i+window}) == 1).
For example, let window = 2.
If the ith value in `y_true` is an anomaly (labeled 1), then we say the anomaly
is predicted if any of i-2, i-1, i, i+1, i+2 value in `y_pred` is an alert (labeled 1).
True Positive (window) is the sum of all such predicted anomalies.
As far as we know these soft metrics do not appear in related work at least in this simple form.
These metric were introduced by Reza Hosseini and Sayan Patra as a part of this work.
They are found to be a very simple yet powerful extension of Precision/Recall in our work.
Parameters
----------
y_true : array-like, 1-D
The actual categories.
y_pred : array-like, 1-D
The predicted categories.
window : `int`
The window size to determine True Positives.
Returns
-------
recall : `dict`
The recall scores for various categories.
Examples
--------
>>> y_true = [0, 1, 1, 1, 0, 0]
>>> y_pred = [0, 0, 0, 1, 0, 1]
>>> print([soft_recall_score(y_true, y_pred, window) for window in [0, 1, 2]])
[0.3333333333333333, 0.6666666666666666, 1.0]
"""
if not isinstance(window, int) or window < 0:
raise ValueError(f"Input value of the parameter window ({window}) is not a non-negative integer.")
# If `window` is 0, we revert to the standard definition directly (to save computation time).
if window == 0:
return recall_score(y_true=y_true, y_pred=y_pred)
lag_y_pred = pd.DataFrame({
"y_pred_0": y_pred
})
for i in np.arange(-window, window + 1):
# Due to shifting there will be missing data at the beginning and the end of
# the series. ffill and bfill interpolates these edge cases.
lag_y_pred[f"y_pred_{i}"] = lag_y_pred["y_pred_0"].shift(i).ffill().bfill()
y_pred_soft = lag_y_pred.any(axis="columns")
return recall_score(y_true, y_pred_soft)
def soft_precision_score(
y_true,
y_pred,
window):
"""Computes the soft precision score for two classes, usually labeled 1 and 0 to denote
an anomaly and not an anomaly.
soft_precision(window) is defined as the proportion of alerts that corresponds to an
anomaly within the window size. Mathematically,
soft_precision(window) = TruePositive(window)/ sum_i (y_pred_i == 1),
where
TruePositive(window) = sum_i(y_pred_i == 1, max(actual_{i-window}, ..., actual_{i+window}) == 1)
For eg. let window = 2.
If the ith value in `y_pred` is an alert (labeled 1), then we say the anomaly
is predicted if any of i-2, i-1, i, i+1, i+2 value in `y_pred` is an anomaly (labeled 1).
True Positive (window) is the sum of all such captured anomalies.
As far as we know these soft metrics do not appear in related work at least in this simple form.
These metric were introduced by Reza Hosseini and Sayan Patra as a part of this work.
They are found to be a very simple yet powerful extension of Precision/Recall in our work.
Parameters
----------
y_true : array-like, 1-D
The actual categories.
y_pred : array-like, 1-D
The predicted categories.
window : `int`
The window size to determine True Positives.
Returns
-------
recall : `dict`
The precision scores for various categories.
Examples
--------
>>> y_true = [0, 1, 1, 1, 0, 0]
>>> y_pred = [0, 0, 0, 1, 0, 1]
>>> print([soft_precision_score(y_true, y_pred, window) for window in [0, 1, 2]])
[0.5, 0.5, 1.0]
"""
if not isinstance(window, int) or window < 0:
raise ValueError(f"Input value of the parameter window ({window}) is not a non-negative integer.")
# If `window` is 0, we revert to the standard definition directly (to save computation time).
if window == 0:
return precision_score(y_true=y_true, y_pred=y_pred)
lag_y_true = pd.DataFrame({
"y_true_0": y_true
})
for i in np.arange(-window, window + 1):
# Due to shifting there will be missing data at the beginning and the end of
# the series. ffill and bfill interpolates these edge cases.
lag_y_true[f"y_true_{i}"] = lag_y_true["y_true_0"].shift(i).ffill().bfill()
y_true_soft = lag_y_true.any(axis="columns")
return precision_score(y_true_soft, y_pred)
The provided code snippet includes necessary dependencies for implementing the `soft_f1_score` function. Write a Python function `def soft_f1_score( y_true, y_pred, window)` to solve the following problem:
Computes the soft F1 score for two classes, usually labeled 1 and 0 to denote an anomaly and not an anomaly. Soft F1 is simply calculated from - Soft Precision: `~greykite.detection.common.evaluation.soft_precision_score` and - Soft Recall: `~greykite.detection.common.evaluation.soft_recall_score` using the standard formula for F1: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html Parameters ---------- y_true : array-like, 1-D The actual categories. y_pred : array-like, 1-D The predicted categories. window : `int` The window size to determine True Positives. Returns ------- recall : `dict` The precision scores for various categories.
Here is the function:
def soft_f1_score(
y_true,
y_pred,
window):
"""Computes the soft F1 score for two classes, usually labeled 1 and 0 to denote
an anomaly and not an anomaly.
Soft F1 is simply calculated from
- Soft Precision: `~greykite.detection.common.evaluation.soft_precision_score` and
- Soft Recall: `~greykite.detection.common.evaluation.soft_recall_score`
using the standard formula for F1: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html
Parameters
----------
y_true : array-like, 1-D
The actual categories.
y_pred : array-like, 1-D
The predicted categories.
window : `int`
The window size to determine True Positives.
Returns
-------
recall : `dict`
The precision scores for various categories.
"""
soft_precision = soft_precision_score(
y_true=y_true,
y_pred=y_pred,
window=window)
soft_recall = soft_recall_score(
y_true=y_true,
y_pred=y_pred,
window=window)
soft_f1 = {}
# Soft f1 can only be defined for categories (e.g. True, False) that
# appear in results of both precision and recall.
# Therefore we first find the intersection.
admissable_categories = set(soft_precision.keys()).intersection(soft_recall.keys())
for categ in admissable_categories:
soft_f1[categ] = (
2 * (soft_precision[categ] * soft_recall[categ]) /
(soft_precision[categ] + soft_recall[categ]))
return soft_f1 | Computes the soft F1 score for two classes, usually labeled 1 and 0 to denote an anomaly and not an anomaly. Soft F1 is simply calculated from - Soft Precision: `~greykite.detection.common.evaluation.soft_precision_score` and - Soft Recall: `~greykite.detection.common.evaluation.soft_recall_score` using the standard formula for F1: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html Parameters ---------- y_true : array-like, 1-D The actual categories. y_pred : array-like, 1-D The predicted categories. window : `int` The window size to determine True Positives. Returns ------- recall : `dict` The precision scores for various categories. |
167,425 | import functools
import warnings
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from sklearn import metrics
from greykite.detection.common.ad_evaluation_utils import compute_range_based_score
from greykite.detection.common.ad_evaluation_utils import prepare_anomaly_ranges
def prepare_anomaly_ranges(pointwise_anomalies, range_based: bool = True):
"""Convert a list of pointwise anomalies into a list of anomaly ranges
Parameters
----------
pointwise_anmalies : array-like, 1-D
List of pointwise anomalies
range_based : `bool`
If False, each pointwise anomaly is treated as an anomaly range
If True, adjacent pointwise anomalies will be merged into a single anomaly interval
Returns
-------
anomaly_ranges: array-like, 2D
2D-array representing anomaly ranges, with each element indicating the
start and end indexes for an anomaly period.
"""
if range_based:
pointwise_anomalies = np.argwhere(pointwise_anomalies == 1).ravel()
anomaly_ranges_shift_forward = shift(
pointwise_anomalies,
1,
fill_value=pointwise_anomalies[0])
anomaly_ranges_shift_backward = shift(
pointwise_anomalies,
-1,
fill_value=pointwise_anomalies[-1])
anomaly_ranges_start = np.argwhere((
anomaly_ranges_shift_forward - pointwise_anomalies) != -1).ravel()
anomaly_ranges_end = np.argwhere((
pointwise_anomalies - anomaly_ranges_shift_backward) != -1).ravel()
anomaly_ranges = np.hstack([
pointwise_anomalies[anomaly_ranges_start].reshape(-1, 1),
pointwise_anomalies[anomaly_ranges_end].reshape(-1, 1)])
else:
anomaly_ranges = np.argwhere(pointwise_anomalies == 1).repeat(2, axis=1)
return anomaly_ranges
def compute_range_based_score(
anomaly_ranges_1,
anomaly_ranges_2,
alpha: float = 0.5,
positional_bias: str = "flat",
cardinality_bias: Optional[str] = None):
"""Given two lists of anomaly ranges, calculate a range-based score over the time series represented by the first list
of anomaly ranges. If ``anomaly_ranges_1`` is the predicted anomaly ranges, the result is range-based precision score. If
``anomaly_range_1`` is the real anomaly ranges, the result is range-based recall score.
Parameters
----------
anomaly_ranges_1 : array-like, 2D
2D-array representing anomaly ranges, with each element indicating the
start and end indexes for an anomaly period.
anomaly_ranges_2 : array-like, 2D
2D-array representing anomaly ranges, with each element indicating the
start and end indexes for an anomaly period.
alpha : `float`
Reward weighting term for the two main reward terms for the real anomaly range recall score: existence
and overlap rewards.
positional_bias : `str`, default "flat"
If "flat", each index position of an anomaly range is equally important. Return the same
number, 1.0, as the positional reward regardless of the location of the pointwise anomaly
within the anomaly range.
If "front", reward is biased towards early detection, as earlier overlap locations of pointwise
anomalies with an anomaly range are assigned higher rewards.
If "middle", reward is biased towards the detection of anomaly closer to its middle point, as
overlap locations closer to the middle of an anomaly range are assigned higher rewards.
If "back", reward is biased towards later detection, as later overlap locations of pointwise
anomalies with an anomaly range are assigned higher rewards.
cardinality_bias: `str` or None, default None
In the overlap reward, this is a penalization factor. If None, no cardinality penalty will be applied. If "reciprocal", the
overlap reward will be penalized as it gets multiplied by the reciprocal of the number of detected anomaly ranges overlapping
with the predicted anomaly range.
Returns
-------
overlap_size_and_position_reward: `float`
Overlap reward for both size and position of two anomaly ranges.
"""
assert 0 <= alpha <= 1
assert positional_bias in ["flat", "front", "middle", "back"]
if cardinality_bias is not None:
assert cardinality_bias == "reciprocal"
score = 0.0
for range_idx1 in range(len(anomaly_ranges_1)):
overlap_count = [0]
overlap_size_and_position_reward = 0
real_range = anomaly_ranges_1[range_idx1, :]
for range_idx2 in range(len(anomaly_ranges_2)):
predicted_range = anomaly_ranges_2[range_idx2, :]
overlap_size_and_position_reward += get_overlap_size_and_position_reward(
real_range,
predicted_range,
overlap_count,
positional_bias)
cardinality_factor = get_cardinality_factor(overlap_count, cardinality_bias)
overlap_reward = cardinality_factor * overlap_size_and_position_reward
existence_reward = 1 if overlap_count[0] > 0 else 0
score += alpha * existence_reward + (1 - alpha) * overlap_reward
score /= len(anomaly_ranges_1)
return score
The provided code snippet includes necessary dependencies for implementing the `range_based_precision_score` function. Write a Python function `def range_based_precision_score( y_true, y_pred, alpha: float = 0.5, positional_bias: str = "flat", cardinality_bias: Optional[str] = None, range_based: bool = True)` to solve the following problem:
Compute a precision score for two classes, usually labeled 1 and 0 to denote an anomaly and not an anomaly. Both ``y_true`` and ``y_pred`` need to be sorted by timestamp. This precision implementation is from the paper: Precision and Recall for Time Series <https://arxiv.org/abs/1803.03639>; Point-wise real and predicted anomalies are first transformed into anomaly ranges. Then, given the set of real anomaly ranges, R = {R_1, ..., R_Nr}, and predicted anomaly ranges, P = {P_1, ..., P_Np}, a precision score Precision_T(R, P_j) is calculated for each predicted anomaly range, P_j. Those precision scores are then added into a total precision score and divided by the total number of predicted anomaly ranges, Np, to obtain an average precision score for the whole timeseries. Multiple considerations are taken into account when computing the individual precision scores for each real anomaly range, such as: Existence: Catching the existence of an anomaly (even by predicting only a single point in R_i), by itself, might be valuable for the application. Size: The larger the size of the correctly predicted portion of R_i, the higher the precision score. Position: In some cases, not only size, but also the relative position of the correctly predicted portion of R_i might matter to the application. Cardinality: Detecting R_i with a single prediction range P_j ∈ P may be more valuable than doing so with multiple different ranges in P in a fragmented manner. All of those considerations are captured using two main reward terms: Existence Reward and Overlap Reward, weighted by a weighting constant ``alpha``. The precision score for each predicted anomaly range will be calculated as: Precision_T = alpha * Existence Reward + (1 - alpha) * Overlap Reward Parameters ---------- y_true : array-like, 1-D The actual point-wise anomalies y_pred : array-like, 1-D The predicted point-wise anomalies alpha : `float` Reward weighting term for the two main reward terms for the predicted anomaly range precision score: existence and overlap rewards. positional_bias : `str`, default "flat" The accepted options are: * "flat": Each index position of an anomaly range is equally important. Return the same value of 1.0 as the positional reward regardless of the location of the pointwise anomaly within the anomaly range. * "front": Positional reward is biased towards early detection, as earlier overlap locations of pointwise anomalies with an anomaly range are assigned higher rewards. * "middle": Positional reward is biased towards the detection of anomaly closer to its middle point, as overlap locations closer to the middle of an anomaly range are assigned higher rewards. * "back": Positional reward is biased towards later detection, as later overlap locations of pointwise anomalies with an anomaly range are assigned higher rewards. cardinality_bias: `str` or None, default None In the overlap reward, this is a penalization factor. If None, no cardinality penalty will be applied. If "reciprocal", the overlap reward will be penalized as it gets multiplied by the reciprocal of the number of detected anomaly ranges overlapping with the predicted anomaly range. range_based: `bool`, default True This implementation of range-based precision subsumes the classic precision. If True range based precision will be calculated, otherwise classic precision will be calculated. Returns ------- precision : `float` The overall precision score for the time series.
Here is the function:
def range_based_precision_score(
y_true,
y_pred,
alpha: float = 0.5,
positional_bias: str = "flat",
cardinality_bias: Optional[str] = None,
range_based: bool = True):
"""Compute a precision score for two classes, usually labeled 1 and 0 to denote an anomaly and not an anomaly.
Both ``y_true`` and ``y_pred`` need to be sorted by timestamp.
This precision implementation is from the paper:
Precision and Recall for Time Series
<https://arxiv.org/abs/1803.03639>;
Point-wise real and predicted anomalies are first transformed into anomaly ranges. Then, given the set of real
anomaly ranges, R = {R_1, ..., R_Nr}, and predicted anomaly ranges, P = {P_1, ..., P_Np}, a precision score Precision_T(R, P_j) is
calculated for each predicted anomaly range, P_j. Those precision scores are then added into a total precision score and divided by the
total number of predicted anomaly ranges, Np, to obtain an average precision score for the whole timeseries.
Multiple considerations are taken into account when computing the individual precision scores for each real anomaly range, such as:
Existence: Catching the existence of an anomaly (even by predicting only a single point in R_i), by itself, might be valuable
for the application.
Size: The larger the size of the correctly predicted portion of R_i, the higher the precision score.
Position: In some cases, not only size, but also the relative position of the correctly predicted portion of R_i might matter
to the application.
Cardinality: Detecting R_i with a single prediction range P_j ∈ P may be more valuable than doing so with multiple different
ranges in P in a fragmented manner.
All of those considerations are captured using two main reward terms: Existence Reward and Overlap Reward, weighted by a weighting
constant ``alpha``. The precision score for each predicted anomaly range will be calculated as:
Precision_T = alpha * Existence Reward + (1 - alpha) * Overlap Reward
Parameters
----------
y_true : array-like, 1-D
The actual point-wise anomalies
y_pred : array-like, 1-D
The predicted point-wise anomalies
alpha : `float`
Reward weighting term for the two main reward terms for the predicted anomaly range precision score: existence and overlap rewards.
positional_bias : `str`, default "flat"
The accepted options are:
* "flat": Each index position of an anomaly range is equally important. Return the same value of 1.0 as the positional
reward regardless of the location of the pointwise anomaly within the anomaly range.
* "front": Positional reward is biased towards early detection, as earlier overlap locations of pointwise
anomalies with an anomaly range are assigned higher rewards.
* "middle": Positional reward is biased towards the detection of anomaly closer to its middle point, as overlap locations
closer to the middle of an anomaly range are assigned higher rewards.
* "back": Positional reward is biased towards later detection, as later overlap locations of pointwise anomalies with an
anomaly range are assigned higher rewards.
cardinality_bias: `str` or None, default None
In the overlap reward, this is a penalization factor. If None, no cardinality penalty will be applied. If "reciprocal", the
overlap reward will be penalized as it gets multiplied by the reciprocal of the number of detected anomaly ranges overlapping
with the predicted anomaly range.
range_based: `bool`, default True
This implementation of range-based precision subsumes the classic precision. If True range based precision will be calculated, otherwise
classic precision will be calculated.
Returns
-------
precision : `float`
The overall precision score for the time series.
"""
assert len(y_true) == len(y_pred)
assert 0 <= alpha <= 1
assert positional_bias in ["flat", "front", "middle", "back"]
if cardinality_bias is not None:
assert cardinality_bias == "reciprocal"
real_anomaly_ranges = prepare_anomaly_ranges(np.array(y_true), range_based)
predicted_anomaly_ranges = prepare_anomaly_ranges(np.array(y_pred), range_based)
precision = compute_range_based_score(
predicted_anomaly_ranges,
real_anomaly_ranges,
alpha, positional_bias, cardinality_bias)
return precision | Compute a precision score for two classes, usually labeled 1 and 0 to denote an anomaly and not an anomaly. Both ``y_true`` and ``y_pred`` need to be sorted by timestamp. This precision implementation is from the paper: Precision and Recall for Time Series <https://arxiv.org/abs/1803.03639>; Point-wise real and predicted anomalies are first transformed into anomaly ranges. Then, given the set of real anomaly ranges, R = {R_1, ..., R_Nr}, and predicted anomaly ranges, P = {P_1, ..., P_Np}, a precision score Precision_T(R, P_j) is calculated for each predicted anomaly range, P_j. Those precision scores are then added into a total precision score and divided by the total number of predicted anomaly ranges, Np, to obtain an average precision score for the whole timeseries. Multiple considerations are taken into account when computing the individual precision scores for each real anomaly range, such as: Existence: Catching the existence of an anomaly (even by predicting only a single point in R_i), by itself, might be valuable for the application. Size: The larger the size of the correctly predicted portion of R_i, the higher the precision score. Position: In some cases, not only size, but also the relative position of the correctly predicted portion of R_i might matter to the application. Cardinality: Detecting R_i with a single prediction range P_j ∈ P may be more valuable than doing so with multiple different ranges in P in a fragmented manner. All of those considerations are captured using two main reward terms: Existence Reward and Overlap Reward, weighted by a weighting constant ``alpha``. The precision score for each predicted anomaly range will be calculated as: Precision_T = alpha * Existence Reward + (1 - alpha) * Overlap Reward Parameters ---------- y_true : array-like, 1-D The actual point-wise anomalies y_pred : array-like, 1-D The predicted point-wise anomalies alpha : `float` Reward weighting term for the two main reward terms for the predicted anomaly range precision score: existence and overlap rewards. positional_bias : `str`, default "flat" The accepted options are: * "flat": Each index position of an anomaly range is equally important. Return the same value of 1.0 as the positional reward regardless of the location of the pointwise anomaly within the anomaly range. * "front": Positional reward is biased towards early detection, as earlier overlap locations of pointwise anomalies with an anomaly range are assigned higher rewards. * "middle": Positional reward is biased towards the detection of anomaly closer to its middle point, as overlap locations closer to the middle of an anomaly range are assigned higher rewards. * "back": Positional reward is biased towards later detection, as later overlap locations of pointwise anomalies with an anomaly range are assigned higher rewards. cardinality_bias: `str` or None, default None In the overlap reward, this is a penalization factor. If None, no cardinality penalty will be applied. If "reciprocal", the overlap reward will be penalized as it gets multiplied by the reciprocal of the number of detected anomaly ranges overlapping with the predicted anomaly range. range_based: `bool`, default True This implementation of range-based precision subsumes the classic precision. If True range based precision will be calculated, otherwise classic precision will be calculated. Returns ------- precision : `float` The overall precision score for the time series. |
167,426 | import functools
import warnings
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from sklearn import metrics
from greykite.detection.common.ad_evaluation_utils import compute_range_based_score
from greykite.detection.common.ad_evaluation_utils import prepare_anomaly_ranges
def prepare_anomaly_ranges(pointwise_anomalies, range_based: bool = True):
"""Convert a list of pointwise anomalies into a list of anomaly ranges
Parameters
----------
pointwise_anmalies : array-like, 1-D
List of pointwise anomalies
range_based : `bool`
If False, each pointwise anomaly is treated as an anomaly range
If True, adjacent pointwise anomalies will be merged into a single anomaly interval
Returns
-------
anomaly_ranges: array-like, 2D
2D-array representing anomaly ranges, with each element indicating the
start and end indexes for an anomaly period.
"""
if range_based:
pointwise_anomalies = np.argwhere(pointwise_anomalies == 1).ravel()
anomaly_ranges_shift_forward = shift(
pointwise_anomalies,
1,
fill_value=pointwise_anomalies[0])
anomaly_ranges_shift_backward = shift(
pointwise_anomalies,
-1,
fill_value=pointwise_anomalies[-1])
anomaly_ranges_start = np.argwhere((
anomaly_ranges_shift_forward - pointwise_anomalies) != -1).ravel()
anomaly_ranges_end = np.argwhere((
pointwise_anomalies - anomaly_ranges_shift_backward) != -1).ravel()
anomaly_ranges = np.hstack([
pointwise_anomalies[anomaly_ranges_start].reshape(-1, 1),
pointwise_anomalies[anomaly_ranges_end].reshape(-1, 1)])
else:
anomaly_ranges = np.argwhere(pointwise_anomalies == 1).repeat(2, axis=1)
return anomaly_ranges
def compute_range_based_score(
anomaly_ranges_1,
anomaly_ranges_2,
alpha: float = 0.5,
positional_bias: str = "flat",
cardinality_bias: Optional[str] = None):
"""Given two lists of anomaly ranges, calculate a range-based score over the time series represented by the first list
of anomaly ranges. If ``anomaly_ranges_1`` is the predicted anomaly ranges, the result is range-based precision score. If
``anomaly_range_1`` is the real anomaly ranges, the result is range-based recall score.
Parameters
----------
anomaly_ranges_1 : array-like, 2D
2D-array representing anomaly ranges, with each element indicating the
start and end indexes for an anomaly period.
anomaly_ranges_2 : array-like, 2D
2D-array representing anomaly ranges, with each element indicating the
start and end indexes for an anomaly period.
alpha : `float`
Reward weighting term for the two main reward terms for the real anomaly range recall score: existence
and overlap rewards.
positional_bias : `str`, default "flat"
If "flat", each index position of an anomaly range is equally important. Return the same
number, 1.0, as the positional reward regardless of the location of the pointwise anomaly
within the anomaly range.
If "front", reward is biased towards early detection, as earlier overlap locations of pointwise
anomalies with an anomaly range are assigned higher rewards.
If "middle", reward is biased towards the detection of anomaly closer to its middle point, as
overlap locations closer to the middle of an anomaly range are assigned higher rewards.
If "back", reward is biased towards later detection, as later overlap locations of pointwise
anomalies with an anomaly range are assigned higher rewards.
cardinality_bias: `str` or None, default None
In the overlap reward, this is a penalization factor. If None, no cardinality penalty will be applied. If "reciprocal", the
overlap reward will be penalized as it gets multiplied by the reciprocal of the number of detected anomaly ranges overlapping
with the predicted anomaly range.
Returns
-------
overlap_size_and_position_reward: `float`
Overlap reward for both size and position of two anomaly ranges.
"""
assert 0 <= alpha <= 1
assert positional_bias in ["flat", "front", "middle", "back"]
if cardinality_bias is not None:
assert cardinality_bias == "reciprocal"
score = 0.0
for range_idx1 in range(len(anomaly_ranges_1)):
overlap_count = [0]
overlap_size_and_position_reward = 0
real_range = anomaly_ranges_1[range_idx1, :]
for range_idx2 in range(len(anomaly_ranges_2)):
predicted_range = anomaly_ranges_2[range_idx2, :]
overlap_size_and_position_reward += get_overlap_size_and_position_reward(
real_range,
predicted_range,
overlap_count,
positional_bias)
cardinality_factor = get_cardinality_factor(overlap_count, cardinality_bias)
overlap_reward = cardinality_factor * overlap_size_and_position_reward
existence_reward = 1 if overlap_count[0] > 0 else 0
score += alpha * existence_reward + (1 - alpha) * overlap_reward
score /= len(anomaly_ranges_1)
return score
The provided code snippet includes necessary dependencies for implementing the `range_based_recall_score` function. Write a Python function `def range_based_recall_score( y_true, y_pred, alpha: float = 0.5, positional_bias: str = "flat", cardinality_bias: Optional[str] = None, range_based: bool = True)` to solve the following problem:
Compute a recall score for two classes, usually labeled 1 and 0 to denote an anomaly and not an anomaly. Both ``y_true`` and ``y_pred`` need to be in sorted by timestamp. This recall implementation is from the paper: Precision and Recall for Time Series <https://arxiv.org/abs/1803.03639>; Point-wise real and predicted anomalies are first transformed into anomaly ranges. Then, given the set of real anomaly ranges, R = {R_1, ..., R_Nr}, and predicted anomaly ranges, P = {P_1, ..., P_Np}, a recall score Recall_T(R_i, P) is calculated for each real anomaly range, R_i. Those recall scores are then added into a total recall score and divided by the total number of real anomaly ranges, Nr, to obtain an average recall score for the whole timeseries. Multiple considerations are taken into account when computing the individual recall scores for each real anomaly range, such as: Existence: Catching the existence of an anomaly (even by predicting only a single point in R_i), by itself, might be valuable for the application. Size: The larger the size of the correctly predicted portion of R_i, the higher the recall score. Position: In some cases, not only size, but also the relative position of the correctly predicted portion of R_i might matter to the application. Cardinality: Detecting R_i with a single prediction range P_j ∈ P may be more valuable than doing so with multiple different ranges in P in a fragmented manner. All of those considerations are captured using two main reward terms: Existence Reward and Overlap Reward, weighted by a weighting constant ``alpha``. The recall score for each real anomaly range will be calculated as: Recall_T = alpha * Existence Reward + (1 - alpha) * Overlap Reward Parameters ---------- y_true : array-like, 1-D The actual point-wise anomalies y_pred : array-like, 1-D The predicted point-wise anomalies alpha : `float` Reward weighting term for the two main reward terms for the real anomaly range recall score: existence and overlap rewards. positional_bias : `str`, default "flat" The accepted options are: * "flat": Each index position of an anomaly range is equally important. Return the same value of 1.0 as the positional reward regardless of the location of the pointwise anomaly within the anomaly range. * "front": Positional reward is biased towards early detection, as earlier overlap locations of pointwise anomalies with an anomaly range are assigned higher rewards. * "middle": Positional reward is biased towards the detection of anomaly closer to its middle point, as overlap locations closer to the middle of an anomaly range are assigned higher rewards. * "back": Positional reward is biased towards later detection, as later overlap locations of pointwise anomalies with an anomaly range are assigned higher rewards. cardinality_bias: `str` or None, default None In the overlap reward, this is a penalization factor. If None, no cardinality penalty will be applied. If "reciprocal", the overlap reward will be penalized as it gets multiplied by the reciprocal of the number of detected anomaly ranges overlapping with the real anomaly range. range_based: `bool`, default True This implementation of range-based recall subsumes the classic recall. If True range based recall will be calculated, otherwise classic recall will be calculated. Returns ------- recall : `float` The overall recall score for the time series.
Here is the function:
def range_based_recall_score(
y_true,
y_pred,
alpha: float = 0.5,
positional_bias: str = "flat",
cardinality_bias: Optional[str] = None,
range_based: bool = True):
"""Compute a recall score for two classes, usually labeled 1 and 0 to denote an anomaly and not an anomaly.
Both ``y_true`` and ``y_pred`` need to be in sorted by timestamp.
This recall implementation is from the paper:
Precision and Recall for Time Series
<https://arxiv.org/abs/1803.03639>;
Point-wise real and predicted anomalies are first transformed into anomaly ranges. Then, given the set of real
anomaly ranges, R = {R_1, ..., R_Nr}, and predicted anomaly ranges, P = {P_1, ..., P_Np}, a recall score Recall_T(R_i, P) is
calculated for each real anomaly range, R_i. Those recall scores are then added into a total recall score and divided by the
total number of real anomaly ranges, Nr, to obtain an average recall score for the whole timeseries.
Multiple considerations are taken into account when computing the individual recall scores for each real anomaly range, such as:
Existence: Catching the existence of an anomaly (even by predicting only a single point in R_i), by itself, might be valuable
for the application.
Size: The larger the size of the correctly predicted portion of R_i, the higher the recall score.
Position: In some cases, not only size, but also the relative position of the correctly predicted portion of R_i might matter
to the application.
Cardinality: Detecting R_i with a single prediction range P_j ∈ P may be more valuable than doing so with multiple different
ranges in P in a fragmented manner.
All of those considerations are captured using two main reward terms: Existence Reward and Overlap Reward, weighted by a weighting
constant ``alpha``. The recall score for each real anomaly range will be calculated as:
Recall_T = alpha * Existence Reward + (1 - alpha) * Overlap Reward
Parameters
----------
y_true : array-like, 1-D
The actual point-wise anomalies
y_pred : array-like, 1-D
The predicted point-wise anomalies
alpha : `float`
Reward weighting term for the two main reward terms for the real anomaly range recall score: existence and overlap rewards.
positional_bias : `str`, default "flat"
The accepted options are:
* "flat": Each index position of an anomaly range is equally important. Return the same value of 1.0 as the positional
reward regardless of the location of the pointwise anomaly within the anomaly range.
* "front": Positional reward is biased towards early detection, as earlier overlap locations of pointwise
anomalies with an anomaly range are assigned higher rewards.
* "middle": Positional reward is biased towards the detection of anomaly closer to its middle point, as overlap locations
closer to the middle of an anomaly range are assigned higher rewards.
* "back": Positional reward is biased towards later detection, as later overlap locations of pointwise anomalies with an
anomaly range are assigned higher rewards.
cardinality_bias: `str` or None, default None
In the overlap reward, this is a penalization factor. If None, no cardinality penalty will be applied. If "reciprocal", the
overlap reward will be penalized as it gets multiplied by the reciprocal of the number of detected anomaly ranges overlapping
with the real anomaly range.
range_based: `bool`, default True
This implementation of range-based recall subsumes the classic recall. If True range based recall will be calculated, otherwise
classic recall will be calculated.
Returns
-------
recall : `float`
The overall recall score for the time series.
"""
assert len(y_true) == len(y_pred)
assert 0 <= alpha <= 1
assert positional_bias in ["flat", "front", "middle", "back"]
if cardinality_bias is not None:
assert cardinality_bias == "reciprocal"
real_anomaly_ranges = prepare_anomaly_ranges(np.array(y_true), range_based)
predicted_anomaly_ranges = prepare_anomaly_ranges(np.array(y_pred), range_based)
recall = compute_range_based_score(
real_anomaly_ranges,
predicted_anomaly_ranges,
alpha, positional_bias, cardinality_bias)
return recall | Compute a recall score for two classes, usually labeled 1 and 0 to denote an anomaly and not an anomaly. Both ``y_true`` and ``y_pred`` need to be in sorted by timestamp. This recall implementation is from the paper: Precision and Recall for Time Series <https://arxiv.org/abs/1803.03639>; Point-wise real and predicted anomalies are first transformed into anomaly ranges. Then, given the set of real anomaly ranges, R = {R_1, ..., R_Nr}, and predicted anomaly ranges, P = {P_1, ..., P_Np}, a recall score Recall_T(R_i, P) is calculated for each real anomaly range, R_i. Those recall scores are then added into a total recall score and divided by the total number of real anomaly ranges, Nr, to obtain an average recall score for the whole timeseries. Multiple considerations are taken into account when computing the individual recall scores for each real anomaly range, such as: Existence: Catching the existence of an anomaly (even by predicting only a single point in R_i), by itself, might be valuable for the application. Size: The larger the size of the correctly predicted portion of R_i, the higher the recall score. Position: In some cases, not only size, but also the relative position of the correctly predicted portion of R_i might matter to the application. Cardinality: Detecting R_i with a single prediction range P_j ∈ P may be more valuable than doing so with multiple different ranges in P in a fragmented manner. All of those considerations are captured using two main reward terms: Existence Reward and Overlap Reward, weighted by a weighting constant ``alpha``. The recall score for each real anomaly range will be calculated as: Recall_T = alpha * Existence Reward + (1 - alpha) * Overlap Reward Parameters ---------- y_true : array-like, 1-D The actual point-wise anomalies y_pred : array-like, 1-D The predicted point-wise anomalies alpha : `float` Reward weighting term for the two main reward terms for the real anomaly range recall score: existence and overlap rewards. positional_bias : `str`, default "flat" The accepted options are: * "flat": Each index position of an anomaly range is equally important. Return the same value of 1.0 as the positional reward regardless of the location of the pointwise anomaly within the anomaly range. * "front": Positional reward is biased towards early detection, as earlier overlap locations of pointwise anomalies with an anomaly range are assigned higher rewards. * "middle": Positional reward is biased towards the detection of anomaly closer to its middle point, as overlap locations closer to the middle of an anomaly range are assigned higher rewards. * "back": Positional reward is biased towards later detection, as later overlap locations of pointwise anomalies with an anomaly range are assigned higher rewards. cardinality_bias: `str` or None, default None In the overlap reward, this is a penalization factor. If None, no cardinality penalty will be applied. If "reciprocal", the overlap reward will be penalized as it gets multiplied by the reciprocal of the number of detected anomaly ranges overlapping with the real anomaly range. range_based: `bool`, default True This implementation of range-based recall subsumes the classic recall. If True range based recall will be calculated, otherwise classic recall will be calculated. Returns ------- recall : `float` The overall recall score for the time series. |
167,427 | import logging
import sys
from enum import Enum
import numpy as np
import six
from greykite.common.constants import LOGGER_NAME
The provided code snippet includes necessary dependencies for implementing the `pprint` function. Write a Python function `def pprint(params, offset=0, printer=repr)` to solve the following problem:
Pretty print the dictionary 'params' Copied from sklearn.base._pprint to avoid accessing protected member of module Parameters ---------- params : dict The dictionary to pretty print offset : int The offset in characters to add at the begin of each line. printer : callable The function to convert entries to strings, typically the builtin str or repr
Here is the function:
def pprint(params, offset=0, printer=repr):
"""Pretty print the dictionary 'params'
Copied from sklearn.base._pprint to avoid accessing protected member of module
Parameters
----------
params : dict
The dictionary to pretty print
offset : int
The offset in characters to add at the begin of each line.
printer : callable
The function to convert entries to strings, typically
the builtin str or repr
"""
# Do a multi-line justified repr:
options = np.get_printoptions()
np.set_printoptions(precision=5, threshold=64, edgeitems=2)
params_list = list()
this_line_length = offset
line_sep = ',\n' + (1 + offset // 2) * ' '
for i, (k, v) in enumerate(sorted(six.iteritems(params))):
if type(v) is float:
# use str for representing floating point numbers
# this way we get consistent representation across
# architectures and versions.
this_repr = '%s=%s' % (k, str(v))
else:
# use repr of the rest
this_repr = '%s=%s' % (k, printer(v))
if len(this_repr) > 500:
this_repr = this_repr[:300] + '...' + this_repr[-100:]
if i > 0:
if this_line_length + len(this_repr) >= 75 or '\n' in this_repr:
params_list.append(line_sep)
this_line_length = len(line_sep)
else:
params_list.append(', ')
this_line_length += 2
params_list.append(this_repr)
this_line_length += len(this_repr)
np.set_printoptions(**options)
lines = ''.join(params_list)
# Strip trailing space to avoid nightmare in doctests
lines = '\n'.join(line.rstrip(' ') for line in lines.split('\n'))
return lines | Pretty print the dictionary 'params' Copied from sklearn.base._pprint to avoid accessing protected member of module Parameters ---------- params : dict The dictionary to pretty print offset : int The offset in characters to add at the begin of each line. printer : callable The function to convert entries to strings, typically the builtin str or repr |
167,428 | import pandas as pd
from greykite.common.viz.timeseries_plotting import plot_multivariate
def plot_multivariate(
df,
x_col,
y_col_style_dict="plotly",
default_color="rgba(0, 145, 202, 1.0)",
xlabel=None,
ylabel=cst.VALUE_COL,
title=None,
showlegend=True):
"""Plots one or more lines against the same x-axis values.
Parameters
----------
df : `pandas.DataFrame`
Data frame with ``x_col`` and columns named by the keys in ``y_col_style_dict``.
x_col: `str`
Which column to plot on the x-axis.
y_col_style_dict: `dict` [`str`, `dict` or None] or "plotly" or "auto" or "auto-fill", default "plotly"
The column(s) to plot on the y-axis, and how to style them.
If a dictionary:
- key : `str`
column name in ``df``
- value : `dict` or None
Optional styling options, passed as kwargs to `go.Scatter`.
If None, uses the default: line labeled by the column name.
See reference page for `plotly.graph_objects.Scatter` for options
(e.g. color, mode, width/size, opacity).
https://plotly.com/python/reference/#scatter.
If a string, plots all columns in ``df`` besides ``x_col`` against ``x_col``:
- "plotly": plot lines with default plotly styling
- "auto": plot lines with color ``default_color``, sorted by value (ascending)
- "auto-fill": plot lines with color ``default_color``, sorted by value (ascending), and fills between lines
default_color: `str`, default "rgba(0, 145, 202, 1.0)" (blue)
Default line color when ``y_col_style_dict`` is one of "auto", "auto-fill".
xlabel : `str` or None, default None
x-axis label. If None, default is ``x_col``.
ylabel : `str` or None, default ``VALUE_COL``
y-axis label
title : `str` or None, default None
Plot title. If None, default is based on axis labels.
showlegend : `bool`, default True
Whether to show the legend.
Returns
-------
fig : `plotly.graph_objects.Figure`
Interactive plotly graph of one or more columns
in ``df`` against ``x_col``.
See `~greykite.common.viz.timeseries_plotting.plot_forecast_vs_actual`
return value for how to plot the figure and add customization.
"""
if xlabel is None:
xlabel = x_col
if title is None and ylabel is not None:
title = f"{ylabel} vs {xlabel}"
auto_style = {"line": {"color": default_color}}
if y_col_style_dict == "plotly":
# Uses plotly default style
y_col_style_dict = {col: None for col in df.columns if col != x_col}
elif y_col_style_dict in ["auto", "auto-fill"]:
# Columns ordered from low to high
means = df.drop(columns=x_col).mean()
column_order = list(means.sort_values().index)
if y_col_style_dict == "auto":
# Lines with color `default_color`
y_col_style_dict = {col: auto_style for col in column_order}
elif y_col_style_dict == "auto-fill":
# Lines with color `default_color`, with fill between lines
y_col_style_dict = {column_order[0]: auto_style}
y_col_style_dict.update({
col: {
"line": {"color": default_color},
"fill": "tonexty"
} for col in column_order[1:]
})
data = []
default_style = dict(mode="lines")
for column, style_dict in y_col_style_dict.items():
# By default, column name in ``df`` is used to label the line
default_col_style = update_dictionary(default_style, overwrite_dict={"name": column})
# User can overwrite any of the default values, or remove them by setting key value to None
style_dict = update_dictionary(default_col_style, overwrite_dict=style_dict)
line = go.Scatter(
x=df[x_col],
y=df[column],
**style_dict)
data.append(line)
layout = go.Layout(
xaxis=dict(title=xlabel),
yaxis=dict(title=ylabel),
title=title,
title_x=0.5,
showlegend=showlegend,
legend={'traceorder': 'reversed'} # Matches the order of ``y_col_style_dict`` (bottom to top)
)
fig = go.Figure(data=data, layout=layout)
return fig
The provided code snippet includes necessary dependencies for implementing the `compare_two_dfs_on_index` function. Write a Python function `def compare_two_dfs_on_index( dfs, df_labels, index_col, diff_cols=None, relative_diff=False)` to solve the following problem:
Calculates difference between two dataframes macthed on a given index. One intended application is to compare breakdown dfs from two related ML models or same model at different times. However it can be used to compare generic dataframes as well. Parameters ---------- dfs: `list` [`pandas.DataFrame`] A list of two dataframes which includes minimally - the index column (``index_col``) - columns which include the values to be compared. If ``diff_cols`` is passed, we expect them to appear in these dataframes. df_labels : `list` [`str`] A list of two strings denoting the label for each ``df`` respectively. index_col : `str` The column name of the index column which will be used for joining and as x axis of the difference plot. diff_cols : `list` [`str`], default None A list of columns to be differenced. Each column represents a variable / component to be compared. If it is not passed or None, all the columns except for ``index_col`` will be used. relative_diff : `bool`, default True It determines if diff is to be simple diff or relative diff obtained by dividing the diff by the absolute values of first dataframe for each value column. Returns ------- result : `dict` A dictionary with following items: - "diff_df": `pandas.DataFrame` A dataframe which includes the diff for each group / component. - "diff_fig": `plotly.graph_objs._figure.Figure` plotly plot overlaying various variable diffs
Here is the function:
def compare_two_dfs_on_index(
dfs,
df_labels,
index_col,
diff_cols=None,
relative_diff=False):
"""Calculates difference between two dataframes macthed on a given index.
One intended application is to compare breakdown dfs from two related ML models
or same model at different times. However it can be used to compare generic
dataframes as well.
Parameters
----------
dfs: `list` [`pandas.DataFrame`]
A list of two dataframes which includes minimally
- the index column (``index_col``)
- columns which include the values to be compared.
If ``diff_cols`` is passed, we expect them to appear in these dataframes.
df_labels : `list` [`str`]
A list of two strings denoting the label for each ``df`` respectively.
index_col : `str`
The column name of the index column which will be used for joining and
as x axis of the difference plot.
diff_cols : `list` [`str`], default None
A list of columns to be differenced.
Each column represents a variable / component to be compared.
If it is not passed or None, all the columns except for ``index_col`` will
be used.
relative_diff : `bool`, default True
It determines if diff is to be simple diff or relative diff obtained by
dividing the diff by the absolute values of first dataframe for each value column.
Returns
-------
result : `dict`
A dictionary with following items:
- "diff_df": `pandas.DataFrame`
A dataframe which includes the diff for each group / component.
- "diff_fig": `plotly.graph_objs._figure.Figure`
plotly plot overlaying various variable diffs
"""
assert len(dfs) == 2, "We expect two dataframes."
assert len(df_labels) == 2, "We expect two labels"
assert list(dfs[0].columns) == list(dfs[1].columns), "We expect same column names in both dataframes"
assert index_col in dfs[0].columns, "`index_col` must be found in both dataframes."
assert index_col in dfs[1].columns, "`index_col` must be found in both dataframes."
diff_df = pd.merge(
dfs[0],
dfs[1],
on=index_col)
if diff_cols is None:
diff_cols = list(dfs[0].columns)
diff_cols.remove(index_col)
y_label = "diff"
for col in diff_cols:
diff_df[col] = diff_df[f"{col}_y"] - diff_df[f"{col}_x"]
if relative_diff:
diff_df[col] = diff_df[col] / abs(diff_df[f"{col}_x"])
y_label = "relative diff"
diff_df = diff_df[[index_col] + diff_cols]
diff_fig = plot_multivariate(
df=diff_df,
x_col=index_col,
title=f"change in variables from {df_labels[0]} to {df_labels[1]}",
ylabel=y_label)
return {
"diff_df": diff_df,
"diff_fig": diff_fig
} | Calculates difference between two dataframes macthed on a given index. One intended application is to compare breakdown dfs from two related ML models or same model at different times. However it can be used to compare generic dataframes as well. Parameters ---------- dfs: `list` [`pandas.DataFrame`] A list of two dataframes which includes minimally - the index column (``index_col``) - columns which include the values to be compared. If ``diff_cols`` is passed, we expect them to appear in these dataframes. df_labels : `list` [`str`] A list of two strings denoting the label for each ``df`` respectively. index_col : `str` The column name of the index column which will be used for joining and as x axis of the difference plot. diff_cols : `list` [`str`], default None A list of columns to be differenced. Each column represents a variable / component to be compared. If it is not passed or None, all the columns except for ``index_col`` will be used. relative_diff : `bool`, default True It determines if diff is to be simple diff or relative diff obtained by dividing the diff by the absolute values of first dataframe for each value column. Returns ------- result : `dict` A dictionary with following items: - "diff_df": `pandas.DataFrame` A dataframe which includes the diff for each group / component. - "diff_fig": `plotly.graph_objs._figure.Figure` plotly plot overlaying various variable diffs |
167,429 | import inspect
import os
import shutil
import warnings
from glob import glob
from pathlib import Path
import plotly
from plotly.io import write_html
from plotly.io import write_image
from plotly.io._base_renderers import ExternalRenderer
from plotly.tools import return_figure_from_figure_or_data
def figure_rst(figure_list, sources_dir):
"""Generate RST for a list of image filenames.
Depending on whether we have one or more figures, we use a
single rst call to 'image' or a horizontal list.
Original functions:
from sphinx_gallery.gen_rst import figure_rst
from plotly.io._sg_scraper import figure_rst
Modified rST directives from image to raw html
Parameters
----------
figure_list : list
List of strings of the figures' absolute paths.
sources_dir : str
absolute path of Sphinx documentation sources
Returns
-------
images_rst : str
rst code to embed the images in the document
"""
# figure_paths = [os.path.relpath(figure_path, sources_dir)
# .replace(os.sep, '/').lstrip('/')
# for figure_path in figure_list]
figure_paths = figure_list
images_rst = ""
if len(figure_paths) == 1:
figure_name = figure_paths[0]
images_rst = SINGLE_HTML % figure_name
elif len(figure_paths) > 1:
images_rst = HLIST_HEADER
for figure_name in figure_paths:
images_rst += HLIST_HTML_TEMPLATE % figure_name
return images_rst
The provided code snippet includes necessary dependencies for implementing the `plotly_sg_scraper` function. Write a Python function `def plotly_sg_scraper(block, block_vars, gallery_conf, **kwargs)` to solve the following problem:
Scrape Plotly figures for galleries of examples using sphinx-gallery. Examples should use ``plotly.io.show()`` to display the figure with the custom sphinx_gallery renderer. Since the sphinx_gallery renderer generates both html and static png files, we simply crawl these files and give them the appropriate path. Original function: from plotly.io._sg_scraper import plotly_sg_scraper Which is based on: https://sphinx-gallery.github.io/stable/advanced.html#example-2-detecting-image-files-on-disk Modified to handle the case where examples_dirs is a list of more than one item. Original code failed to render plots for multiple directories: - Only the rendered the first directory - If multiple directories were specified, matplotlib plots in first directory were not rendered Parameters ---------- block : tuple A tuple containing the (label, content, line_number) of the block. block_vars : dict Dict of block variables. gallery_conf : dict Contains the configuration of Sphinx-Gallery **kwargs : dict Additional keyword arguments to pass to :meth:`~matplotlib.figure.Figure.savefig`, e.g. ``format='svg'``. The ``format`` kwarg in particular is used to set the file extension of the output file (currently only 'png' and 'svg' are supported). Returns ------- rst : str The ReSTructuredText that will be rendered to HTML containing the images. Notes ----- Add this function to the image scrapers
Here is the function:
def plotly_sg_scraper(block, block_vars, gallery_conf, **kwargs):
"""Scrape Plotly figures for galleries of examples using
sphinx-gallery.
Examples should use ``plotly.io.show()`` to display the figure with
the custom sphinx_gallery renderer.
Since the sphinx_gallery renderer generates both html and static png
files, we simply crawl these files and give them the appropriate path.
Original function:
from plotly.io._sg_scraper import plotly_sg_scraper
Which is based on:
https://sphinx-gallery.github.io/stable/advanced.html#example-2-detecting-image-files-on-disk
Modified to handle the case where examples_dirs is a list of more than one item.
Original code failed to render plots for multiple directories:
- Only the rendered the first directory
- If multiple directories were specified, matplotlib plots in first directory were not rendered
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
**kwargs : dict
Additional keyword arguments to pass to
:meth:`~matplotlib.figure.Figure.savefig`, e.g. ``format='svg'``.
The ``format`` kwarg in particular is used to set the file extension
of the output file (currently only 'png' and 'svg' are supported).
Returns
-------
rst : str
The ReSTructuredText that will be rendered to HTML containing
the images.
Notes
-----
Add this function to the image scrapers
"""
examples_dir = os.path.dirname(block_vars["src_file"])
pngs = sorted(glob(os.path.join(examples_dir, "*.png")))
htmls = sorted(glob(os.path.join(examples_dir, "*.html")))
image_path_iterator = block_vars["image_path_iterator"]
image_names = list()
seen = set()
for html, png in zip(htmls, pngs):
if png not in seen:
seen |= set(png)
# the incrementor simply increments the filename as long as html/png are found
# _001.png, _002.png, _003.png, etc.
this_image_path_png = next(image_path_iterator)
this_image_path_html = os.path.splitext(this_image_path_png)[0] + ".html"
image_names.append(this_image_path_html)
shutil.move(png, this_image_path_png)
shutil.move(html, this_image_path_html)
# Use the `figure_rst` helper function to generate rST for image files
return figure_rst(image_names, gallery_conf["src_dir"]) | Scrape Plotly figures for galleries of examples using sphinx-gallery. Examples should use ``plotly.io.show()`` to display the figure with the custom sphinx_gallery renderer. Since the sphinx_gallery renderer generates both html and static png files, we simply crawl these files and give them the appropriate path. Original function: from plotly.io._sg_scraper import plotly_sg_scraper Which is based on: https://sphinx-gallery.github.io/stable/advanced.html#example-2-detecting-image-files-on-disk Modified to handle the case where examples_dirs is a list of more than one item. Original code failed to render plots for multiple directories: - Only the rendered the first directory - If multiple directories were specified, matplotlib plots in first directory were not rendered Parameters ---------- block : tuple A tuple containing the (label, content, line_number) of the block. block_vars : dict Dict of block variables. gallery_conf : dict Contains the configuration of Sphinx-Gallery **kwargs : dict Additional keyword arguments to pass to :meth:`~matplotlib.figure.Figure.savefig`, e.g. ``format='svg'``. The ``format`` kwarg in particular is used to set the file extension of the output file (currently only 'png' and 'svg' are supported). Returns ------- rst : str The ReSTructuredText that will be rendered to HTML containing the images. Notes ----- Add this function to the image scrapers |
167,430 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `mean_absolute_percent_error` function. Write a Python function `def mean_absolute_percent_error(y_true, y_pred)` to solve the following problem:
Calculates mean absolute percentage error. :param y_true: observed values given in a list (or numpy array) :param y_pred: predicted values given in a list (or numpy array) :return: mean absolute percent error
Here is the function:
def mean_absolute_percent_error(y_true, y_pred):
"""Calculates mean absolute percentage error.
:param y_true: observed values given in a list (or numpy array)
:param y_pred: predicted values given in a list (or numpy array)
:return: mean absolute percent error
"""
smallest_denominator = np.min(np.abs(y_true))
if smallest_denominator == 0:
warnings.warn("y_true contains 0. MAPE is undefined.")
return None
elif smallest_denominator < 1e-8:
warnings.warn("y_true contains very small values. MAPE is likely highly volatile.")
return 100 * (np.abs(y_true - y_pred) / np.abs(y_true)).mean() | Calculates mean absolute percentage error. :param y_true: observed values given in a list (or numpy array) :param y_pred: predicted values given in a list (or numpy array) :return: mean absolute percent error |
167,431 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `median_absolute_percent_error` function. Write a Python function `def median_absolute_percent_error(y_true, y_pred)` to solve the following problem:
Calculates median absolute percentage error. :param y_true: observed values given in a list (or numpy array) :param y_pred: predicted values given in a list (or numpy array) :return: median absolute percent error
Here is the function:
def median_absolute_percent_error(y_true, y_pred):
"""Calculates median absolute percentage error.
:param y_true: observed values given in a list (or numpy array)
:param y_pred: predicted values given in a list (or numpy array)
:return: median absolute percent error
"""
smallest_denominator = np.min(np.abs(y_true))
if smallest_denominator == 0:
warnings.warn("y_true contains 0. MedAPE is undefined.")
return None
elif smallest_denominator < 1e-8:
num_small = len(y_true[y_true < 1e-8])
if num_small > (len(y_true) - 1) // 2:
# if too many very small values, median is affected
warnings.warn("y_true contains very small values. MedAPE is likely highly volatile.")
return 100 * np.median((np.abs(y_true - y_pred) / np.abs(y_true))) | Calculates median absolute percentage error. :param y_true: observed values given in a list (or numpy array) :param y_pred: predicted values given in a list (or numpy array) :return: median absolute percent error |
167,432 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `symmetric_mean_absolute_percent_error` function. Write a Python function `def symmetric_mean_absolute_percent_error(y_true, y_pred)` to solve the following problem:
Calculates symmetric mean absolute percentage error Note that we do not include a factor of 2 in the denominator, so the range is 0% to 100%. :param y_true: observed values given in a list (or numpy array) :param y_pred: predicted values given in a list (or numpy array) :return: symmetric mean absolute percent error
Here is the function:
def symmetric_mean_absolute_percent_error(y_true, y_pred):
"""Calculates symmetric mean absolute percentage error
Note that we do not include a factor of 2 in the denominator, so the range is 0% to 100%.
:param y_true: observed values given in a list (or numpy array)
:param y_pred: predicted values given in a list (or numpy array)
:return: symmetric mean absolute percent error
"""
smallest_denominator = np.min(np.abs(y_true) + np.abs(y_pred))
if smallest_denominator == 0:
warnings.warn("denominator contains 0. sMAPE is undefined.")
return None
elif smallest_denominator < 1e-8:
warnings.warn("denominator contains very small values. sMAPE is likely highly volatile.")
return 100 * (np.abs(y_true - y_pred) / (np.abs(y_true) + np.abs(y_pred))).mean() | Calculates symmetric mean absolute percentage error Note that we do not include a factor of 2 in the denominator, so the range is 0% to 100%. :param y_true: observed values given in a list (or numpy array) :param y_pred: predicted values given in a list (or numpy array) :return: symmetric mean absolute percent error |
167,433 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `root_mean_squared_error` function. Write a Python function `def root_mean_squared_error(y_true, y_pred)` to solve the following problem:
Calculates root mean square error. :param y_true: observed values given in a list (or numpy array) :param y_pred: predicted values given in a list (or numpy array) :return: mean absolute percent error
Here is the function:
def root_mean_squared_error(y_true, y_pred):
"""Calculates root mean square error.
:param y_true: observed values given in a list (or numpy array)
:param y_pred: predicted values given in a list (or numpy array)
:return: mean absolute percent error
"""
return math.sqrt(mean_squared_error(y_true, y_pred)) | Calculates root mean square error. :param y_true: observed values given in a list (or numpy array) :param y_pred: predicted values given in a list (or numpy array) :return: mean absolute percent error |
167,434 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `correlation` function. Write a Python function `def correlation(y_true, y_pred)` to solve the following problem:
Calculates correlation. :param y_true: observed values given in a list (or numpy array) :param y_pred: predicted values given in a list (or numpy array) :return: correlation
Here is the function:
def correlation(y_true, y_pred):
"""Calculates correlation.
:param y_true: observed values given in a list (or numpy array)
:param y_pred: predicted values given in a list (or numpy array)
:return: correlation
"""
if np.unique(y_true).size == 1:
warnings.warn("y_true is constant. Correlation is not defined.")
return None
elif np.unique(y_pred).size == 1:
warnings.warn("y_pred is constant. Correlation is not defined.")
return None
else:
return pearsonr(y_true, y_pred)[0] | Calculates correlation. :param y_true: observed values given in a list (or numpy array) :param y_pred: predicted values given in a list (or numpy array) :return: correlation |
167,435 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
def quantile_loss(y_true, y_pred, q: float = 0.95):
"""Calculates the quantile (pinball) loss with quantile q of y_true and y_pred.
:param y_true: one column of true values.
:type y_true: list or numpy array
:param y_pred: one column of predicted values.
:type y_pred: list or numpy array.
:param q: the quantile.
:type q: float
:return: quantile loss.
:returns: float
"""
return np.where(y_true < y_pred, (1 - q) * (y_pred - y_true), q * (y_true - y_pred)).mean()
The provided code snippet includes necessary dependencies for implementing the `quantile_loss_q` function. Write a Python function `def quantile_loss_q(q)` to solve the following problem:
Returns quantile loss function for the specified quantile
Here is the function:
def quantile_loss_q(q):
"""Returns quantile loss function for the specified quantile"""
def quantile_loss_wrapper(y_true, y_pred):
return quantile_loss(y_true, y_pred, q=q)
return quantile_loss_wrapper | Returns quantile loss function for the specified quantile |
167,436 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
def valid_elements_for_evaluation(
reference_arrays: List[Union[np.array, pd.Series, List[Union[int, float]]]],
arrays: List[Optional[Union[int, float, np.array, pd.Series, List[Union[int, float]]]]],
reference_array_names: str,
drop_leading_only: bool,
keep_inf: bool):
"""Keeps finite elements from reference_array, and corresponding elements in *arrays.
Parameters
----------
reference_arrays : `list` [`numpy.array`, `pandas.Series` or `list` [`int`, `float`]]
The reference arrays where the indices of NA/infs are populated.
If length is longer than 1, a logical and will be used to choose valid elements.
arrays : `list` [`int`, `float`, `numpy.array`, `pandas.Series` or `list` [`int`, `float`]]
The arrays with the indices of NA/infs in ``reference_array`` to be dropped.
reference_array_names : `str`
The reference array name to be printed in the warning.
drop_leading_only : `bool`
True means dropping the leading NA/infs only
(drop the leading indices whose values are not valid in any reference array).
False means dropping all NA/infs regardless of where they are.
keep_inf : `bool`
True means dropping NA only.
False means dropping both NA and INF.
Returns
-------
arrays_valid_elements : `list` [`numpy.array`]
List of numpy arrays with valid indices [*reference_arrays, *arrays]
"""
if not all_equal_length(*reference_arrays, *arrays):
raise Exception("length of arrays do not match")
if len(reference_arrays) == 0:
return reference_arrays + arrays
reference_arrays = [np.array(reference_array) for reference_array in reference_arrays]
array_length = reference_arrays[0].shape[0]
# Defines a function to perform the opposite of `numpy.isnan`.
def is_not_nan(x):
"""Gets the True/False for elements that are not/are NANs.
Parameters
----------
x : array-like
The input array.
Returns
-------
is_not_nan : `numpy.array`
True/False array indicating whethere the elements are not NAN/ are NAN.
"""
return ~np.isnan(x)
validation_func = is_not_nan if keep_inf else np.isfinite
# Finds the indices of finite elements in reference array
keep = [validation_func(reference_array) for reference_array in reference_arrays]
if drop_leading_only:
# Gets the index where the first True is.
# All the False after this True will not be heading False
# and shouldn't be dropped.
# If multiple arrays in ``reference_arrays``,
# this will be the minimum.
valid_indices = [np.where(array)[0] for array in keep]
heading_lengths = [
length[0] if length.shape[0] > 0 else array_length for length in valid_indices]
heading_length = min(heading_lengths)
# Generates arrays with the is_heading flag.
is_not_heading = np.repeat([False, True], [heading_length, array_length - heading_length])
else:
is_not_heading = np.repeat([False, True], [array_length, 0])
keep = np.logical_and.reduce(keep, axis=0)
keep = np.logical_or(keep, is_not_heading)
num_remaining = keep.sum()
num_removed = array_length - num_remaining
removed_elements = "NA" if keep_inf else "NA or infinite"
if num_remaining == 0:
warnings.warn(f"There are 0 non-null elements for evaluation.")
if num_removed > 0:
warnings.warn(
f"{num_removed} value(s) in {reference_array_names} were {removed_elements} and are omitted in error calc.")
# Keeps these indices in all arrays. Leaves float, int, and None as-is
return [array[keep] for array in reference_arrays] + [np.array(array)[keep] if (
array is not None and not isinstance(array, (float, int, np.float32)))
else array
for array in arrays]
The provided code snippet includes necessary dependencies for implementing the `fraction_within_bands` function. Write a Python function `def fraction_within_bands(observed, lower, upper)` to solve the following problem:
Computes the fraction of observed values between lower and upper. :param observed: pd.Series or np.array, numeric, observed values :param lower: pd.Series or np.array, numeric, lower bound :param upper: pd.Series or np.array, numeric, upper bound :return: float between 0.0 and 1.0
Here is the function:
def fraction_within_bands(observed, lower, upper):
"""Computes the fraction of observed values between lower and upper.
:param observed: pd.Series or np.array, numeric, observed values
:param lower: pd.Series or np.array, numeric, lower bound
:param upper: pd.Series or np.array, numeric, upper bound
:return: float between 0.0 and 1.0
"""
observed, lower, upper = valid_elements_for_evaluation(
reference_arrays=[observed],
arrays=[lower, upper],
reference_array_names="y_true",
drop_leading_only=False,
keep_inf=False)
lower, upper, observed = valid_elements_for_evaluation(
reference_arrays=[lower, upper],
arrays=[observed],
reference_array_names="lower/upper bound",
drop_leading_only=True,
keep_inf=False)
num_reversed = np.count_nonzero(upper < lower)
if num_reversed > 0:
warnings.warn(f"{num_reversed} of {len(observed)} upper bound values are smaller than the lower bound")
return np.count_nonzero((observed > lower) & (observed < upper)) / len(observed) if len(observed) > 0 else None | Computes the fraction of observed values between lower and upper. :param observed: pd.Series or np.array, numeric, observed values :param lower: pd.Series or np.array, numeric, lower bound :param upper: pd.Series or np.array, numeric, upper bound :return: float between 0.0 and 1.0 |
167,437 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
def valid_elements_for_evaluation(
reference_arrays: List[Union[np.array, pd.Series, List[Union[int, float]]]],
arrays: List[Optional[Union[int, float, np.array, pd.Series, List[Union[int, float]]]]],
reference_array_names: str,
drop_leading_only: bool,
keep_inf: bool):
"""Keeps finite elements from reference_array, and corresponding elements in *arrays.
Parameters
----------
reference_arrays : `list` [`numpy.array`, `pandas.Series` or `list` [`int`, `float`]]
The reference arrays where the indices of NA/infs are populated.
If length is longer than 1, a logical and will be used to choose valid elements.
arrays : `list` [`int`, `float`, `numpy.array`, `pandas.Series` or `list` [`int`, `float`]]
The arrays with the indices of NA/infs in ``reference_array`` to be dropped.
reference_array_names : `str`
The reference array name to be printed in the warning.
drop_leading_only : `bool`
True means dropping the leading NA/infs only
(drop the leading indices whose values are not valid in any reference array).
False means dropping all NA/infs regardless of where they are.
keep_inf : `bool`
True means dropping NA only.
False means dropping both NA and INF.
Returns
-------
arrays_valid_elements : `list` [`numpy.array`]
List of numpy arrays with valid indices [*reference_arrays, *arrays]
"""
if not all_equal_length(*reference_arrays, *arrays):
raise Exception("length of arrays do not match")
if len(reference_arrays) == 0:
return reference_arrays + arrays
reference_arrays = [np.array(reference_array) for reference_array in reference_arrays]
array_length = reference_arrays[0].shape[0]
# Defines a function to perform the opposite of `numpy.isnan`.
def is_not_nan(x):
"""Gets the True/False for elements that are not/are NANs.
Parameters
----------
x : array-like
The input array.
Returns
-------
is_not_nan : `numpy.array`
True/False array indicating whethere the elements are not NAN/ are NAN.
"""
return ~np.isnan(x)
validation_func = is_not_nan if keep_inf else np.isfinite
# Finds the indices of finite elements in reference array
keep = [validation_func(reference_array) for reference_array in reference_arrays]
if drop_leading_only:
# Gets the index where the first True is.
# All the False after this True will not be heading False
# and shouldn't be dropped.
# If multiple arrays in ``reference_arrays``,
# this will be the minimum.
valid_indices = [np.where(array)[0] for array in keep]
heading_lengths = [
length[0] if length.shape[0] > 0 else array_length for length in valid_indices]
heading_length = min(heading_lengths)
# Generates arrays with the is_heading flag.
is_not_heading = np.repeat([False, True], [heading_length, array_length - heading_length])
else:
is_not_heading = np.repeat([False, True], [array_length, 0])
keep = np.logical_and.reduce(keep, axis=0)
keep = np.logical_or(keep, is_not_heading)
num_remaining = keep.sum()
num_removed = array_length - num_remaining
removed_elements = "NA" if keep_inf else "NA or infinite"
if num_remaining == 0:
warnings.warn(f"There are 0 non-null elements for evaluation.")
if num_removed > 0:
warnings.warn(
f"{num_removed} value(s) in {reference_array_names} were {removed_elements} and are omitted in error calc.")
# Keeps these indices in all arrays. Leaves float, int, and None as-is
return [array[keep] for array in reference_arrays] + [np.array(array)[keep] if (
array is not None and not isinstance(array, (float, int, np.float32)))
else array
for array in arrays]
The provided code snippet includes necessary dependencies for implementing the `prediction_band_width` function. Write a Python function `def prediction_band_width(observed, lower, upper)` to solve the following problem:
Computes the prediction band width, expressed as a % relative to observed. Width is defined as average ratio of (upper-lower)/observed. :param observed: pd.Series or np.array, numeric, observed values :param lower: pd.Series or np.array, numeric, lower bound :param upper: pd.Series or np.array, numeric, upper bound :return: float, average percentage width
Here is the function:
def prediction_band_width(observed, lower, upper):
"""Computes the prediction band width, expressed as a % relative to observed.
Width is defined as average ratio of (upper-lower)/observed.
:param observed: pd.Series or np.array, numeric, observed values
:param lower: pd.Series or np.array, numeric, lower bound
:param upper: pd.Series or np.array, numeric, upper bound
:return: float, average percentage width
"""
observed, lower, upper = valid_elements_for_evaluation(
reference_arrays=[observed],
arrays=[lower, upper],
reference_array_names="y_true",
drop_leading_only=False,
keep_inf=False)
lower, upper, observed = valid_elements_for_evaluation(
reference_arrays=[lower, upper],
arrays=[observed],
reference_array_names="lower/upper bound",
drop_leading_only=True,
keep_inf=True) # Keeps inf from prediction.
observed = np.abs(observed)
num_reversed = np.count_nonzero(upper < lower)
if num_reversed > 0:
warnings.warn(f"{num_reversed} of {len(observed)} upper bound values are smaller than the lower bound")
# if there are 0s in observed, relative size is undefined
return 100.0 * np.mean(np.abs(upper - lower) / observed) if len(observed) > 0 and observed.min() > 0 else None | Computes the prediction band width, expressed as a % relative to observed. Width is defined as average ratio of (upper-lower)/observed. :param observed: pd.Series or np.array, numeric, observed values :param lower: pd.Series or np.array, numeric, lower bound :param upper: pd.Series or np.array, numeric, upper bound :return: float, average percentage width |
167,438 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
def valid_elements_for_evaluation(
reference_arrays: List[Union[np.array, pd.Series, List[Union[int, float]]]],
arrays: List[Optional[Union[int, float, np.array, pd.Series, List[Union[int, float]]]]],
reference_array_names: str,
drop_leading_only: bool,
keep_inf: bool):
"""Keeps finite elements from reference_array, and corresponding elements in *arrays.
Parameters
----------
reference_arrays : `list` [`numpy.array`, `pandas.Series` or `list` [`int`, `float`]]
The reference arrays where the indices of NA/infs are populated.
If length is longer than 1, a logical and will be used to choose valid elements.
arrays : `list` [`int`, `float`, `numpy.array`, `pandas.Series` or `list` [`int`, `float`]]
The arrays with the indices of NA/infs in ``reference_array`` to be dropped.
reference_array_names : `str`
The reference array name to be printed in the warning.
drop_leading_only : `bool`
True means dropping the leading NA/infs only
(drop the leading indices whose values are not valid in any reference array).
False means dropping all NA/infs regardless of where they are.
keep_inf : `bool`
True means dropping NA only.
False means dropping both NA and INF.
Returns
-------
arrays_valid_elements : `list` [`numpy.array`]
List of numpy arrays with valid indices [*reference_arrays, *arrays]
"""
if not all_equal_length(*reference_arrays, *arrays):
raise Exception("length of arrays do not match")
if len(reference_arrays) == 0:
return reference_arrays + arrays
reference_arrays = [np.array(reference_array) for reference_array in reference_arrays]
array_length = reference_arrays[0].shape[0]
# Defines a function to perform the opposite of `numpy.isnan`.
def is_not_nan(x):
"""Gets the True/False for elements that are not/are NANs.
Parameters
----------
x : array-like
The input array.
Returns
-------
is_not_nan : `numpy.array`
True/False array indicating whethere the elements are not NAN/ are NAN.
"""
return ~np.isnan(x)
validation_func = is_not_nan if keep_inf else np.isfinite
# Finds the indices of finite elements in reference array
keep = [validation_func(reference_array) for reference_array in reference_arrays]
if drop_leading_only:
# Gets the index where the first True is.
# All the False after this True will not be heading False
# and shouldn't be dropped.
# If multiple arrays in ``reference_arrays``,
# this will be the minimum.
valid_indices = [np.where(array)[0] for array in keep]
heading_lengths = [
length[0] if length.shape[0] > 0 else array_length for length in valid_indices]
heading_length = min(heading_lengths)
# Generates arrays with the is_heading flag.
is_not_heading = np.repeat([False, True], [heading_length, array_length - heading_length])
else:
is_not_heading = np.repeat([False, True], [array_length, 0])
keep = np.logical_and.reduce(keep, axis=0)
keep = np.logical_or(keep, is_not_heading)
num_remaining = keep.sum()
num_removed = array_length - num_remaining
removed_elements = "NA" if keep_inf else "NA or infinite"
if num_remaining == 0:
warnings.warn(f"There are 0 non-null elements for evaluation.")
if num_removed > 0:
warnings.warn(
f"{num_removed} value(s) in {reference_array_names} were {removed_elements} and are omitted in error calc.")
# Keeps these indices in all arrays. Leaves float, int, and None as-is
return [array[keep] for array in reference_arrays] + [np.array(array)[keep] if (
array is not None and not isinstance(array, (float, int, np.float32)))
else array
for array in arrays]
The provided code snippet includes necessary dependencies for implementing the `mean_interval_score` function. Write a Python function `def mean_interval_score(observed, lower, upper, coverage)` to solve the following problem:
Calculates the mean interval score. If an observed value falls within the interval, the score is simply the width of the interval. If an observed value falls outside the interval, the score is the width of the interval plus an error term proportional to distance between the actual and its closest interval boundary. The proportionality constant is 2.0 / (1.0 - `coverage`). See `Strictly Proper Scoring Rules, Prediction, and Estimation, Tilmann Gneiting and Adrian E. Raftery, 2007, Journal of the American Statistical Association, Volume 102, 2007 - Issue 477`. Parameters ---------- observed: `pandas.Series` or `numpy.array` Numeric, observed values. lower: `pandas.Series` or `numpy.array` Numeric, lower bound. upper: `pandas.Series` or `numpy.array` Numeric, upper bound. coverage: `float` Intended coverage of the prediction bands (0.0 to 1.0) Returns ------- mean_interval_score: `float` The mean interval score.
Here is the function:
def mean_interval_score(observed, lower, upper, coverage):
"""Calculates the mean interval score.
If an observed value falls within the interval, the score is simply the width of the interval.
If an observed value falls outside the interval, the score is the width of the interval plus an error term
proportional to distance between the actual and its closest interval boundary.
The proportionality constant is 2.0 / (1.0 - `coverage`).
See `Strictly Proper Scoring Rules, Prediction, and Estimation, Tilmann Gneiting and Adrian E. Raftery, 2007,
Journal of the American Statistical Association, Volume 102, 2007 - Issue 477`.
Parameters
----------
observed: `pandas.Series` or `numpy.array`
Numeric, observed values.
lower: `pandas.Series` or `numpy.array`
Numeric, lower bound.
upper: `pandas.Series` or `numpy.array`
Numeric, upper bound.
coverage: `float`
Intended coverage of the prediction bands (0.0 to 1.0)
Returns
-------
mean_interval_score: `float`
The mean interval score.
"""
observed, lower, upper = valid_elements_for_evaluation(
reference_arrays=[observed],
arrays=[lower, upper],
reference_array_names="y_true",
drop_leading_only=False,
keep_inf=False)
lower, upper, observed = valid_elements_for_evaluation(
reference_arrays=[lower, upper],
arrays=[observed],
reference_array_names="lower/upper bounds",
drop_leading_only=False,
keep_inf=True)
interval_width = upper - lower
error_lower = np.where(observed < lower, 2.0 * (lower - observed) / (1.0 - coverage), 0.0)
error_upper = np.where(observed > upper, 2.0 * (observed - upper) / (1.0 - coverage), 0.0)
interval_score = interval_width + error_lower + error_upper
return np.mean(interval_score) | Calculates the mean interval score. If an observed value falls within the interval, the score is simply the width of the interval. If an observed value falls outside the interval, the score is the width of the interval plus an error term proportional to distance between the actual and its closest interval boundary. The proportionality constant is 2.0 / (1.0 - `coverage`). See `Strictly Proper Scoring Rules, Prediction, and Estimation, Tilmann Gneiting and Adrian E. Raftery, 2007, Journal of the American Statistical Association, Volume 102, 2007 - Issue 477`. Parameters ---------- observed: `pandas.Series` or `numpy.array` Numeric, observed values. lower: `pandas.Series` or `numpy.array` Numeric, lower bound. upper: `pandas.Series` or `numpy.array` Numeric, upper bound. coverage: `float` Intended coverage of the prediction bands (0.0 to 1.0) Returns ------- mean_interval_score: `float` The mean interval score. |
167,439 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
def valid_elements_for_evaluation(
reference_arrays: List[Union[np.array, pd.Series, List[Union[int, float]]]],
arrays: List[Optional[Union[int, float, np.array, pd.Series, List[Union[int, float]]]]],
reference_array_names: str,
drop_leading_only: bool,
keep_inf: bool):
"""Keeps finite elements from reference_array, and corresponding elements in *arrays.
Parameters
----------
reference_arrays : `list` [`numpy.array`, `pandas.Series` or `list` [`int`, `float`]]
The reference arrays where the indices of NA/infs are populated.
If length is longer than 1, a logical and will be used to choose valid elements.
arrays : `list` [`int`, `float`, `numpy.array`, `pandas.Series` or `list` [`int`, `float`]]
The arrays with the indices of NA/infs in ``reference_array`` to be dropped.
reference_array_names : `str`
The reference array name to be printed in the warning.
drop_leading_only : `bool`
True means dropping the leading NA/infs only
(drop the leading indices whose values are not valid in any reference array).
False means dropping all NA/infs regardless of where they are.
keep_inf : `bool`
True means dropping NA only.
False means dropping both NA and INF.
Returns
-------
arrays_valid_elements : `list` [`numpy.array`]
List of numpy arrays with valid indices [*reference_arrays, *arrays]
"""
if not all_equal_length(*reference_arrays, *arrays):
raise Exception("length of arrays do not match")
if len(reference_arrays) == 0:
return reference_arrays + arrays
reference_arrays = [np.array(reference_array) for reference_array in reference_arrays]
array_length = reference_arrays[0].shape[0]
# Defines a function to perform the opposite of `numpy.isnan`.
def is_not_nan(x):
"""Gets the True/False for elements that are not/are NANs.
Parameters
----------
x : array-like
The input array.
Returns
-------
is_not_nan : `numpy.array`
True/False array indicating whethere the elements are not NAN/ are NAN.
"""
return ~np.isnan(x)
validation_func = is_not_nan if keep_inf else np.isfinite
# Finds the indices of finite elements in reference array
keep = [validation_func(reference_array) for reference_array in reference_arrays]
if drop_leading_only:
# Gets the index where the first True is.
# All the False after this True will not be heading False
# and shouldn't be dropped.
# If multiple arrays in ``reference_arrays``,
# this will be the minimum.
valid_indices = [np.where(array)[0] for array in keep]
heading_lengths = [
length[0] if length.shape[0] > 0 else array_length for length in valid_indices]
heading_length = min(heading_lengths)
# Generates arrays with the is_heading flag.
is_not_heading = np.repeat([False, True], [heading_length, array_length - heading_length])
else:
is_not_heading = np.repeat([False, True], [array_length, 0])
keep = np.logical_and.reduce(keep, axis=0)
keep = np.logical_or(keep, is_not_heading)
num_remaining = keep.sum()
num_removed = array_length - num_remaining
removed_elements = "NA" if keep_inf else "NA or infinite"
if num_remaining == 0:
warnings.warn(f"There are 0 non-null elements for evaluation.")
if num_removed > 0:
warnings.warn(
f"{num_removed} value(s) in {reference_array_names} were {removed_elements} and are omitted in error calc.")
# Keeps these indices in all arrays. Leaves float, int, and None as-is
return [array[keep] for array in reference_arrays] + [np.array(array)[keep] if (
array is not None and not isinstance(array, (float, int, np.float32)))
else array
for array in arrays]
class ValidationMetricEnum(Enum):
"""Valid diagnostic metrics.
The values tuple is ``(score_func: callable, greater_is_better: boolean, short_name: str)``
"""
BAND_WIDTH = (prediction_band_width, False, "band_width")
BAND_COVERAGE = (fraction_within_bands, True, "band_coverage")
MEAN_INTERVAL_SCORE = (mean_interval_score, False, "MIS")
"""Mean interval score"""
def get_metric_func(self):
"""Returns the metric function."""
return self.value[0]
def get_metric_greater_is_better(self):
"""Returns the greater_is_better boolean."""
return self.value[1]
def get_metric_name(self):
"""Returns the short name."""
return self.value[2]
PREDICTION_BAND_WIDTH = "Prediction Band Width (%)"
PREDICTION_BAND_COVERAGE = "Prediction Band Coverage (fraction)"
LOWER_BAND_COVERAGE = "Coverage: Lower Band"
UPPER_BAND_COVERAGE = "Coverage: Upper Band"
COVERAGE_VS_INTENDED_DIFF = "Coverage Diff: Actual_Coverage - Intended_Coverage"
The provided code snippet includes necessary dependencies for implementing the `calc_pred_coverage` function. Write a Python function `def calc_pred_coverage(observed, predicted, lower, upper, coverage)` to solve the following problem:
Calculates the prediction coverages: prediction band width, prediction band coverage etc. :param observed: pd.Series or np.array, numeric, observed values :param predicted: pd.Series or np.array, numeric, predicted values :param lower: pd.Series or np.array, numeric, lower bound :param upper: pd.Series or np.array, numeric, upper bound :param coverage: float, intended coverage of the prediction bands (0.0 to 1.0) :return: prediction band width, prediction band coverage etc.
Here is the function:
def calc_pred_coverage(observed, predicted, lower, upper, coverage):
"""Calculates the prediction coverages:
prediction band width, prediction band coverage etc.
:param observed: pd.Series or np.array, numeric, observed values
:param predicted: pd.Series or np.array, numeric, predicted values
:param lower: pd.Series or np.array, numeric, lower bound
:param upper: pd.Series or np.array, numeric, upper bound
:param coverage: float, intended coverage of the prediction bands (0.0 to 1.0)
:return: prediction band width, prediction band coverage etc.
"""
observed, predicted, lower, upper = valid_elements_for_evaluation(
reference_arrays=[observed],
arrays=[predicted, lower, upper],
reference_array_names="y_true",
drop_leading_only=False,
keep_inf=False)
predicted, lower, upper, observed = valid_elements_for_evaluation(
reference_arrays=[predicted, lower, upper],
arrays=[observed],
reference_array_names="y_pred and lower/upper bounds",
drop_leading_only=True,
keep_inf=True)
metrics = {}
if len(observed) > 0:
# Relative size of prediction bands vs actual, as a percent.
enum = ValidationMetricEnum.BAND_WIDTH
metric_func = enum.get_metric_func()
metrics.update({PREDICTION_BAND_WIDTH: metric_func(observed, lower, upper)})
enum = ValidationMetricEnum.BAND_COVERAGE
metric_func = enum.get_metric_func()
# Fraction of observations within the bands.
metrics.update({PREDICTION_BAND_COVERAGE: metric_func(observed, lower, upper)})
# Fraction of observations within the lower band.
metrics.update({LOWER_BAND_COVERAGE: metric_func(observed, lower, predicted)})
# Fraction of observations within the upper band.
metrics.update({UPPER_BAND_COVERAGE: metric_func(observed, predicted, upper)})
# Difference between actual and intended coverage.
metrics.update({COVERAGE_VS_INTENDED_DIFF: (metrics[PREDICTION_BAND_COVERAGE] - coverage)})
# Mean interval score.
enum = ValidationMetricEnum.MEAN_INTERVAL_SCORE
metric_func = enum.get_metric_func()
metric_name = enum.get_metric_name()
metrics.update({metric_name: (metric_func(observed, lower, upper, coverage))})
return metrics | Calculates the prediction coverages: prediction band width, prediction band coverage etc. :param observed: pd.Series or np.array, numeric, observed values :param predicted: pd.Series or np.array, numeric, predicted values :param lower: pd.Series or np.array, numeric, lower bound :param upper: pd.Series or np.array, numeric, upper bound :param coverage: float, intended coverage of the prediction bands (0.0 to 1.0) :return: prediction band width, prediction band coverage etc. |
167,440 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `elementwise_residual` function. Write a Python function `def elementwise_residual(true_val, pred_val)` to solve the following problem:
The residual between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- residual : float The residual, true minus predicted
Here is the function:
def elementwise_residual(true_val, pred_val):
"""The residual between a single true and predicted value.
Parameters
----------
true_val : float
True value.
pred_val : float
Predicted value.
Returns
-------
residual : float
The residual, true minus predicted
"""
return true_val - pred_val | The residual between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- residual : float The residual, true minus predicted |
167,441 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `elementwise_absolute_error` function. Write a Python function `def elementwise_absolute_error(true_val, pred_val)` to solve the following problem:
The absolute error between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- residual : float Absolute error, |true_val - pred_val|
Here is the function:
def elementwise_absolute_error(true_val, pred_val):
"""The absolute error between a single true and predicted value.
Parameters
----------
true_val : float
True value.
pred_val : float
Predicted value.
Returns
-------
residual : float
Absolute error, |true_val - pred_val|
"""
return abs(true_val - pred_val) | The absolute error between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- residual : float Absolute error, |true_val - pred_val| |
167,442 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `elementwise_squared_error` function. Write a Python function `def elementwise_squared_error(true_val, pred_val)` to solve the following problem:
The absolute error between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- residual : float Squared error, (true_val - pred_val)^2
Here is the function:
def elementwise_squared_error(true_val, pred_val):
"""The absolute error between a single true and predicted value.
Parameters
----------
true_val : float
True value.
pred_val : float
Predicted value.
Returns
-------
residual : float
Squared error, (true_val - pred_val)^2
"""
return (true_val - pred_val) ** 2 | The absolute error between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- residual : float Squared error, (true_val - pred_val)^2 |
167,443 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `elementwise_absolute_percent_error` function. Write a Python function `def elementwise_absolute_percent_error(true_val, pred_val)` to solve the following problem:
The absolute percent error between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- percent_error : float Percent error, pred_val / true_val - 1
Here is the function:
def elementwise_absolute_percent_error(true_val, pred_val):
"""The absolute percent error between a single true and predicted value.
Parameters
----------
true_val : float
True value.
pred_val : float
Predicted value.
Returns
-------
percent_error : float
Percent error, pred_val / true_val - 1
"""
if true_val == 0:
warnings.warn("true_val is 0. Percent error is undefined.")
return np.nan
elif true_val < 1e-8:
warnings.warn("true_val is less than 1e-8. Percent error is very likely highly volatile.")
return 100 * abs(true_val - pred_val) / abs(true_val) | The absolute percent error between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- percent_error : float Percent error, pred_val / true_val - 1 |
167,444 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `elementwise_symmetric_absolute_percent_error` function. Write a Python function `def elementwise_symmetric_absolute_percent_error(true_val, pred_val)` to solve the following problem:
The symmetric absolute percent error between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- symmetric_absolute_percent_error : float Symmetric Absolute Percent error, abs(true_val - pred_val) / (abs(true_val) + abs(pred_val))
Here is the function:
def elementwise_symmetric_absolute_percent_error(true_val, pred_val):
"""The symmetric absolute percent error between a single true and predicted value.
Parameters
----------
true_val : float
True value.
pred_val : float
Predicted value.
Returns
-------
symmetric_absolute_percent_error : float
Symmetric Absolute Percent error, abs(true_val - pred_val) / (abs(true_val) + abs(pred_val))
"""
denominator = abs(true_val) + abs(pred_val)
if denominator == 0:
warnings.warn("true_val and pred_val are 0. Symmetric absolute percent error is undefined.")
return None
elif denominator < 1e-8:
warnings.warn("denominator contains very small values. Symmetric absolute percent error is "
"very likely highly volatile.")
return 100 * abs(true_val - pred_val) / (abs(true_val) + abs(pred_val)) | The symmetric absolute percent error between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- symmetric_absolute_percent_error : float Symmetric Absolute Percent error, abs(true_val - pred_val) / (abs(true_val) + abs(pred_val)) |
167,445 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `elementwise_quantile` function. Write a Python function `def elementwise_quantile(true_val, pred_val, q)` to solve the following problem:
The quantile loss between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- quantile_loss : float Quantile loss, absolute error weighed by ``q`` for underpredictions and ``1-q`` for overpredictions.
Here is the function:
def elementwise_quantile(true_val, pred_val, q):
"""The quantile loss between a single true and predicted value.
Parameters
----------
true_val : float
True value.
pred_val : float
Predicted value.
Returns
-------
quantile_loss : float
Quantile loss, absolute error weighed by ``q``
for underpredictions and ``1-q`` for overpredictions.
"""
weight = 1 - q if true_val < pred_val else q
return weight * abs(true_val - pred_val) | The quantile loss between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- quantile_loss : float Quantile loss, absolute error weighed by ``q`` for underpredictions and ``1-q`` for overpredictions. |
167,446 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `elementwise_outside_tolerance` function. Write a Python function `def elementwise_outside_tolerance(true_val, pred_val, rtol=0.05)` to solve the following problem:
Whether the relative difference between ``pred_val`` and ``true_val`` is strictly greater than ``rtol``. Parameters ---------- true_val : float True value. pred_val : float Predicted value. rtol : float, default 0.05 Relative error tolerance. For example, 0.05 allows for 5% relative error. Returns ------- is_outside_tolerance : float 1.0 if the error is outside tolerance, else 0.0. A value is outside tolerance if `numpy.isclose` with the specified ``rtol`` and ``atol=0.0`` returns False. See Also --------
Here is the function:
def elementwise_outside_tolerance(true_val, pred_val, rtol=0.05):
"""Whether the relative difference between ``pred_val`` and
``true_val`` is strictly greater than ``rtol``.
Parameters
----------
true_val : float
True value.
pred_val : float
Predicted value.
rtol : float, default 0.05
Relative error tolerance.
For example, 0.05 allows for 5% relative error.
Returns
-------
is_outside_tolerance : float
1.0 if the error is outside tolerance, else 0.0.
A value is outside tolerance if `numpy.isclose`
with the specified ``rtol`` and ``atol=0.0`` returns False.
See Also
--------
"""
return 0.0 if np.isclose(pred_val, true_val, rtol=rtol, atol=0.0) else 1.0 | Whether the relative difference between ``pred_val`` and ``true_val`` is strictly greater than ``rtol``. Parameters ---------- true_val : float True value. pred_val : float Predicted value. rtol : float, default 0.05 Relative error tolerance. For example, 0.05 allows for 5% relative error. Returns ------- is_outside_tolerance : float 1.0 if the error is outside tolerance, else 0.0. A value is outside tolerance if `numpy.isclose` with the specified ``rtol`` and ``atol=0.0`` returns False. See Also -------- |
167,447 | import math
import warnings
from collections import namedtuple
from enum import Enum
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import r2_score
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import COVERAGE_VS_INTENDED_DIFF
from greykite.common.constants import LOWER_BAND_COVERAGE
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import PREDICTED_LOWER_COL
from greykite.common.constants import PREDICTED_UPPER_COL
from greykite.common.constants import PREDICTION_BAND_COVERAGE
from greykite.common.constants import PREDICTION_BAND_WIDTH
from greykite.common.constants import UPPER_BAND_COVERAGE
from greykite.common.logging import LoggingLevelEnum
from greykite.common.logging import log_message
The provided code snippet includes necessary dependencies for implementing the `elementwise_within_bands` function. Write a Python function `def elementwise_within_bands(true_val, lower_val, upper_val)` to solve the following problem:
Whether ``true_val`` is strictly between ``lower_val`` and ``upper_val``. Parameters ---------- true_val : float True value. lower_val : float Lower bound. upper_val : float Upper bound. Returns ------- is_within_band : float 1.0 if error is strictly within the limits, else 0.0
Here is the function:
def elementwise_within_bands(true_val, lower_val, upper_val):
"""Whether ``true_val`` is strictly between ``lower_val`` and ``upper_val``.
Parameters
----------
true_val : float
True value.
lower_val : float
Lower bound.
upper_val : float
Upper bound.
Returns
-------
is_within_band : float
1.0 if error is strictly within the limits, else 0.0
"""
return 1.0 if lower_val < true_val < upper_val else 0.0 | Whether ``true_val`` is strictly between ``lower_val`` and ``upper_val``. Parameters ---------- true_val : float True value. lower_val : float Lower bound. upper_val : float Upper bound. Returns ------- is_within_band : float 1.0 if error is strictly within the limits, else 0.0 |
167,448 | import numpy as np
from greykite.common.features.timeseries_lags import build_agg_lag_df
def impute_with_lags(
df,
value_col,
orders,
agg_func="mean",
iter_num=1):
"""A function to impute timeseries values (given in ``df``) and in ``value_col``
with chosen lagged values or an aggregated of those.
For example for daily data one could use the 7th lag to impute using the
value of the same day of past week as opposed to the closest value available
which can be inferior for business related timeseries.
The imputation can be done multiple times by specifying ``iter_num``
to decrease the number of missing in some cases.
Note that there are no guarantees to impute all missing values with this
method by design.
However the original number of missing values and the final number of missing
values are returned by the function along with the imputed dataframe.
Parameters
----------
df : `pandas.DataFrame`
Input dataframe which must include `value_col` as a column.
value_col : `str`
The column name in ``df`` representing the values of the timeseries.
orders : list of `int`
The lag orders to be used for aggregation.
agg_func : "mean" or callable, default: "mean"
`pandas.Series` -> `float`
An aggregation function to aggregate the chosen lags.
If "mean", uses `pandas.DataFrame.mean`.
iter_num : `int`, default `1`
Maximum number of iterations to impute the series.
Each iteration represent an imputation of the series using the provided
lag orders (``orders``) and return an imputed dataframe.
It might be the case that with one iterations some values
are not imputed but with more iterations one can achieve more
imputed values.
Returns
-------
impute_info : `dict`
A dictionary with following items:
"df" : `pandas.DataFrame`
A dataframe with the imputed values.
"initial_missing_num" : `int`
Initial number of missing values.
"final_missing_num" : `int`
Final number of missing values after imputations.
"""
df = df.copy()
nan_index = df[value_col].isnull()
missing_num = sum(nan_index)
initial_missing_num = missing_num
def nan_agg_func(x):
"""To avoid warnings due to aggregation performed on sub-series
with only NAs, we define an internal modified version of ``agg_func``.
Note that `np.mean` passed to `pandas.DataFrame.apply` ignores NAs and
already has the same effect as `np.nanmean`.
"""
x = x.dropna()
if len(x) == 0:
return np.nan
else:
return agg_func(x)
safe_agg_func = agg_func if isinstance(agg_func, str) else nan_agg_func
i = 0
while i < iter_num and missing_num > 0:
agg_lag_info = build_agg_lag_df(
value_col=value_col,
df=df,
orders_list=[orders],
interval_list=[],
agg_func=safe_agg_func,
agg_name="avglag")
agg_lag_df = agg_lag_info["agg_lag_df"]
# In this case the lagged dataframe will have only one column
# which can be extracted from the list given in the ``"col_names"`` item
agg_col_name = agg_lag_info["col_names"][0]
df.loc[nan_index, value_col] = agg_lag_df.loc[nan_index, agg_col_name]
nan_index = df[value_col].isnull()
missing_num = sum(nan_index)
i += 1
return {
"df": df,
"initial_missing_num": initial_missing_num,
"final_missing_num": missing_num}
The provided code snippet includes necessary dependencies for implementing the `impute_with_lags_multi` function. Write a Python function `def impute_with_lags_multi( df, orders, agg_func=np.mean, iter_num=1, cols=None)` to solve the following problem:
Imputes every column of ``df`` using `~greykite.common.features.timeseries_impute.impute_with_lags`. Parameters ---------- df : `pandas.DataFrame` Input dataframe which must include `value_col` as a column. orders : list of `int` The lag orders to be used for aggregation. agg_func : callable, default `np.mean` `pandas.Series` -> `float` An aggregation function to aggregate the chosen lags. iter_num : `int`, default `1` Maximum number of iterations to impute the series. Each iteration represent an imputation of the series using the provided lag orders (``orders``) and return an imputed dataframe. It might be the case that with one iterations some values are not imputed but with more iterations one can achieve more imputed values. cols : `list` [`str`] or None, default None Which columns to impute. If None, imputes all columns. Returns ------- impute_info : `dict` A dictionary with following items: "df" : `pandas.DataFrame` A dataframe with the imputed values. "missing_info" : `dict` Dictionary with information about the missing info. Key = name of a column in ``df`` Value = dictionary containing: "initial_missing_num" : `int` Initial number of missing values. "final_missing_num" : `int` Final number of missing values after imputation.
Here is the function:
def impute_with_lags_multi(
df,
orders,
agg_func=np.mean,
iter_num=1,
cols=None):
"""Imputes every column of ``df`` using
`~greykite.common.features.timeseries_impute.impute_with_lags`.
Parameters
----------
df : `pandas.DataFrame`
Input dataframe which must include `value_col` as a column.
orders : list of `int`
The lag orders to be used for aggregation.
agg_func : callable, default `np.mean`
`pandas.Series` -> `float`
An aggregation function to aggregate the chosen lags.
iter_num : `int`, default `1`
Maximum number of iterations to impute the series.
Each iteration represent an imputation of the series using the provided
lag orders (``orders``) and return an imputed dataframe.
It might be the case that with one iterations some values
are not imputed but with more iterations one can achieve more
imputed values.
cols : `list` [`str`] or None, default None
Which columns to impute. If None, imputes all columns.
Returns
-------
impute_info : `dict`
A dictionary with following items:
"df" : `pandas.DataFrame`
A dataframe with the imputed values.
"missing_info" : `dict`
Dictionary with information about the missing info.
Key = name of a column in ``df``
Value = dictionary containing:
"initial_missing_num" : `int`
Initial number of missing values.
"final_missing_num" : `int`
Final number of missing values after imputation.
"""
if cols is None:
cols = df.columns
impute_info = {
"df": df.copy(),
"missing_info": {}
}
for col in cols:
# updates each column with the imputed values
col_impute_info = impute_with_lags(
df=df,
value_col=col,
orders=orders,
agg_func=agg_func,
iter_num=iter_num,
)
impute_info["df"][col] = col_impute_info["df"][col]
impute_info["missing_info"][col] = {
"initial_missing_num": col_impute_info["initial_missing_num"],
"final_missing_num": col_impute_info["final_missing_num"],
}
return impute_info | Imputes every column of ``df`` using `~greykite.common.features.timeseries_impute.impute_with_lags`. Parameters ---------- df : `pandas.DataFrame` Input dataframe which must include `value_col` as a column. orders : list of `int` The lag orders to be used for aggregation. agg_func : callable, default `np.mean` `pandas.Series` -> `float` An aggregation function to aggregate the chosen lags. iter_num : `int`, default `1` Maximum number of iterations to impute the series. Each iteration represent an imputation of the series using the provided lag orders (``orders``) and return an imputed dataframe. It might be the case that with one iterations some values are not imputed but with more iterations one can achieve more imputed values. cols : `list` [`str`] or None, default None Which columns to impute. If None, imputes all columns. Returns ------- impute_info : `dict` A dictionary with following items: "df" : `pandas.DataFrame` A dataframe with the imputed values. "missing_info" : `dict` Dictionary with information about the missing info. Key = name of a column in ``df`` Value = dictionary containing: "initial_missing_num" : `int` Initial number of missing values. "final_missing_num" : `int` Final number of missing values after imputation. |
167,449 | import math
from datetime import datetime
from datetime import timedelta
import numpy as np
import pandas as pd
import pytz
from holidays_ext import get_holidays as get_hdays
from pandas.tseries.frequencies import to_offset
from scipy.special import expit
from greykite.common import constants as cst
from greykite.common.python_utils import split_offset_str
The provided code snippet includes necessary dependencies for implementing the `pytz_is_dst_fcn` function. Write a Python function `def pytz_is_dst_fcn(time_zone)` to solve the following problem:
For a given timezone, it constructs a function which determines if a timestamp (`dt`) is inside the daylight saving period or not for a list of timestamps. This function, should work for regions in US / Canada and Europe. The returned function assumes that the timestamps are in the given ``time_zone``. Note that since daylight saving is the same for all of mainland US / Canada, one can pass any US time zone e.g. ``"US/Pacific"`` to construct a function which works for all of mainland US. Similarly for most of Europe, it is suffcient to pass any Europe time zone e.g. ``"Europe/London"``. Note: Since this function is slow, a faster version is available: `~greykite.common.features.timeseries_features.is_dst_fcn`. However, we expect the current function would be more accurate assuming the package `pytz` keeps up to date with potential changes in DST. Parameters ---------- time_zone : `str` A string denoting the timestamp e.g. "US/Pacific", "Canada/Eastern", "Europe/London". Returns ------- is_dst : callable A function which takes a list of datetime-like objects and returns a list of colleans to determine if each timestamp is in daylight saving.
Here is the function:
def pytz_is_dst_fcn(time_zone):
"""For a given timezone, it constructs a function which determines
if a timestamp (`dt`) is inside the daylight saving period or not for
a list of timestamps.
This function, should work for regions in US / Canada and Europe.
The returned function assumes that the timestamps are in the given
``time_zone``.
Note that since daylight saving is the same for all of mainland US / Canada,
one can pass any US time zone e.g. ``"US/Pacific"`` to construct a function
which works for all of mainland US.
Similarly for most of Europe, it is suffcient to pass any Europe time zone e.g.
``"Europe/London"``.
Note: Since this function is slow, a faster version is available:
`~greykite.common.features.timeseries_features.is_dst_fcn`.
However, we expect the current function would be more accurate assuming
the package `pytz` keeps up to date with potential changes in DST.
Parameters
----------
time_zone : `str`
A string denoting the timestamp e.g. "US/Pacific", "Canada/Eastern",
"Europe/London".
Returns
-------
is_dst : callable
A function which takes a list of datetime-like objects
and returns a list of colleans to determine if each timestamp is in daylight saving.
"""
timezone = pytz.timezone(time_zone)
def is_dst(dt):
"""A function which takes a list of datetime-like objects
and returns a list of booleans to determine if that timestamp
is in daylight saving.
Parameters
----------
dt : `list` of datetime-like object
Returns
-------
result : `list` [`bool`]
A list of booleans:
- If True, the input time is in daylight saving.
- If False, the input time is NOT in daylight saving.
"""
diff = []
for dt0 in dt:
timezone_date = timezone.localize(dt0, is_dst=False)
diff.append(timezone_date.tzinfo._dst.seconds)
return list(pd.Series(diff) != 0)
return is_dst | For a given timezone, it constructs a function which determines if a timestamp (`dt`) is inside the daylight saving period or not for a list of timestamps. This function, should work for regions in US / Canada and Europe. The returned function assumes that the timestamps are in the given ``time_zone``. Note that since daylight saving is the same for all of mainland US / Canada, one can pass any US time zone e.g. ``"US/Pacific"`` to construct a function which works for all of mainland US. Similarly for most of Europe, it is suffcient to pass any Europe time zone e.g. ``"Europe/London"``. Note: Since this function is slow, a faster version is available: `~greykite.common.features.timeseries_features.is_dst_fcn`. However, we expect the current function would be more accurate assuming the package `pytz` keeps up to date with potential changes in DST. Parameters ---------- time_zone : `str` A string denoting the timestamp e.g. "US/Pacific", "Canada/Eastern", "Europe/London". Returns ------- is_dst : callable A function which takes a list of datetime-like objects and returns a list of colleans to determine if each timestamp is in daylight saving. |
167,450 | import math
from datetime import datetime
from datetime import timedelta
import numpy as np
import pandas as pd
import pytz
from holidays_ext import get_holidays as get_hdays
from pandas.tseries.frequencies import to_offset
from scipy.special import expit
from greykite.common import constants as cst
from greykite.common.python_utils import split_offset_str
The provided code snippet includes necessary dependencies for implementing the `get_available_holiday_lookup_countries` function. Write a Python function `def get_available_holiday_lookup_countries(countries=None)` to solve the following problem:
Returns list of available countries for modeling holidays :param countries: List[str] only look for available countries in this set :return: List[str] list of available countries for modeling holidays
Here is the function:
def get_available_holiday_lookup_countries(countries=None):
"""Returns list of available countries for modeling holidays
:param countries: List[str]
only look for available countries in this set
:return: List[str]
list of available countries for modeling holidays
"""
return get_hdays.get_available_holiday_lookup_countries(
countries=countries
) | Returns list of available countries for modeling holidays :param countries: List[str] only look for available countries in this set :return: List[str] list of available countries for modeling holidays |
167,451 | import math
from datetime import datetime
from datetime import timedelta
import numpy as np
import pandas as pd
import pytz
from holidays_ext import get_holidays as get_hdays
from pandas.tseries.frequencies import to_offset
from scipy.special import expit
from greykite.common import constants as cst
from greykite.common.python_utils import split_offset_str
The provided code snippet includes necessary dependencies for implementing the `get_available_holidays_in_countries` function. Write a Python function `def get_available_holidays_in_countries( countries, year_start, year_end)` to solve the following problem:
Returns a dictionary mapping each country to its holidays between the years specified. :param countries: List[str] countries for which we need holidays :param year_start: int first year of interest :param year_end: int last year of interest :return: Dict[str, List[str]] key: country name value: list of holidays in that country between [year_start, year_end]
Here is the function:
def get_available_holidays_in_countries(
countries,
year_start,
year_end):
"""Returns a dictionary mapping each country to its holidays
between the years specified.
:param countries: List[str]
countries for which we need holidays
:param year_start: int
first year of interest
:param year_end: int
last year of interest
:return: Dict[str, List[str]]
key: country name
value: list of holidays in that country between [year_start, year_end]
"""
return get_hdays.get_available_holidays_in_countries(
countries=countries,
year_start=year_start,
year_end=year_end
) | Returns a dictionary mapping each country to its holidays between the years specified. :param countries: List[str] countries for which we need holidays :param year_start: int first year of interest :param year_end: int last year of interest :return: Dict[str, List[str]] key: country name value: list of holidays in that country between [year_start, year_end] |
167,452 | import math
from datetime import datetime
from datetime import timedelta
import numpy as np
import pandas as pd
import pytz
from holidays_ext import get_holidays as get_hdays
from pandas.tseries.frequencies import to_offset
from scipy.special import expit
from greykite.common import constants as cst
from greykite.common.python_utils import split_offset_str
The provided code snippet includes necessary dependencies for implementing the `get_available_holidays_across_countries` function. Write a Python function `def get_available_holidays_across_countries( countries, year_start, year_end)` to solve the following problem:
Returns a list of holidays that occur any of the countries between the years specified. :param countries: List[str] countries for which we need holidays :param year_start: int first year of interest :param year_end: int last year of interest :return: List[str] names of holidays in any of the countries between [year_start, year_end]
Here is the function:
def get_available_holidays_across_countries(
countries,
year_start,
year_end):
"""Returns a list of holidays that occur any of the countries
between the years specified.
:param countries: List[str]
countries for which we need holidays
:param year_start: int
first year of interest
:param year_end: int
last year of interest
:return: List[str]
names of holidays in any of the countries between [year_start, year_end]
"""
return get_hdays.get_available_holidays_across_countries(
countries=countries,
year_start=year_start,
year_end=year_end
) | Returns a list of holidays that occur any of the countries between the years specified. :param countries: List[str] countries for which we need holidays :param year_start: int first year of interest :param year_end: int last year of interest :return: List[str] names of holidays in any of the countries between [year_start, year_end] |
167,453 | import math
from datetime import datetime
from datetime import timedelta
import numpy as np
import pandas as pd
import pytz
from holidays_ext import get_holidays as get_hdays
from pandas.tseries.frequencies import to_offset
from scipy.special import expit
from greykite.common import constants as cst
from greykite.common.python_utils import split_offset_str
def split_offset_str(
offset_str: str) -> List[str]:
"""Splits a pandas offset string into number part and frequency string part.
Parameters
----------
offset_str : `str`
An offset string parsable by `pandas`.
For example, "7D", "-5H", etc.
The number part should only include numbers and "+" or "-".
The frequency part should only include letters.
Returns
-------
split_strs : `list` [`str`]
A list of split strings.
For example, ["7", "D"].
"""
freq = offset_str.lstrip("+-012334556789")
num = offset_str[:-len(freq)]
return [num, freq]
The provided code snippet includes necessary dependencies for implementing the `add_daily_events` function. Write a Python function `def add_daily_events( df, event_df_dict, date_col=cst.EVENT_DF_DATE_COL, regular_day_label=cst.EVENT_DEFAULT, neighbor_impact=None, shifted_effect=None)` to solve the following problem:
For each key of event_df_dict, it adds a new column to a data frame (df) with a date column (date_col). Each new column will represent the events given for that key. This function also generates 3 binary event flags ``IS_EVENT_EXACT_COL``, ``IS_EVENT_ADJACENT_COL`` and ``IS_EVENT_COL`` given the information in ``event_df_dict`` with the following logic: (1) If the key contains "_minus_" or "_plus_", that means the event was generated by the ``add_event_window`` function, and it is a neighboring day of some exact event day. In this case, ``IS_EVENT_ADJACENT_COL`` will be 1 for all days in this key. (2) Otherwise the key indicates that it is on the exact event day being modeled. In this case, ``IS_EVENT_EXACT_COL`` will be 1 for all days in this key. (3) If a date appears in both types of keys, both above columns will be 1. (4) ``IS_EVENT_COL`` is 1 for all dates in the provided ``event_df_dict``. Parameters ---------- df : `pandas.DataFrame` The data frame which has a date column. event_df_dict : `dict` [`str`, `pandas.DataFrame`] A dictionary of data frames, each representing events data for the corresponding key. Values are DataFrames with two columns: - The first column contains the date. Must be at the same frequency as ``df[date_col]`` for proper join. Must be in a format recognized by `pandas.to_datetime`. - The second column contains the event label for each date date_col : `str` Column name in ``df`` that contains the dates for joining against the events in ``event_df_dict``. regular_day_label : `str` The label used for regular days which are not "events". neighbor_impact : `int`, `list` [`int`], callable or None, default None The impact of neighboring timestamps of the events in ``event_df_dict``. This is for daily events so the units below are all in days. For example, if the data is weekly ("W-SUN") and an event is daily, it may not exactly fall on the weekly date. But you can specify for New Year's day on 1-1, it affects all dates in the week, e.g. 12-31, 1-1, ..., 1-6, then it will be mapped to the weekly date. In this case you may want to map a daily event's date to a few dates, and can specify ``neighbor_impact=lambda x: [x-timedelta(days=x.isocalendar()[2]-1) + timedelta(days=i) for i in range(7)]``. Another example is that the data is rolling 7 day daily data, thus a holiday may affect the t, t+1, ..., t+6 dates. You can specify ``neighbor_impact=7``. If input is `int`, the mapping is t, t+1, ..., t+neighbor_impact-1. If input is `list`, the mapping is [t+x for x in neighbor_impact]. If input is a function, it maps each daily event's date to a list of dates. shifted_effect : `list` [`str`] or None, default None Additional neighbor events based on given events. For example, passing ["-1D", "7D"] will add extra daily events which are 1 day before and 7 days after the given events. Offset format is {d}{freq} with any integer plus a frequency string. Must be parsable by pandas ``to_offset``. The new events' names will be the current events' names with suffix "{offset}_before" or "{offset}_after". For example, if we have an event named "US_Christmas Day", a "7D" shift will have name "US_Christmas Day_7D_after". This is useful when you expect an offset of the current holidays also has impact on the time series, or you want to interact the lagged terms with autoregression. If ``neighbor_impact`` is also specified, this will be applied after adding neighboring days. Returns ------- df_daily_events : `pandas.DataFrame` An augmented data frame version of df with new label columns -- one for each key of ``event_df_dict``.
Here is the function:
def add_daily_events(
df,
event_df_dict,
date_col=cst.EVENT_DF_DATE_COL,
regular_day_label=cst.EVENT_DEFAULT,
neighbor_impact=None,
shifted_effect=None):
"""For each key of event_df_dict, it adds a new column to a data frame (df)
with a date column (date_col).
Each new column will represent the events given for that key.
This function also generates 3 binary event flags
``IS_EVENT_EXACT_COL``, ``IS_EVENT_ADJACENT_COL`` and ``IS_EVENT_COL``
given the information in ``event_df_dict`` with the following logic:
(1) If the key contains "_minus_" or "_plus_", that means the event
was generated by the ``add_event_window`` function, and it is a
neighboring day of some exact event day.
In this case, ``IS_EVENT_ADJACENT_COL`` will be 1 for all days in this key.
(2) Otherwise the key indicates that it is on the exact event day being modeled.
In this case, ``IS_EVENT_EXACT_COL`` will be 1 for all days in this key.
(3) If a date appears in both types of keys, both above columns will be 1.
(4) ``IS_EVENT_COL`` is 1 for all dates in the provided ``event_df_dict``.
Parameters
----------
df : `pandas.DataFrame`
The data frame which has a date column.
event_df_dict : `dict` [`str`, `pandas.DataFrame`]
A dictionary of data frames, each representing events data
for the corresponding key.
Values are DataFrames with two columns:
- The first column contains the date. Must be at the same
frequency as ``df[date_col]`` for proper join. Must be in a
format recognized by `pandas.to_datetime`.
- The second column contains the event label for each date
date_col : `str`
Column name in ``df`` that contains the dates for joining against
the events in ``event_df_dict``.
regular_day_label : `str`
The label used for regular days which are not "events".
neighbor_impact : `int`, `list` [`int`], callable or None, default None
The impact of neighboring timestamps of the events in ``event_df_dict``.
This is for daily events so the units below are all in days.
For example, if the data is weekly ("W-SUN") and an event is daily,
it may not exactly fall on the weekly date.
But you can specify for New Year's day on 1-1, it affects all dates
in the week, e.g. 12-31, 1-1, ..., 1-6, then it will be mapped to the weekly date.
In this case you may want to map a daily event's date to a few dates,
and can specify
``neighbor_impact=lambda x: [x-timedelta(days=x.isocalendar()[2]-1) + timedelta(days=i) for i in range(7)]``.
Another example is that the data is rolling 7 day daily data,
thus a holiday may affect the t, t+1, ..., t+6 dates.
You can specify ``neighbor_impact=7``.
If input is `int`, the mapping is t, t+1, ..., t+neighbor_impact-1.
If input is `list`, the mapping is [t+x for x in neighbor_impact].
If input is a function, it maps each daily event's date to a list of dates.
shifted_effect : `list` [`str`] or None, default None
Additional neighbor events based on given events.
For example, passing ["-1D", "7D"] will add extra daily events which are 1 day before
and 7 days after the given events.
Offset format is {d}{freq} with any integer plus a frequency string. Must be parsable by pandas ``to_offset``.
The new events' names will be the current events' names with suffix "{offset}_before" or "{offset}_after".
For example, if we have an event named "US_Christmas Day",
a "7D" shift will have name "US_Christmas Day_7D_after".
This is useful when you expect an offset of the current holidays also has impact on the
time series, or you want to interact the lagged terms with autoregression.
If ``neighbor_impact`` is also specified, this will be applied after adding neighboring days.
Returns
-------
df_daily_events : `pandas.DataFrame`
An augmented data frame version of df with new label columns --
one for each key of ``event_df_dict``.
"""
df[date_col] = pd.to_datetime(df[date_col])
get_neighbor_days_func = None
new_event_cols = [cst.IS_EVENT_EXACT_COL, cst.IS_EVENT_ADJACENT_COL, cst.IS_EVENT_COL]
event_flag_df_list = []
if neighbor_impact is not None:
if isinstance(neighbor_impact, int):
neighbor_impact = sorted([neighbor_impact, 0])
neighbor_impact[1] += 1
def get_neighbor_days_func(date):
return [date + timedelta(days=d) for d in range(*neighbor_impact)]
elif isinstance(neighbor_impact, list):
if 0 not in neighbor_impact:
neighbor_impact = sorted(neighbor_impact + [0])
def get_neighbor_days_func(date):
return [date + timedelta(days=d) for d in neighbor_impact]
else:
get_neighbor_days_func = neighbor_impact
for label, event_df in event_df_dict.items():
event_df = event_df.copy().drop_duplicates() # Makes a copy to avoid modifying input
new_col = f"{cst.EVENT_PREFIX}_{label}"
event_df.columns = [date_col, new_col]
event_df[date_col] = pd.to_datetime(event_df[date_col])
# Handles neighboring impact.
if get_neighbor_days_func is not None:
new_event_df = None
for i in range(len(event_df)):
mapped_dates = get_neighbor_days_func(event_df["date"].iloc[i])
new_event_df = pd.concat([
new_event_df, event_df.iloc[[i] * len(mapped_dates)].assign(**{date_col: mapped_dates})],
axis=0
)
event_df = new_event_df.drop_duplicates().reset_index(drop=True)
df = df.merge(event_df, on=date_col, how="left")
df[new_col] = df[new_col].fillna(regular_day_label)
# Adds neighbor events if requested.
new_event_dfs = []
if shifted_effect is not None:
for lag in shifted_effect:
num, freq = split_offset_str(lag)
num = int(num)
if num != 0:
lag_offset = to_offset(lag)
new_event_df = event_df.copy()
new_event_df[date_col] += lag_offset
suffix = cst.EVENT_SHIFTED_SUFFIX_BEFORE if num < 0 else cst.EVENT_SHIFTED_SUFFIX_AFTER
new_col = f"{cst.EVENT_PREFIX}_{label}_{abs(num)}{freq}{suffix}"
new_event_df.columns = [date_col, new_col]
new_event_df[new_col] += f"_{abs(num)}{freq}{suffix}"
df = df.merge(new_event_df, on=date_col, how="left")
df[new_col] = df[new_col].fillna(regular_day_label)
new_event_dfs.append(new_event_df)
# Generates event indicators.
# `augmented_event_df` contains `date_col` and three event indicator columns to be added to `df`.
for event_df_temp in [event_df] + new_event_dfs:
augmented_event_df = event_df_temp[[date_col]].drop_duplicates()
is_event_adjacent = "_minus_" in label or "_plus_" in label
augmented_event_df[cst.IS_EVENT_EXACT_COL] = 0 if is_event_adjacent else 1
augmented_event_df[cst.IS_EVENT_ADJACENT_COL] = 1 if is_event_adjacent else 0
augmented_event_df[cst.IS_EVENT_COL] = 1 # In either case, `IS_EVENT_COL` is 1.
event_flag_df_list.append(augmented_event_df)
event_flag_df = pd.concat(event_flag_df_list)
# Sets a day as 1 if it is marked by any of the keys in `event_df_dict`.
event_flag_df = event_flag_df.groupby(by=date_col)[new_event_cols].sum().reset_index(drop=False)
event_flag_df[new_event_cols] = 1 * (event_flag_df[new_event_cols] > 0)
# Joins the new event indicators to `df`.
df = df.merge(event_flag_df, on=date_col, how="left")
df[new_event_cols] = df[new_event_cols].fillna(0)
return df | For each key of event_df_dict, it adds a new column to a data frame (df) with a date column (date_col). Each new column will represent the events given for that key. This function also generates 3 binary event flags ``IS_EVENT_EXACT_COL``, ``IS_EVENT_ADJACENT_COL`` and ``IS_EVENT_COL`` given the information in ``event_df_dict`` with the following logic: (1) If the key contains "_minus_" or "_plus_", that means the event was generated by the ``add_event_window`` function, and it is a neighboring day of some exact event day. In this case, ``IS_EVENT_ADJACENT_COL`` will be 1 for all days in this key. (2) Otherwise the key indicates that it is on the exact event day being modeled. In this case, ``IS_EVENT_EXACT_COL`` will be 1 for all days in this key. (3) If a date appears in both types of keys, both above columns will be 1. (4) ``IS_EVENT_COL`` is 1 for all dates in the provided ``event_df_dict``. Parameters ---------- df : `pandas.DataFrame` The data frame which has a date column. event_df_dict : `dict` [`str`, `pandas.DataFrame`] A dictionary of data frames, each representing events data for the corresponding key. Values are DataFrames with two columns: - The first column contains the date. Must be at the same frequency as ``df[date_col]`` for proper join. Must be in a format recognized by `pandas.to_datetime`. - The second column contains the event label for each date date_col : `str` Column name in ``df`` that contains the dates for joining against the events in ``event_df_dict``. regular_day_label : `str` The label used for regular days which are not "events". neighbor_impact : `int`, `list` [`int`], callable or None, default None The impact of neighboring timestamps of the events in ``event_df_dict``. This is for daily events so the units below are all in days. For example, if the data is weekly ("W-SUN") and an event is daily, it may not exactly fall on the weekly date. But you can specify for New Year's day on 1-1, it affects all dates in the week, e.g. 12-31, 1-1, ..., 1-6, then it will be mapped to the weekly date. In this case you may want to map a daily event's date to a few dates, and can specify ``neighbor_impact=lambda x: [x-timedelta(days=x.isocalendar()[2]-1) + timedelta(days=i) for i in range(7)]``. Another example is that the data is rolling 7 day daily data, thus a holiday may affect the t, t+1, ..., t+6 dates. You can specify ``neighbor_impact=7``. If input is `int`, the mapping is t, t+1, ..., t+neighbor_impact-1. If input is `list`, the mapping is [t+x for x in neighbor_impact]. If input is a function, it maps each daily event's date to a list of dates. shifted_effect : `list` [`str`] or None, default None Additional neighbor events based on given events. For example, passing ["-1D", "7D"] will add extra daily events which are 1 day before and 7 days after the given events. Offset format is {d}{freq} with any integer plus a frequency string. Must be parsable by pandas ``to_offset``. The new events' names will be the current events' names with suffix "{offset}_before" or "{offset}_after". For example, if we have an event named "US_Christmas Day", a "7D" shift will have name "US_Christmas Day_7D_after". This is useful when you expect an offset of the current holidays also has impact on the time series, or you want to interact the lagged terms with autoregression. If ``neighbor_impact`` is also specified, this will be applied after adding neighboring days. Returns ------- df_daily_events : `pandas.DataFrame` An augmented data frame version of df with new label columns -- one for each key of ``event_df_dict``. |
167,454 | import math
from datetime import datetime
from datetime import timedelta
import numpy as np
import pandas as pd
import pytz
from holidays_ext import get_holidays as get_hdays
from pandas.tseries.frequencies import to_offset
from scipy.special import expit
from greykite.common import constants as cst
from greykite.common.python_utils import split_offset_str
def signed_pow(x, y):
""" Takes the absolute value of x and raises it to power of y.
Then it multiplies the result by sign of x.
This guarantees this function is non-decreasing.
This is useful in many contexts e.g. statistical modeling.
:param x: the base number which can be any real number
:param y: the power which can be any real number
:return: returns abs(x) to power of y multiplied by sign of x
"""
return np.sign(x) * np.power(np.abs(x), y)
def signed_pow_fcn(y):
return lambda x: signed_pow(x, y) | null |
167,455 | import math
from datetime import datetime
from datetime import timedelta
import numpy as np
import pandas as pd
import pytz
from holidays_ext import get_holidays as get_hdays
from pandas.tseries.frequencies import to_offset
from scipy.special import expit
from greykite.common import constants as cst
from greykite.common.python_utils import split_offset_str
def logistic(
x,
growth_rate=1.0,
capacity=1.0,
floor=0.0,
inflection_point=0.0):
"""Evaluates the logistic function at x with the specified growth rate,
capacity, floor, and inflection point.
:param x: value to evaluate the logistic function
:type x: float
:param growth_rate: growth rate
:type growth_rate: float
:param capacity: max value (carrying capacity)
:type capacity: float
:param floor: min value (lower bound)
:type floor: float
:param inflection_point: the t value of the inflection point
:type inflection_point: float
:return: value of the logistic function at t
:rtype: float
"""
return floor + capacity * expit(growth_rate * (x - inflection_point))
The provided code snippet includes necessary dependencies for implementing the `get_logistic_func` function. Write a Python function `def get_logistic_func( growth_rate=1.0, capacity=1.0, floor=0.0, inflection_point=0.0)` to solve the following problem:
Returns a function that evaluates the logistic function at t with the specified growth rate, capacity, floor, and inflection point. f(x) = floor + capacity / (1 + exp(-growth_rate * (x - inflection_point))) :param growth_rate: growth rate :type growth_rate: float :param capacity: max value (carrying capacity) :type capacity: float :param floor: min value (lower bound) :type floor: float :param inflection_point: the t value of the inflection point :type inflection_point: float :return: the logistic function with specified parameters :rtype: callable
Here is the function:
def get_logistic_func(
growth_rate=1.0,
capacity=1.0,
floor=0.0,
inflection_point=0.0):
"""Returns a function that evaluates the logistic function at t with the
specified growth rate, capacity, floor, and inflection point.
f(x) = floor + capacity / (1 + exp(-growth_rate * (x - inflection_point)))
:param growth_rate: growth rate
:type growth_rate: float
:param capacity: max value (carrying capacity)
:type capacity: float
:param floor: min value (lower bound)
:type floor: float
:param inflection_point: the t value of the inflection point
:type inflection_point: float
:return: the logistic function with specified parameters
:rtype: callable
"""
return lambda t: logistic(t, growth_rate, capacity, floor, inflection_point) | Returns a function that evaluates the logistic function at t with the specified growth rate, capacity, floor, and inflection point. f(x) = floor + capacity / (1 + exp(-growth_rate * (x - inflection_point))) :param growth_rate: growth rate :type growth_rate: float :param capacity: max value (carrying capacity) :type capacity: float :param floor: min value (lower bound) :type floor: float :param inflection_point: the t value of the inflection point :type inflection_point: float :return: the logistic function with specified parameters :rtype: callable |
167,456 | import numpy as np
import pandas as pd
from greykite.common import constants as cst
def build_autoreg_df(
value_col,
lag_dict=None,
agg_lag_dict=None,
series_na_fill_func=lambda s: s.bfill().ffill()):
"""This function generates a function ("build_lags_func" in the returned dict)
which when called builds a lag data frame and an aggregated lag data frame using
"build_lag_df" and "build_agg_lag_df" functions.
Note: In case of training, validation and testing (e.g. cross-validation)
for forecasting, this function needs to be applied after the data split is done.
This is especially important if "series_na_fill_func" is using future values
in interpolation - that is the case for the default which is
lambda s: s.bfill().ffill()
:param value_col: str
the column name for the values of interest
:param lag_dict: Optional[dict]
A dictionary which encapsulates the needed params to be passed to the
function "build_lag_df"
Expected items are:
- "max_order": Optional[int]
the max_order for creating lags
- "orders": Optional[List[int]]
the orders for which lag is needed
:param agg_lag_dict: Optional[dict]
A dictionary encapsulating the needed params to be passed to the function
"build_agg_lag_df"
Expected items are:
- "orders_list": List[List[int]]
A list of list of integers.
Each int list is to be used as order of lags to be aggregated
See build_lag_df arguments for more details
- "interval_list": List[tuple]
A list of tuples each of length 2.
Each tuple is used to construct an aggregated lag using all orders within that range
See build_agg_lag_df arguments for more details
- "agg_func": "mean" or func (pd.Dataframe -> pd.Dataframe)
The function used for aggregation in "build_agg_lag_df"
If this key is not passed, the default of "build_agg_lag_df" will be used.
If "mean", uses `pandas.DataFrame.mean`.
:param series_na_fill_func: (pd.Series -> pd.Series)
default: lambda s: s.bfill.ffill()
This function is used to fill in the missing data
The default works by first back-filling and then forward-filling
This function should not be applied to data before CV split is done.
:return: dict
a dictionary with following items
- "build_lags_func": func
pd.Daframe -> dict(lag_df=pd.DataFrame, agg_lag_df=pd.DataFrame)
A function which takes a df (need to have value_col) as input
calculates the lag_df and agg_lag_df and returns them
- "lag_col_names": Optional[List[str]]
The list of generated column names for the returned lag_df
when "build_lags_func" is applied
- "agg_lag_col_names": Optional[List[str]]
The list of generated column names for returned agg_lag_df when
"build_lags_func" is applied
- "max_order": int
the maximum lag order needed in the calculation of "build_lags_func"
- "min_order": int
the minimum lag order needed in the calculation of "build_lags_func"
"""
# building arguments for passing to build_lag_df
# when lag_dict is not None
build_lag_df_args = None
if lag_dict is not None:
build_lag_df_args = {"value_col": value_col}
build_lag_df_args.update(lag_dict)
# building arguments for passing to build_agg_lag_df
# when agg_lag_dict is not None
build_agg_lag_df_args = None
if agg_lag_dict is not None:
build_agg_lag_df_args = {"value_col": value_col}
build_agg_lag_df_args.update(agg_lag_dict)
# we get the col_names for lag_df
lag_col_names = None
if lag_dict is not None:
lag_info = build_lag_df(
df=None,
**build_lag_df_args)
lag_col_names = lag_info["col_names"]
# we get col_names for agg_lag_df
agg_lag_col_names = None
if agg_lag_dict is not None:
agg_lag_info = build_agg_lag_df(
df=None,
**build_agg_lag_df_args)
agg_lag_col_names = agg_lag_info["col_names"]
# we find out the max_order needed
# outside the internal function: build_lags_func
min_max_order = min_max_lag_order(
lag_dict=build_lag_df_args,
agg_lag_dict=build_agg_lag_df_args)
max_order = min_max_order["max_order"]
min_order = min_max_order["min_order"]
def build_lags_func(df, past_df=None):
"""A function which uses:
df (pd.Dataframe), past_df (pd.DataFrame)
and returns lag_df and agg_lag_df for df.
This function infers some parameters
e.g. value_col, max_order, series_na_fill_func from its environment.
:param df: pd.DataFrame
The input dataframe which is expected to have value_col as a column
The returned lag_df and agg_lag_df are generated for df
(past_df will be used in calculation if provided)
:param past_df: Optional[pd.DataFrame]
When provided it will be appended to df (from left)
in order for the lags to be calculated.
past_df is considered to include the past values for the time series
leading up to df values. So if df values start at time t0:
Y(t0), ..., Y(t0 + len(df))
past_df will include these values
Y(t-len(past_df)), ..., Y(t0-1)
Note that the last value in past_df is the immediate value in time
before t0 which is the first time in df.
Also note that we do not require a timestamp column in df and past_df
as that is not needed in the logic.
If past_df is None, and series_na_fill_func is also None.
Therefore lag_df and agg_lag_df will include NULLs at the beginning
depending on how many lags are calculated
:return: dict
A dictionary including lag_df and agg_lag_df for the input df
The dictionary includes following items:
- "lag_df": Optional[pd.DataFrame]
- "agg_lag_df": Optional[pd.DataFrame]
"""
df = df[[value_col]].reset_index(drop=True)
# if past_df is None, we create one with np.nan
# also if it is shorter than max_order we expand it with np.nan
if past_df is None:
past_df = pd.DataFrame({value_col: [np.nan]*max_order})
else:
if value_col not in list(past_df.columns):
raise ValueError(
f"{value_col} must appear in past_df if past_df is not None")
past_df = past_df[[value_col]].reset_index(drop=True)
# if past_df length (number of rows) is smaller than max_order
# we expand it to avoid NULLs
if past_df.shape[0] < max_order:
past_df_list = [pd.DataFrame(
{value_col: [np.nan]*(max_order - past_df.shape[0])}), past_df]
past_df = pd.concat(past_df_list)
# df is expanded by adding past_df as the past data for df
# this will help in avoiding NULLs to appear in lag_df and agg_lag_df
# as long as past_df has data in it or expanded df is interpolated
df_expanded = pd.concat([past_df, df])
if series_na_fill_func is not None:
df_expanded[value_col] = series_na_fill_func(df_expanded[value_col])
# we get the col_names for lag_df
lag_df = None
if lag_dict is not None:
lag_info = build_lag_df(
df=df_expanded,
**build_lag_df_args)
# since the lag calculation is done on expanded dataframe (`df_expanded`)
# we need to pick only the relevant rows which match original
# dataframe (via `iloc`)
lag_df = lag_info["lag_df"].iloc[-(df.shape[0]):].reset_index(
drop=True)
# cast dtype to 'bool' if original dtype is 'bool', need to make sure there is no NaN
# there is an edge case where ``df[value_col]`` is NaN but ``past_df[value_col]`` is not
# e.g., in predict phase with autoregression, ``df_fut[value_col]`` would be NaN
if (df[value_col].dtype == 'bool' or past_df[value_col].dtype == 'bool') and lag_df.isna().sum().sum() == 0:
lag_df = lag_df.astype('bool')
# we get col_names for agg_lag_df
agg_lag_df = None
if agg_lag_dict is not None:
agg_lag_info = build_agg_lag_df(
df=df_expanded,
**build_agg_lag_df_args)
# since the lag calculation is done on expanded dataframe (`df_expanded`)
# we need to pick only the relevant rows which match original
# dataframe (via `iloc`)
agg_lag_df = agg_lag_info["agg_lag_df"].iloc[
-(df.shape[0]):].reset_index(drop=True)
return {
"lag_df": lag_df,
"agg_lag_df": agg_lag_df
}
return {
"build_lags_func": build_lags_func,
"lag_col_names": lag_col_names,
"agg_lag_col_names": agg_lag_col_names,
"min_order": min_order,
"max_order": max_order
}
The provided code snippet includes necessary dependencies for implementing the `build_autoreg_df_multi` function. Write a Python function `def build_autoreg_df_multi( value_lag_info_dict, series_na_fill_func=lambda s: s.bfill().ffill())` to solve the following problem:
A function which returns a function to build autoregression dataframe for multiple value columns. This function should not be applied to data before CV split is done. Parameters ---------- value_lag_info_dict : `dict` [`str`, `dict`] A dictionary with keys being the target value columns: `value_col` For each of these value columns, a dictionary with following keys `lag_dict`, `agg_lag_dict`, `series_na_fill_func` The `value_col` and the above three variables are then passed to the following function: build_autoreg_df( value_col, lag_dict, agg_lag_dict, series_na_fill_func) Check the `greykite.common.features.timeseries_lags.build_autoreg_df` docstring for more details for each argument. series_na_fill_func : callable, (pd.Series -> pd.Series) default: `lambda s: s.bfill.ffill()` This function is used to fill in the missing data The default works by first back-filling and then forward-filling Returns ------- A dictionary with following items "autoreg_func" : callable, (pd.DataFrame -> pd.DataFrame) A function which can be applied to a dataframe and return a dataframe which has the lagged values for all the relevant columns "autoreg_col_names" : List[str] A list of all the generated columns "autoreg_orig_col_names" : List[str] A list of all the original target value columns "max_order" : int Maximum lag order for all target value columns "min_order" : int Minimum lag order for all target value columns
Here is the function:
def build_autoreg_df_multi(
value_lag_info_dict,
series_na_fill_func=lambda s: s.bfill().ffill()):
"""A function which returns a function to build autoregression
dataframe for multiple value columns.
This function should not be applied to data before CV split is done.
Parameters
----------
value_lag_info_dict : `dict` [`str`, `dict`]
A dictionary with keys being the target value columns: `value_col`
For each of these value columns, a dictionary with following keys
`lag_dict`,
`agg_lag_dict`,
`series_na_fill_func`
The `value_col` and the above three variables are then passed to the
following function:
build_autoreg_df(
value_col,
lag_dict,
agg_lag_dict,
series_na_fill_func)
Check the
`greykite.common.features.timeseries_lags.build_autoreg_df`
docstring for more details for each argument.
series_na_fill_func : callable, (pd.Series -> pd.Series)
default: `lambda s: s.bfill.ffill()`
This function is used to fill in the missing data
The default works by first back-filling and then forward-filling
Returns
-------
A dictionary with following items
"autoreg_func" : callable, (pd.DataFrame -> pd.DataFrame)
A function which can be applied to a dataframe and return a dataframe
which has the lagged values for all the relevant columns
"autoreg_col_names" : List[str]
A list of all the generated columns
"autoreg_orig_col_names" : List[str]
A list of all the original target value columns
"max_order" : int
Maximum lag order for all target value columns
"min_order" : int
Minimum lag order for all target value columns
"""
multi_autoreg_info = {}
autoreg_col_names = []
autoreg_orig_col_names = list(value_lag_info_dict.keys())
min_order = np.inf
max_order = 0
for value_col, lag_info in value_lag_info_dict.items():
# we assign the interpolation function to be the default specified above
# in this function
# if a custom interpolation function is made available for that
# `value_col`, we replace the default
series_na_fill_func0 = lag_info.get(
"series_na_fill_func",
series_na_fill_func)
autoreg_info = build_autoreg_df(
value_col,
lag_dict=lag_info.get("lag_dict"),
agg_lag_dict=lag_info.get("agg_lag_dict"),
series_na_fill_func=series_na_fill_func0)
# store the result (`autoreg_info`) for each `value_col` in a dictionary
# the result for each `value_col` will be
# a dictionary with following keys:
# "build_lags_func"
# "lag_col_names"
# "agg_lag_col_names"
# "min_order"
# "max_order"
multi_autoreg_info[value_col] = autoreg_info
# extract column names for lagged variables and add to the full list of
# all lagged variable column names: `autoreg_col_names`
lag_col_names = autoreg_info["lag_col_names"]
agg_lag_col_names = autoreg_info["agg_lag_col_names"]
if lag_col_names is not None:
autoreg_col_names += lag_col_names
if agg_lag_col_names is not None:
autoreg_col_names += agg_lag_col_names
# extract the min_order and max_order for each col and update the overall lagged_regressor_order
min_order = np.nanmin([min_order, autoreg_info["min_order"]])
max_order = np.nanmax([max_order, autoreg_info["max_order"]])
def build_lags_func_multi(df, past_df=None):
"""A function which generates a lagged dataframe
for a given dataframe with potentially multiple value columns
to be lagged. Note `df` and `past_df` must have the same extract
columns. However time column is not needed as the function assumes
`past_df` is the data which precedes `df` (without gaps).
Parameters
----------
df : `pd.DataFrame`
The dataframe which includes the value columns for which lagged
data is needed
past_df : `pandas.DataFrame` or None, default None
The past data which is immediately before `df` with same
value columns.
Returns :
-------
autoreg_df : `pandas.DataFrame`
A DataFrame which includes the lagged values as columns
"""
autoreg_df = None
lag_dfs = []
for value_col, lag_info in multi_autoreg_info.items():
build_lags_func = lag_info["build_lags_func"]
res = build_lags_func(
df=df[[value_col]],
past_df=past_df)
lag_df = res["lag_df"]
agg_lag_df = res["agg_lag_df"]
lag_dfs.append(lag_df)
lag_dfs.append(agg_lag_df)
try:
# Concatenates the columns to the result
# dataframe in column-wise fashion
autoreg_df = pd.concat(lag_dfs, axis=1)
except ValueError: # All objects passed are None
autoreg_df = None
return autoreg_df
return {
"autoreg_func": build_lags_func_multi,
"autoreg_col_names": autoreg_col_names,
"autoreg_orig_col_names": autoreg_orig_col_names,
"min_order": min_order,
"max_order": max_order
} | A function which returns a function to build autoregression dataframe for multiple value columns. This function should not be applied to data before CV split is done. Parameters ---------- value_lag_info_dict : `dict` [`str`, `dict`] A dictionary with keys being the target value columns: `value_col` For each of these value columns, a dictionary with following keys `lag_dict`, `agg_lag_dict`, `series_na_fill_func` The `value_col` and the above three variables are then passed to the following function: build_autoreg_df( value_col, lag_dict, agg_lag_dict, series_na_fill_func) Check the `greykite.common.features.timeseries_lags.build_autoreg_df` docstring for more details for each argument. series_na_fill_func : callable, (pd.Series -> pd.Series) default: `lambda s: s.bfill.ffill()` This function is used to fill in the missing data The default works by first back-filling and then forward-filling Returns ------- A dictionary with following items "autoreg_func" : callable, (pd.DataFrame -> pd.DataFrame) A function which can be applied to a dataframe and return a dataframe which has the lagged values for all the relevant columns "autoreg_col_names" : List[str] A list of all the generated columns "autoreg_orig_col_names" : List[str] A list of all the original target value columns "max_order" : int Maximum lag order for all target value columns "min_order" : int Minimum lag order for all target value columns |
167,457 | import colorsys
import matplotlib
import numpy as np
from matplotlib import pyplot as plt
from pandas.plotting import register_matplotlib_converters
matplotlib.use("agg")
The provided code snippet includes necessary dependencies for implementing the `plt_compare_timeseries` function. Write a Python function `def plt_compare_timeseries( df_dict, time_col, value_col, legends_dict=None, colors_dict=None, start_time=None, end_time=None, transform=lambda x: x, transform_name="", plt_title="", alpha=0.6, linewidth=4)` to solve the following problem:
Compare a collection by of timeseries (given in `df_dict`) by overlaying them in the specified period between ``start_time`` and ``end_time``. :param df_dict: Dict[str, pd.DataFrame] The keys are the arbitrary labels for each dataframe provided by the user. The values are dataframes each containing a timeseries with `time_col` and `value_col` as columns. :param time_col: str The column denoting time in datetime format. :param value_col: str The value column of interest for the y axis. :param legends_dict: Optional[Dict[str, str]] Labels for plot legend. The keys are the df_dict labels (or a subset of them). The values are the labels appearing in the plot legend. If not provided or None, the `df_dict` keys will be used. :param colors_dict: Optional[Dict[str, str]] A dictionary determining the color for each series in `df_dict`. The keys are the df_dict labels (or a subset of them). The values are the colors appearing for each curve in the plot. If not provided or None, the colors will be generated. :param start_time: Optional[datetime.datetime] The start time of the series plot. :param end_time: Optional[datetime.datetime] The end time of the series plot. :param transform: Optional[func] A function to transform the y values before plotting. :param transform_name: Optional[str] The name of the transformation for using in the title. :param plt_title: str Plot title. :param alpha: Optional[float] Transparency of the curves. :param linewidth: Optional[float] The width of the curves.
Here is the function:
def plt_compare_timeseries(
df_dict,
time_col,
value_col,
legends_dict=None,
colors_dict=None,
start_time=None,
end_time=None,
transform=lambda x: x,
transform_name="",
plt_title="",
alpha=0.6,
linewidth=4):
"""Compare a collection by of timeseries (given in `df_dict`)
by overlaying them in the specified period between
``start_time`` and ``end_time``.
:param df_dict: Dict[str, pd.DataFrame]
The keys are the arbitrary labels for each dataframe provided by the user.
The values are dataframes each containing a timeseries
with `time_col` and `value_col` as columns.
:param time_col: str
The column denoting time in datetime format.
:param value_col: str
The value column of interest for the y axis.
:param legends_dict: Optional[Dict[str, str]]
Labels for plot legend.
The keys are the df_dict labels (or a subset of them).
The values are the labels appearing in the plot legend.
If not provided or None, the `df_dict` keys will be used.
:param colors_dict: Optional[Dict[str, str]]
A dictionary determining the color for each series in `df_dict`.
The keys are the df_dict labels (or a subset of them).
The values are the colors appearing for each curve in the plot.
If not provided or None, the colors will be generated.
:param start_time: Optional[datetime.datetime]
The start time of the series plot.
:param end_time: Optional[datetime.datetime]
The end time of the series plot.
:param transform: Optional[func]
A function to transform the y values before plotting.
:param transform_name: Optional[str]
The name of the transformation for using in the title.
:param plt_title: str
Plot title.
:param alpha: Optional[float]
Transparency of the curves.
:param linewidth: Optional[float]
The width of the curves.
"""
if start_time is not None:
for label, df in df_dict.items():
df_dict[label] = df[df[time_col] >= start_time]
if end_time is not None:
for label, df in df_dict.items():
df_dict[label] = df[df[time_col] <= end_time]
n = len(df_dict)
labels = list(df_dict.keys())
if colors_dict is None:
hsv_tuples = [(x * 1.0 / n, 0.5, 0.5) for x in range(n)]
rgb_tuples = [(lambda x: colorsys.hsv_to_rgb(*x))(x) for x in hsv_tuples]
colors_dict = {labels[i]: rgb_tuples[i] for i in range(n)}
if legends_dict is None:
legends_dict = {label: label for label in labels}
fig, ax = plt.subplots()
legend_patches = []
for label in labels:
df = df_dict[label]
color = colors_dict[label]
legend = legends_dict.get(label)
# Avoids the following issue:
# "ValueError: view limit minimum -36864.55 is less than 1 and is an invalid
# Matplotlib date value. This often happens if you pass a non-datetime value
# to an axis that has datetime units".
dates = df[time_col].astype("O")
# we add a legend for the given series if legend is not None
# for that series
if legend is not None:
ax.plot(
dates,
transform(df[value_col]),
alpha=alpha,
color=color,
label=legend,
linewidth=linewidth)
patch = matplotlib.patches.Patch(color=color, label=legend)
legend_patches.append(patch)
else:
ax.plot(
dates,
transform(df[value_col]),
alpha=alpha,
color=color,
linewidth=linewidth)
legends = list(legends_dict.values())
ax.legend(
labels=[legend for legend in legends if legend is not None],
handles=legend_patches)
fig.autofmt_xdate() # rotates the dates
ax.set_title(plt_title + " " + transform_name)
plt.show() | Compare a collection by of timeseries (given in `df_dict`) by overlaying them in the specified period between ``start_time`` and ``end_time``. :param df_dict: Dict[str, pd.DataFrame] The keys are the arbitrary labels for each dataframe provided by the user. The values are dataframes each containing a timeseries with `time_col` and `value_col` as columns. :param time_col: str The column denoting time in datetime format. :param value_col: str The value column of interest for the y axis. :param legends_dict: Optional[Dict[str, str]] Labels for plot legend. The keys are the df_dict labels (or a subset of them). The values are the labels appearing in the plot legend. If not provided or None, the `df_dict` keys will be used. :param colors_dict: Optional[Dict[str, str]] A dictionary determining the color for each series in `df_dict`. The keys are the df_dict labels (or a subset of them). The values are the colors appearing for each curve in the plot. If not provided or None, the colors will be generated. :param start_time: Optional[datetime.datetime] The start time of the series plot. :param end_time: Optional[datetime.datetime] The end time of the series plot. :param transform: Optional[func] A function to transform the y values before plotting. :param transform_name: Optional[str] The name of the transformation for using in the title. :param plt_title: str Plot title. :param alpha: Optional[float] Transparency of the curves. :param linewidth: Optional[float] The width of the curves. |
167,458 | import colorsys
import matplotlib
import numpy as np
from matplotlib import pyplot as plt
from pandas.plotting import register_matplotlib_converters
def plt_overlay_long_df(
df,
x_col,
y_col,
split_col,
agg_dict=None,
agg_col_names=None,
overlay_color="black",
agg_col_colors=None,
plt_title=None):
"""Overlay by splitting wrt values of a column (split_col).
If some agg metrics (specified by agg_dict) are also desired,
we overlay the aggregate metrics as well.
:param df: pd.DataFrame
data frame which includes the data
:param x_col: str
the column for the values for the x-axis
:param y_col: str
the column for the values for the y-axis
:param split_col: str
the column which is used to split the data to various
parts to be overlayed
:param agg_dict: Optional[dict]
a dictionary to specify aggregations.
we could calculate multiple metrics for example mean and median
:param agg_col_names: optional[list[str]]
names for the aggregated columns.
if not provided it will be generated during aggregations
:param overlay_color: Optional[str]
the color of the overlayed curves.
The color will be transparent so we can see the curves overlap
:param agg_col_colors: Optional[str]
the color of the aggregate curves
:param plt_title: Optional[str]
the title of the plot.
It will default to y_col if not provided
"""
g = df.groupby([split_col], as_index=False)
df_num = len(g)
alpha = 5.0 / df_num
for name, df0 in g:
plt.plot(
df0[x_col],
df0[y_col],
color=overlay_color,
alpha=alpha,
label=None)
agg_df = None
if agg_dict is not None:
g2 = df.groupby([x_col], as_index=False)
agg_df = g2.agg(agg_dict)
agg_df.columns = [" ".join(col).strip() for col in agg_df.columns.values]
if agg_col_names is not None:
agg_df.columns = [x_col] + agg_col_names
if agg_col_colors is None:
n = len(agg_col_names)
hsv_tuples = [(x * 1.0 / n, 0.5, 0.5) for x in range(n)]
rgb_tuples = [colorsys.hsv_to_rgb(*x) for x in hsv_tuples]
agg_col_colors = rgb_tuples
legend_patches = []
for i in range(len(agg_col_names)):
col = agg_col_names[i]
color = agg_col_colors[i]
plt.plot(agg_df[x_col], agg_df[col], label=col, color=color)
patch = matplotlib.patches.Patch(color=color, label=col)
legend_patches.append(patch)
plt.legend(labels=agg_col_names, handles=legend_patches)
if plt_title is None:
plt_title = y_col
plt.title(plt_title)
plt.xlabel(x_col)
plt.ylabel(y_col)
return agg_df
The provided code snippet includes necessary dependencies for implementing the `plt_overlay_with_bands` function. Write a Python function `def plt_overlay_with_bands( df, x_col, y_col, split_col, perc=(25, 75), overlay_color="black", agg_col_colors=("blue", "black", "red"), plt_title=None)` to solve the following problem:
Overlay by splitting wrt a column and plot wrt time. We also add quantile (percentile) bands :param df: pd.DataFrame data frame which includes the data :param x_col: str the column for the values for the x-axis :param y_col: str the column for the values for the y-axis :param split_col: str the column which is used to split the data to various partitions t be overlayed :param perc: tuple[float, float] the percentiles for the bands. The default is 25 and 75 percentiles :param overlay_color: Optional[str] the color of the overlayed curves. The color will be transparanet so we can see the curves overlap :param agg_col_colors: Optional[str] the color of the aggregate curves :param plt_title: Optional[str] the title of the plot. It will default to y_col if not provided
Here is the function:
def plt_overlay_with_bands(
df,
x_col,
y_col,
split_col,
perc=(25, 75),
overlay_color="black",
agg_col_colors=("blue", "black", "red"),
plt_title=None):
"""Overlay by splitting wrt a column and plot wrt time.
We also add quantile (percentile) bands
:param df: pd.DataFrame
data frame which includes the data
:param x_col: str
the column for the values for the x-axis
:param y_col: str
the column for the values for the y-axis
:param split_col: str
the column which is used to split the data
to various partitions t be overlayed
:param perc: tuple[float, float]
the percentiles for the bands.
The default is 25 and 75 percentiles
:param overlay_color: Optional[str]
the color of the overlayed curves.
The color will be transparanet so we can see the curves overlap
:param agg_col_colors: Optional[str]
the color of the aggregate curves
:param plt_title: Optional[str]
the title of the plot.
It will default to y_col if not provided
"""
def quantile_fcn(q):
return lambda x: np.nanpercentile(a=x, q=q)
agg_dict = {
y_col: [np.nanmean, quantile_fcn(perc[0]), quantile_fcn(perc[1])]
}
res = plt_overlay_long_df(
df=df,
x_col=x_col,
y_col=y_col,
split_col=split_col,
agg_dict=agg_dict,
agg_col_names=["mean", ("Q" + str(perc[0])), ("Q" + str(perc[1]))],
overlay_color=overlay_color,
agg_col_colors=agg_col_colors,
plt_title=plt_title)
return res | Overlay by splitting wrt a column and plot wrt time. We also add quantile (percentile) bands :param df: pd.DataFrame data frame which includes the data :param x_col: str the column for the values for the x-axis :param y_col: str the column for the values for the y-axis :param split_col: str the column which is used to split the data to various partitions t be overlayed :param perc: tuple[float, float] the percentiles for the bands. The default is 25 and 75 percentiles :param overlay_color: Optional[str] the color of the overlayed curves. The color will be transparanet so we can see the curves overlap :param agg_col_colors: Optional[str] the color of the aggregate curves :param plt_title: Optional[str] the title of the plot. It will default to y_col if not provided |
167,459 | import colorsys
import matplotlib
import numpy as np
from matplotlib import pyplot as plt
from pandas.plotting import register_matplotlib_converters
The provided code snippet includes necessary dependencies for implementing the `plt_longterm_ts_agg` function. Write a Python function `def plt_longterm_ts_agg( df, time_col, window_col, value_col, color_col=None, agg_func=np.nanmean, plt_title="", color="blue", choose_color_func=None)` to solve the following problem:
Make a longterm avg plot by taking the average in a window and moving that across the time. That window can be a week, month, year etc :param df: pd.DataFrame The data frame with the data :param time_col: str The column with timestamps :param window_col: str This is a column which represents a coarse time granularity eg "2018-01" represents year-month In this case the avg across that month is calculated :param value_col: str The column denoting the values :param color_col: Optional[str] The column denoting the color for each point. We allow the curve color to change. When aggregating for each window the first color appearing in that window will be used by default. :param agg_func: Optional[func] the aggregation function to be used across the window :param plt_title: Optional[str] Plot title :param color: Optional[str] Color of the curve if it is not provided by `color_col` in original dataframe :param choose_color_func: func Function to determine how pointwise colors are translated to aggregated to be used for the aggregate curve. The default choosed the first color appearing in the data for the corresponding slice. :return pd.DataFrame The aggregated data frame constructed for the plot
Here is the function:
def plt_longterm_ts_agg(
df,
time_col,
window_col,
value_col,
color_col=None,
agg_func=np.nanmean,
plt_title="",
color="blue",
choose_color_func=None):
"""Make a longterm avg plot by taking the average in a window
and moving that across the time.
That window can be a week, month, year etc
:param df: pd.DataFrame
The data frame with the data
:param time_col: str
The column with timestamps
:param window_col: str
This is a column which represents a coarse time granularity
eg "2018-01" represents year-month
In this case the avg across that month is calculated
:param value_col: str
The column denoting the values
:param color_col: Optional[str]
The column denoting the color for each point.
We allow the curve color to change.
When aggregating for each window the first color
appearing in that window will be used by default.
:param agg_func: Optional[func]
the aggregation function to be used across the window
:param plt_title: Optional[str]
Plot title
:param color: Optional[str]
Color of the curve if it is not provided by `color_col`
in original dataframe
:param choose_color_func: func
Function to determine how pointwise colors are translated to aggregated
to be used for the aggregate curve.
The default choosed the first color appearing in the data for
the corresponding slice.
:return pd.DataFrame
The aggregated data frame constructed for the plot
"""
df = df.copy()
# this is for choosing the color for the aggregated curve
# after averaging
if choose_color_func is None:
def choose_color_func(color_values):
return color_values.iloc[0]
if color_col is None:
color_col = "curve_color"
df["curve_color"] = color
agg_dict = {
time_col: np.nanmean,
value_col: agg_func,
color_col: choose_color_func}
g = df.groupby([window_col], as_index=False)
df_agg = g.agg(agg_dict)
df_agg.columns = [window_col, time_col, value_col, color_col]
df_agg.sort_values(by=time_col, inplace=True)
# plotting the whole curve in grey
plt.plot(
df_agg[time_col],
df_agg[value_col],
alpha=0.5,
color="grey")
plt.xlabel(time_col)
plt.ylabel(value_col)
colors_set = set(list(df[color_col].values))
# adding scatter points in colors for each part of curve
# based on `color_col`
for c in colors_set:
df_agg_subset = df_agg.loc[
df_agg[color_col] == c].reset_index(drop=True)
plt.scatter(
df_agg_subset[time_col].values,
df_agg_subset[value_col].values,
alpha=0.5,
color=c)
plt.title(plt_title)
return df_agg | Make a longterm avg plot by taking the average in a window and moving that across the time. That window can be a week, month, year etc :param df: pd.DataFrame The data frame with the data :param time_col: str The column with timestamps :param window_col: str This is a column which represents a coarse time granularity eg "2018-01" represents year-month In this case the avg across that month is calculated :param value_col: str The column denoting the values :param color_col: Optional[str] The column denoting the color for each point. We allow the curve color to change. When aggregating for each window the first color appearing in that window will be used by default. :param agg_func: Optional[func] the aggregation function to be used across the window :param plt_title: Optional[str] Plot title :param color: Optional[str] Color of the curve if it is not provided by `color_col` in original dataframe :param choose_color_func: func Function to determine how pointwise colors are translated to aggregated to be used for the aggregate curve. The default choosed the first color appearing in the data for the corresponding slice. :return pd.DataFrame The aggregated data frame constructed for the plot |
167,460 | import pandas as pd
import plotly.graph_objects as go
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import ANOMALY_COL
from greykite.common.constants import END_TIME_COL
from greykite.common.constants import PREDICTED_ANOMALY_COL
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import START_TIME_COL
from greykite.common.constants import TIME_COL
from greykite.common.features.adjust_anomalous_data import label_anomalies_multi_metric
from greykite.common.viz.colors_utils import get_distinct_colors
from greykite.common.viz.timeseries_plotting import plot_forecast_vs_actual
The provided code snippet includes necessary dependencies for implementing the `plt_annotate_series` function. Write a Python function `def plt_annotate_series( df, x_col, value_col, label_col, annotate_labels=None, keep_cols=None, fill_cols=None, title=None)` to solve the following problem:
A function which plots a values given in ``value_col`` of a dataframe ``df`` against x-axis values given in ``x_col`` and adds annotations based on labels in ``label_col``. Parameters ---------- df : `pandas.DataFrame` Data frame with ``x_col``, ``value_col`` and ``label_col``. If ``keep_cols`` is not None ``df`` is supposed to have the columns in ``keep_cols`` as well. x_col: `str` Which column to plot on the x-axis. value_col : `str` The column with the values for the series. label_col : `str` The column which includes the labels for which we want to annotate the series given in ``value_col``. annotate_labels : `List` [`str`] or None, default None If not None, the annotations will only be added for the labels given in this list. keep_cols: `List` [`str`] or None, default None Extra columns to be plotted if not None. fill_cols : `List` [ `List` [`str`] ] Fill between each list of columns in ``fill_cols``. title : `str` or None, default None Plot title. If None, default is based on axis labels. Returns ------- result : `dict` with following items: - "fig" : `plotly.graph_objects.Figure` Interactive plotly graph of ``value_col`` and potentially columns in specified in ``keep_cols`` (if not None) in ``df`` against ``x_col`` with added annotations. - "df": `pandas.DataFrame` A dataframe which is an expansion of ``df`` and includes extra columns with new value columns for each label in ``annotate_labels`` or all labels if ``annotate_labels`` is None. The new column for each label is NA if that label is not activated and equals ``value_col`` otherwise.
Here is the function:
def plt_annotate_series(
df,
x_col,
value_col,
label_col,
annotate_labels=None,
keep_cols=None,
fill_cols=None,
title=None):
"""A function which plots a values given in ``value_col`` of a dataframe
``df`` against x-axis values given in ``x_col`` and adds annotations based
on labels in ``label_col``.
Parameters
----------
df : `pandas.DataFrame`
Data frame with ``x_col``, ``value_col`` and ``label_col``.
If ``keep_cols`` is not None ``df`` is supposed to have the columns
in ``keep_cols`` as well.
x_col: `str`
Which column to plot on the x-axis.
value_col : `str`
The column with the values for the series.
label_col : `str`
The column which includes the labels for which we want to annotate the
series given in ``value_col``.
annotate_labels : `List` [`str`] or None, default None
If not None, the annotations will only be added for the labels given in
this list.
keep_cols: `List` [`str`] or None, default None
Extra columns to be plotted if not None.
fill_cols : `List` [ `List` [`str`] ]
Fill between each list of columns in ``fill_cols``.
title : `str` or None, default None
Plot title. If None, default is based on axis labels.
Returns
-------
result : `dict` with following items:
- "fig" : `plotly.graph_objects.Figure`
Interactive plotly graph of ``value_col`` and potentially columns
in specified in ``keep_cols`` (if not None)
in ``df`` against ``x_col`` with added annotations.
- "df": `pandas.DataFrame`
A dataframe which is an expansion of ``df`` and includes extra columns
with new value columns for each label in ``annotate_labels`` or all labels
if ``annotate_labels`` is None. The new column for each label is NA if
that label is not activated and equals ``value_col`` otherwise.
"""
df = df.copy()
if keep_cols is None:
keep_cols = []
y_col_style_dict = {}
# The columns to be filled. They will be handled separately from ``keep_cols``.
all_fill_cols = []
if fill_cols is not None and len(fill_cols) > 0:
if not isinstance(fill_cols[0], list):
raise ValueError(f"fill_cols must be a list of lists of strings.")
all_fill_cols = [c for c_list in fill_cols for c in c_list]
# Removes a col in keep_cols if it is already in fill_cols.
keep_cols = [col for col in keep_cols if col not in all_fill_cols]
df = df[[x_col, value_col, label_col] + keep_cols + all_fill_cols]
if annotate_labels is None:
annotate_labels = df[label_col].unique()
for col in [value_col] + keep_cols:
y_col_style_dict[col] = {
"mode": "lines"
}
for label in annotate_labels:
new_col = f"{value_col}_label_{label}"
df[new_col] = df[value_col]
df.loc[~(df[label_col] == label), new_col] = None
y_col_style_dict[new_col] = {
"mode": "markers"}
y_col_style_dict[value_col] = {
"mode": "lines",
"line": {
"color": "rgba(0, 0, 255, 0.3)",
"dash": "solid"}}
del df[label_col]
# Instead of calling plot_multivariate, we make the figure manually to avoid the column order to be
# flipped due to the fact that dictionary is unordered. This may affect the fill between certain columns.
data = []
# Plots fill_cols first to make them in the bottom layer.
if fill_cols is not None:
first_fill_color = "rgba(142, 215, 246, 0.3)" # blue
for g, col_list in enumerate(fill_cols):
for i, col in enumerate(col_list):
line = go.Scatter(
x=df[x_col],
y=df[col],
name=col,
legendgroup=f"{g}",
mode="lines",
line=dict(color=(first_fill_color if g == 0 else None)),
fill=("tonexty" if i != 0 else None),
fillcolor=(first_fill_color if g == 0 else None)
)
data.append(line)
for column, style_dict in y_col_style_dict.items():
style_dict = dict(
name=column,
**style_dict
)
line = go.Scatter(
x=df[x_col],
y=df[column],
**style_dict)
data.append(line)
layout = go.Layout(
xaxis=dict(title=x_col),
yaxis=dict(title=value_col),
title=title,
title_x=0.5,
showlegend=True,
)
fig = go.Figure(data=data, layout=layout)
return {
"fig": fig,
"annotated_df": df} | A function which plots a values given in ``value_col`` of a dataframe ``df`` against x-axis values given in ``x_col`` and adds annotations based on labels in ``label_col``. Parameters ---------- df : `pandas.DataFrame` Data frame with ``x_col``, ``value_col`` and ``label_col``. If ``keep_cols`` is not None ``df`` is supposed to have the columns in ``keep_cols`` as well. x_col: `str` Which column to plot on the x-axis. value_col : `str` The column with the values for the series. label_col : `str` The column which includes the labels for which we want to annotate the series given in ``value_col``. annotate_labels : `List` [`str`] or None, default None If not None, the annotations will only be added for the labels given in this list. keep_cols: `List` [`str`] or None, default None Extra columns to be plotted if not None. fill_cols : `List` [ `List` [`str`] ] Fill between each list of columns in ``fill_cols``. title : `str` or None, default None Plot title. If None, default is based on axis labels. Returns ------- result : `dict` with following items: - "fig" : `plotly.graph_objects.Figure` Interactive plotly graph of ``value_col`` and potentially columns in specified in ``keep_cols`` (if not None) in ``df`` against ``x_col`` with added annotations. - "df": `pandas.DataFrame` A dataframe which is an expansion of ``df`` and includes extra columns with new value columns for each label in ``annotate_labels`` or all labels if ``annotate_labels`` is None. The new column for each label is NA if that label is not activated and equals ``value_col`` otherwise. |
167,461 | import pandas as pd
import plotly.graph_objects as go
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import ANOMALY_COL
from greykite.common.constants import END_TIME_COL
from greykite.common.constants import PREDICTED_ANOMALY_COL
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import START_TIME_COL
from greykite.common.constants import TIME_COL
from greykite.common.features.adjust_anomalous_data import label_anomalies_multi_metric
from greykite.common.viz.colors_utils import get_distinct_colors
from greykite.common.viz.timeseries_plotting import plot_forecast_vs_actual
The provided code snippet includes necessary dependencies for implementing the `plt_compare_series_annotations` function. Write a Python function `def plt_compare_series_annotations( df, x_col, actual_col, actual_label_col, forecast_label_col, forecast_col=None, keep_cols=None, fill_cols=None, standardize_col=None, title=None, x_label=None, y_label=None)` to solve the following problem:
A function which plots ``actual_col`` and ``forecast_col`` and well as ``forecast_lower_col``, ``forecast_upper_col`` with respect to x axis (often time) given in ``x_col``. Then it annotates: - the ``actual_col`` with markers when ``actual_label_col`` is non-zero. - the ``forecast_col`` with markers when ``forecast_label_col`` is non-zero. This will help user to identify where the two annotations are consistent. Parameters ---------- df : `pandas.DataFrame` Data frame with all columns used in this function (see arguments passed ending with "_col"). x_col: `str` Which column to plot on the x-axis. actual_col: `str` The column in the dataframe which includes the actual values (ground truth). actual_label_col: `str` The column which has labels including 0, and will be used to annotate the values in ``actual_col`` for non-zero values. The non-zero labels are often considerd anomalies. forecast_label_col: `str` The column which has labels including 0, and will be used to annotate the values in ``forecast_col`` for non-zero values. The non-zero labels are often considerd anomalies. forecast_col : `str` or None, default None The column in the dataframe which includes the forecast values keep_cols: `List` [`str`] or None, default None Extra columns to be plotted. The color for these extra columns will be opaque grey so they do not be the center of attention in the plot. Often these columns will be model upper and lower bound predictions. fill_cols: `list` [`list` [`str`] ] or None, default None Fill between each list of columns in ``fill_cols``. standardize_col : `str` or `None` In case we like to standardize all values with respect to a column, that column name would be passed here. Often ``actual_col`` will be a good candidate to be used here. title : `str` or None, default None Plot title. If None, default is based on axis labels. x_label : `str` or None, default None x axis label, if None ``x_col`` will be used. y_label : `str` or None, default None y axis label, if None, no label will be used for y-axis. Note that the legend will include the label for various curves / markers. Returns ------- fig : `plotly.graph_objects.Figure` Interactive plotly graph.
Here is the function:
def plt_compare_series_annotations(
df,
x_col,
actual_col,
actual_label_col,
forecast_label_col,
forecast_col=None,
keep_cols=None,
fill_cols=None,
standardize_col=None,
title=None,
x_label=None,
y_label=None):
"""A function which plots ``actual_col`` and ``forecast_col`` and well as
``forecast_lower_col``, ``forecast_upper_col`` with respect to x axis
(often time) given in ``x_col``. Then it annotates:
- the ``actual_col`` with markers when ``actual_label_col`` is non-zero.
- the ``forecast_col`` with markers when ``forecast_label_col`` is non-zero.
This will help user to identify where the two annotations are consistent.
Parameters
----------
df : `pandas.DataFrame`
Data frame with all columns used in this function (see arguments passed
ending with "_col").
x_col: `str`
Which column to plot on the x-axis.
actual_col: `str`
The column in the dataframe which includes the actual values (ground truth).
actual_label_col: `str`
The column which has labels including 0, and will be used to annotate
the values in ``actual_col`` for non-zero values. The non-zero labels
are often considerd anomalies.
forecast_label_col: `str`
The column which has labels including 0, and will be used to annotate
the values in ``forecast_col`` for non-zero values. The non-zero labels
are often considerd anomalies.
forecast_col : `str` or None, default None
The column in the dataframe which includes the forecast values
keep_cols: `List` [`str`] or None, default None
Extra columns to be plotted. The color for these extra columns will be
opaque grey so they do not be the center of attention in the plot.
Often these columns will be model upper and lower bound predictions.
fill_cols: `list` [`list` [`str`] ] or None, default None
Fill between each list of columns in ``fill_cols``.
standardize_col : `str` or `None`
In case we like to standardize all values with respect to a column, that
column name would be passed here. Often ``actual_col`` will be a good
candidate to be used here.
title : `str` or None, default None
Plot title. If None, default is based on axis labels.
x_label : `str` or None, default None
x axis label, if None ``x_col`` will be used.
y_label : `str` or None, default None
y axis label, if None, no label will be used for y-axis. Note that the
legend will include the label for various curves / markers.
Returns
-------
fig : `plotly.graph_objects.Figure`
Interactive plotly graph.
"""
df = df.copy()
df[f"model_anomaly"] = df[actual_col]
df.loc[df[forecast_label_col].map(float) == 0, f"model_anomaly"] = None
df[f"true_anomaly"] = df[actual_col]
df.loc[df[actual_label_col].map(float) == 0, f"true_anomaly"] = None
cols = [
actual_col,
f"model_anomaly",
f"true_anomaly"]
all_fill_cols = []
# The columns in fill_cols will be handled separately.
if fill_cols is not None and len(fill_cols) > 0:
if not isinstance(fill_cols[0], list):
raise ValueError(f"fill_cols must be a list of lists of strings.")
all_fill_cols = [c for c_list in fill_cols for c in c_list]
if keep_cols is not None:
# Removes a col in keep_cols if it is already in fill_cols.
keep_cols = [col for col in keep_cols if col not in all_fill_cols]
if keep_cols is not None:
cols += keep_cols
if forecast_col is not None:
cols += [forecast_col]
cols += all_fill_cols
if standardize_col:
x = df[standardize_col]
for col in cols:
df[col] = df[col] / x
y_col_style_dict = {
actual_col: {
"mode": "lines",
"line": {
"color": "rgba(0, 255, 0, 0.3)",
"dash": "solid"
}
},
"true_anomaly": {
"mode": "markers",
"marker": dict(
color="rgba(255, 0, 0, 0.5)",
symbol="square")
},
"model_anomaly": {
"mode": "markers",
"marker": dict(
color="rgba(0, 0, 255, 0.6)",
symbol="star")
}
}
if forecast_col is not None:
y_col_style_dict[forecast_col] = {
"mode": "lines",
"line": {
"color": "rgba(0, 0, 255, 0.4)",
"dash": "solid"
}
}
if keep_cols is not None:
for i in range(len(keep_cols)):
col = keep_cols[i]
# this is to be able to distinguish between the ``keep_cols`` using opacity
opacity = (i + 1) / (len(keep_cols) + 1)
y_col_style_dict[col] = {
"mode": "lines",
"line": {
"color": f"rgba(191, 191, 191, {opacity})",
"dash": "solid"}}
# Instead of calling plot_multivariate, we make the figure manually to avoid the column order to be
# flipped due to the fact that dictionary is unordered. This may affect the fill between certain columns.
data = []
# Plots fill_cols first to make them in the bottom layer.
if fill_cols is not None:
first_fill_color = "rgba(142, 215, 246, 0.3)" # blue
for g, col_list in enumerate(fill_cols):
for i, col in enumerate(col_list):
line = go.Scatter(
x=df[x_col],
y=df[col],
name=col,
legendgroup=f"{g}",
mode="lines",
line=dict(color=(first_fill_color if g == 0 else None)),
fill=("tonexty" if i != 0 else None),
fillcolor=(first_fill_color if g == 0 else None)
)
data.append(line)
for column, style_dict in y_col_style_dict.items():
style_dict = dict(
name=column,
**style_dict
)
line = go.Scatter(
x=df[x_col],
y=df[column],
**style_dict)
data.append(line)
layout = go.Layout(
xaxis=dict(title=(x_label if x_label is not None else x_col)),
yaxis=dict(title=(y_label if y_label is not None else None)),
title=title,
title_x=0.5,
showlegend=True,
)
fig = go.Figure(data=data, layout=layout)
return fig | A function which plots ``actual_col`` and ``forecast_col`` and well as ``forecast_lower_col``, ``forecast_upper_col`` with respect to x axis (often time) given in ``x_col``. Then it annotates: - the ``actual_col`` with markers when ``actual_label_col`` is non-zero. - the ``forecast_col`` with markers when ``forecast_label_col`` is non-zero. This will help user to identify where the two annotations are consistent. Parameters ---------- df : `pandas.DataFrame` Data frame with all columns used in this function (see arguments passed ending with "_col"). x_col: `str` Which column to plot on the x-axis. actual_col: `str` The column in the dataframe which includes the actual values (ground truth). actual_label_col: `str` The column which has labels including 0, and will be used to annotate the values in ``actual_col`` for non-zero values. The non-zero labels are often considerd anomalies. forecast_label_col: `str` The column which has labels including 0, and will be used to annotate the values in ``forecast_col`` for non-zero values. The non-zero labels are often considerd anomalies. forecast_col : `str` or None, default None The column in the dataframe which includes the forecast values keep_cols: `List` [`str`] or None, default None Extra columns to be plotted. The color for these extra columns will be opaque grey so they do not be the center of attention in the plot. Often these columns will be model upper and lower bound predictions. fill_cols: `list` [`list` [`str`] ] or None, default None Fill between each list of columns in ``fill_cols``. standardize_col : `str` or `None` In case we like to standardize all values with respect to a column, that column name would be passed here. Often ``actual_col`` will be a good candidate to be used here. title : `str` or None, default None Plot title. If None, default is based on axis labels. x_label : `str` or None, default None x axis label, if None ``x_col`` will be used. y_label : `str` or None, default None y axis label, if None, no label will be used for y-axis. Note that the legend will include the label for various curves / markers. Returns ------- fig : `plotly.graph_objects.Figure` Interactive plotly graph. |
167,462 | import pandas as pd
import plotly.graph_objects as go
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import ANOMALY_COL
from greykite.common.constants import END_TIME_COL
from greykite.common.constants import PREDICTED_ANOMALY_COL
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import START_TIME_COL
from greykite.common.constants import TIME_COL
from greykite.common.features.adjust_anomalous_data import label_anomalies_multi_metric
from greykite.common.viz.colors_utils import get_distinct_colors
from greykite.common.viz.timeseries_plotting import plot_forecast_vs_actual
def plot_lines_markers(
df,
x_col,
line_cols=None,
marker_cols=None,
band_cols=None,
band_cols_dict=None,
line_colors=None,
marker_colors=None,
band_colors=None,
title=None):
"""A lightweight, easy-to-use function to create a plotly figure of given
- lines (curves)
- markers (points)
- filled bands (e.g. error bands)
from the columns of a dataframe with a legend which matches the column names.
This can be used for example to annotate multiple curves, markers and bands
with an easy function call.
Parameters
----------
df : `pandas.DataFrame`
Data frame with ``x_col`` and value columns specified in ``line_cols`` and ``marker_cols``.
x_col : `str`
The column used for the x-axis.
line_cols : `list` [`str`] or None, default None
The list of y-axis variables to be plotted as lines / curves.
marker_cols : `list` [`str`] or None, default None
The list of y-axis variables to be plotted as markers / points.
band_cols : `list` [`str`] or None, default None
The list of y-axis variables to be plotted as bands.
Each column is expected to have tuples, each of which denote the upper
and lower bounds.
band_cols_dict : `dict` [`str`: [`str`]] or None, default None
This is another way to specify bands.
In this case:
- each key will be the name for the band
- the value contains the two bound colums of `df` for the band.
For example `{
"forecast": ["forecast_upper", "forecast_lower"],
"w": ["w1", "w2"]}`
Specifies two bands, one is based on the forecast prediction intervals
and one is based on a variables denoted by "w" which has two corresponding
columns in df: `"w1"` and `"w2"`.
line_colors : `list` [`str`] or None, default None
The list of colors to be used for each corresponding line column given in ``line_cols``.
marker_colors : `list` [`str`] or None, default None
The list of colors to be used for each corresponding marker column given in ``line_cols``.
band_colors : `list` [`str`] or None, default None
The list of colors to be used for each corresponding band column given in ``band_cols``.
Each of these colors are used as filler for each band.
title : `str` or None, default None
Plot title. If None, no title will appear.
Returns
-------
fig : `plotly.graph_objects.Figure`
Interactive plotly graph of one or more columns in ``df`` against ``x_col``.
"""
if line_colors is not None and line_cols is not None:
if len(line_colors) < len(line_cols):
raise ValueError(
"If `line_colors` is passed, its length must be at least `len(line_cols)`")
if marker_colors is not None and marker_cols is not None:
if len(marker_colors) < len(marker_cols):
raise ValueError(
"If `marker_colors` is passed, its length must be at least `len(marker_cols)`")
if band_colors is not None and band_cols is not None:
if len(band_colors) < len(band_cols):
raise ValueError(
"If `band_colors` is passed, its length must be at least `len(band_cols)`")
if band_colors is not None and band_cols_dict is not None:
if len(band_colors) < len(band_cols_dict):
raise ValueError(
"If `band_colors` is passed, its length must be at least `len(band_cols_dict)`")
if (
line_cols is None and
marker_cols is None and
band_cols is None and
band_cols_dict is None):
raise ValueError(
"At least one of `line_cols` or `marker_cols` or `band_cols`"
" or `band_cols_dict` must be passed as a list (not None).")
fig = go.Figure()
# Below we count the number of figure components to assign proper labels to legends.
count_fig_data = -1
if line_cols is not None:
for i, col in enumerate(line_cols):
if line_colors is not None:
line = go.scatter.Line(color=line_colors[i])
else:
line = go.scatter.Line()
fig.add_trace(go.Scatter(
x=df[x_col],
y=df[col],
mode="lines",
line=line,
showlegend=True))
count_fig_data += 1
fig["data"][count_fig_data]["name"] = col
if marker_cols is not None:
for i, col in enumerate(marker_cols):
if marker_colors is not None:
marker = go.scatter.Marker(color=marker_colors[i])
else:
marker = go.scatter.Marker()
fig.add_trace(go.Scatter(
x=df[x_col],
y=df[col],
mode="markers",
marker=marker,
showlegend=True))
count_fig_data += 1
fig["data"][count_fig_data]["name"] = col
if band_cols is not None:
if band_colors is None:
band_colors = get_distinct_colors(
num_colors=len(band_cols),
opacity=0.2)
for i, col in enumerate(band_cols):
fig.add_traces([
go.Scatter(
x=df[x_col],
y=df[col].map(lambda b: b[1]),
mode="lines",
line=line,
line_color="rgba(0, 0, 0, 0)",
showlegend=True),
go.Scatter(
x=df[x_col],
y=df[col].map(lambda b: b[0]),
mode="lines",
line_color="rgba(0, 0, 0, 0)",
line=line,
fill="tonexty",
fillcolor=band_colors[i],
showlegend=True)
])
# The code below adds legend for each band.
# We increment the count by two this time because each band comes with the
# inner filling and lines around it.
# In this case, we have made the lines around each band to be invisible.
# However, they do appear in the figure data and we want to only include
# one legend for each band.
count_fig_data += 2
# This adds the legend corresponding to the band filler color.
fig["data"][len(fig["data"]) - 1]["name"] = col
# The name for this added data is the empty string,
# because we do not want to add a legend for the empty lines
# around the bands.
fig["data"][len(fig["data"]) - 2]["name"] = ""
if band_cols_dict is not None:
if band_colors is None:
band_colors = get_distinct_colors(
num_colors=len(band_cols_dict),
opacity=0.2)
for i, name in enumerate(band_cols_dict):
col1 = band_cols_dict[name][0]
col2 = band_cols_dict[name][1]
fig.add_traces([
go.Scatter(
x=df[x_col],
y=df[col2],
mode="lines",
line=line,
line_color="rgba(0, 0, 0, 0)",
showlegend=True),
go.Scatter(
x=df[x_col],
y=df[col1],
mode="lines",
line_color="rgba(0, 0, 0, 0)",
line=line,
fill="tonexty",
fillcolor=band_colors[i],
showlegend=True)
])
count_fig_data += 2
fig["data"][len(fig["data"]) - 1]["name"] = name
fig["data"][len(fig["data"]) - 2]["name"] = ""
fig.update_layout(title=title)
return fig
TIME_COL = "ts"
START_TIME_COL = "start_time"
END_TIME_COL = "end_time"
def get_distinct_colors(
num_colors,
opacity=0.95):
"""Gets ``num_colors`` most distinguishable colors.
Uses color maps "tab10", "tab20" or "viridis" depending on the
number of colors needed.
See above color pallettes here:
https://matplotlib.org/stable/tutorials/colors/colormaps.html
Parameters
----------
num_colors : `int`
The number of colors needed.
opacity : `float`, default 0.95
The opacity of the color. This has to be a number between 0 and 1.
Returns
-------
colors : `list` [`str`]
A list of string colors in RGB.
"""
if opacity < 0 or opacity > 1:
raise ValueError("Opacity must be between 0 and 1.")
if num_colors <= 10:
colors = get_cmap("tab10").colors
elif num_colors <= 20:
colors = get_cmap("tab20").colors
elif num_colors <= 256:
# Removes default opacity by ":3".
colors = get_cmap(name="viridis")(np.linspace(0, 1, num_colors))[:, :3]
else:
raise ValueError("The maximum number of colors is 256.")
result = []
for color in colors:
# Converts the color components to "rgba" format
color = f"rgba{int(color[0] * 255), int(color[1] * 255), int(color[2] * 255), opacity}"
result.append(color)
return result[:num_colors]
The provided code snippet includes necessary dependencies for implementing the `plot_event_periods_multi` function. Write a Python function `def plot_event_periods_multi( periods_df, start_time_col=START_TIME_COL, end_time_col=END_TIME_COL, freq=None, grouping_col=None, min_timestamp=None, max_timestamp=None, new_cols_tag="_is_anomaly", title="anomaly periods")` to solve the following problem:
For a dataframe (``periods_df``) with rows denoting start and end of the periods, it plots the periods. If there extra segmentation is given (``grouping_col``) then the periods in each segment/slice will be plotted separately on top of each other so that their overlap can be seen easily. Parameters ---------- periods_df : `pandas.DataFrame` Data frame with ``start_time_col`` and ``end_time_col`` and optionally ``grouping_col`` if passed. start_time_col : `str`, default START_TIME_COL The column denoting the start of a period. The type can be any type admissable as `pandas.to_datetime`. end_time_col : `str`, default END_TIME_COL The column denoting the start of a period. The type can be any type admissable as `pandas.to_datetime`. freq : `str` or None, default None Frequency of the generated time grid which is used to plot the horizontal line segments (points). If None, we use hourly as default (freq = "H") which will be accurate for timestamps which are rounded up to an hour. For finer timestamps user should specify higher frequencies e.g. "min" for minutely. Also for daily, weekly, monthly data, user can use a lower frequency to make the plot size on disk smaller. grouping_col : `str` or None, default None A column which specifies the slicing. Each slice's event / anomaly period will be plotted with a specific color for that slice. Each segment will appear at a different height of the y-axis and its periods would be annotated at that height. min_timestamp : `str` or None, default None A string denoting the starting point (time) the x axis. If None, the minimum of ``start_time_col`` will be used. max_timestamp : `str` or None, default None A string denoting the end point (time) for the x axis. If None, the maximum of ``end_time_col`` will be used. title : `str` or None, default None Plot title. If None, default is based on axis labels. new_cols_tag : `str`, default "_is_anomaly" The tag used in the column names for each group. The column name has this format: f"{group}{new_cols_tag}". For example if a group is "impressions", with the default value of this argument the added column name is "impressions_is_anomaly" Returns ------- result : `dict` - "fig" : `plotly.graph_objects.Figure` Interactive plotly graph of periods given for each group. - "labels_df" : `pandas.DataFrame` A dataframe which includes timestamps as one column (TIME_COL) and one dummy string column for each group. The values of the new columns are None, except for the time periods specified in each corresponding group. - "groups" : `list` [`str`] The distinct values seen in ``df[grouping_col]`` which are used for slicing of data. - "new_cols" : `list` [`str`] The new columns generated and added to ``labels_df``. Each column corresponds to one slice of the data as specified in ``grouping_col``. - "ts" : `list` [`pandas._libs.tslibs.timestamps.Timestamp`] A time-grid generated by ``pandas.date_range`` - "min_timestamp" : `str` or None, default None A string denoting the starting point (time) the x axis. - "max_timestamp" : `str` or None, default None A string denoting the end point (time) for the x axis. - "marker_colors" : `list` [`str`] A list of strings denoting the colors used for various slices.
Here is the function:
def plot_event_periods_multi(
periods_df,
start_time_col=START_TIME_COL,
end_time_col=END_TIME_COL,
freq=None,
grouping_col=None,
min_timestamp=None,
max_timestamp=None,
new_cols_tag="_is_anomaly",
title="anomaly periods"):
"""For a dataframe (``periods_df``) with rows denoting start and end of the periods,
it plots the periods. If there extra segmentation is given (``grouping_col``) then
the periods in each segment/slice will be plotted separately on top of each other so that
their overlap can be seen easily.
Parameters
----------
periods_df : `pandas.DataFrame`
Data frame with ``start_time_col`` and ``end_time_col`` and optionally
``grouping_col`` if passed.
start_time_col : `str`, default START_TIME_COL
The column denoting the start of a period. The type can be any type
admissable as `pandas.to_datetime`.
end_time_col : `str`, default END_TIME_COL
The column denoting the start of a period. The type can be any type
admissable as `pandas.to_datetime`.
freq : `str` or None, default None
Frequency of the generated time grid which is used to plot the horizontal
line segments (points).
If None, we use hourly as default (freq = "H") which will be accurate
for timestamps which are rounded up to an hour. For finer timestamps
user should specify higher frequencies e.g. "min" for minutely. Also for
daily, weekly, monthly data, user can use a lower frequency to make the plot
size on disk smaller.
grouping_col : `str` or None, default None
A column which specifies the slicing.
Each slice's event / anomaly period will be plotted with a specific color
for that slice. Each segment will appear at a different height of the y-axis
and its periods would be annotated at that height.
min_timestamp : `str` or None, default None
A string denoting the starting point (time) the x axis.
If None, the minimum of ``start_time_col`` will be used.
max_timestamp : `str` or None, default None
A string denoting the end point (time) for the x axis.
If None, the maximum of ``end_time_col`` will be used.
title : `str` or None, default None
Plot title. If None, default is based on axis labels.
new_cols_tag : `str`, default "_is_anomaly"
The tag used in the column names for each group.
The column name has this format: f"{group}{new_cols_tag}".
For example if a group is "impressions", with the default value
of this argument the added column name is "impressions_is_anomaly"
Returns
-------
result : `dict`
- "fig" : `plotly.graph_objects.Figure`
Interactive plotly graph of periods given for each group.
- "labels_df" : `pandas.DataFrame`
A dataframe which includes timestamps as one column (TIME_COL) and one
dummy string column for each group.
The values of the new columns are None, except for the time periods specified
in each corresponding group.
- "groups" : `list` [`str`]
The distinct values seen in ``df[grouping_col]`` which are used for
slicing of data.
- "new_cols" : `list` [`str`]
The new columns generated and added to ``labels_df``.
Each column corresponds to one slice of the data as specified in
``grouping_col``.
- "ts" : `list` [`pandas._libs.tslibs.timestamps.Timestamp`]
A time-grid generated by ``pandas.date_range``
- "min_timestamp" : `str` or None, default None
A string denoting the starting point (time) the x axis.
- "max_timestamp" : `str` or None, default None
A string denoting the end point (time) for the x axis.
- "marker_colors" : `list` [`str`]
A list of strings denoting the colors used for various slices.
"""
periods_df = periods_df.copy()
if min_timestamp is None:
min_timestamp = periods_df[start_time_col].min()
if max_timestamp is None:
max_timestamp = periods_df[end_time_col].max()
periods_df = periods_df[
(periods_df[start_time_col] >= min_timestamp) &
(periods_df[end_time_col] <= max_timestamp)].reset_index(drop=True)
if freq is None:
freq = "H"
ts = pd.date_range(start=min_timestamp, end=max_timestamp, freq=freq)
labels_df = pd.DataFrame({TIME_COL: ts})
# Converting the time to standard string format in order to use plotly safely
labels_df[TIME_COL] = labels_df[TIME_COL].dt.strftime("%Y-%m-%d %H:%M:%S")
def add_periods_dummy_column_for_one_group(
labels_df,
periods_df,
new_col,
label):
"""This function will add a dummy column for the time periods of each group to the ``labels_df``.
Parameters
----------
labels_df : `pandas.DataFrame`
A data frame which at least inludes a timestamp column (TIME_COL).
periods_df : `pandas.DataFrame`
Data frame with ``start_time_col`` and ``end_time_col``.
new_col : `str`
The column name for the new dummy column to be added.
label : `str`
The label to be used in the new column when an event / anomaly is
happening. Other values will be None.
Returns
-------
labels_df : `pandas.DataFrame`
A dataframe which has one extra column as compared with the input ``labels_df``.
This extra column is a dummy string column for the input ``group``.
"""
for i, row in periods_df.iterrows():
t1 = row[start_time_col]
t2 = row[end_time_col]
if t2 < t1:
raise ValueError(
f"End Time: {t2} cannot be before Start Time: {t1}, in ``periods_df``.")
bool_index = (ts >= t1) & (ts <= t2)
labels_df.loc[bool_index, new_col] = label
return labels_df
new_cols = []
# If there is no grouping column we add a grouping column with only one value ("metric")
if grouping_col is None:
grouping_col = "metric"
periods_df["metric"] = "metric"
groups = set(periods_df[grouping_col].values)
marker_colors = get_distinct_colors(
len(groups),
opacity=0.8)
for group in groups:
new_col = f"{group}{new_cols_tag}"
new_cols.append(new_col)
periods_df_group = periods_df.loc[
periods_df[grouping_col] == group]
labels_df = add_periods_dummy_column_for_one_group(
labels_df=labels_df,
periods_df=periods_df_group,
new_col=new_col,
label=group)
# Plotting line segments for each period.
# The line segments will have the same color for the same group.
# Each group will be occupying one horizontal level in the plot.
# The groups are stacked vertically in the plot so that the user can
# scan and compare the periods across groups.
fig = plot_lines_markers(
df=labels_df,
x_col=TIME_COL,
line_cols=None,
marker_cols=new_cols,
line_colors=None,
marker_colors=marker_colors)
# Specify the y axis range
fig.update_yaxes(range=[-1, len(groups)])
# We add rectangles for each event period.
# The rectangle colors for each group will be the same and consistent with
# the line segments generated before for the same group.
# The rectangles span all the way through the y-axis so that the user can
# inspect the intersections between various groups better.
shapes = []
for i, group in enumerate(groups):
ind = (periods_df[grouping_col] == group)
periods_df_group = periods_df.loc[ind]
fillcolor = marker_colors[i]
for j, row in periods_df_group.iterrows():
x0 = row[start_time_col]
x1 = row[end_time_col]
y0 = -1
y1 = len(groups)
# Specify the corners of the rectangles
shape = dict(
type="rect",
x0=x0,
y0=y0,
x1=x1,
y1=y1,
fillcolor=fillcolor,
opacity=0.6,
line_width=2,
line_color=fillcolor,
layer="below")
shapes.append(shape)
fig.update_layout(
shapes=shapes,
title=title,
plot_bgcolor="rgba(233, 233, 233, 0.3)") # light grey (lighter than default background)
return {
"fig": fig,
"labels_df": labels_df,
"groups": groups,
"new_cols": new_cols,
"ts": ts,
"min_timestamp": min_timestamp,
"max_timestamp": max_timestamp,
"marker_colors": marker_colors,
"periods_df": periods_df
} | For a dataframe (``periods_df``) with rows denoting start and end of the periods, it plots the periods. If there extra segmentation is given (``grouping_col``) then the periods in each segment/slice will be plotted separately on top of each other so that their overlap can be seen easily. Parameters ---------- periods_df : `pandas.DataFrame` Data frame with ``start_time_col`` and ``end_time_col`` and optionally ``grouping_col`` if passed. start_time_col : `str`, default START_TIME_COL The column denoting the start of a period. The type can be any type admissable as `pandas.to_datetime`. end_time_col : `str`, default END_TIME_COL The column denoting the start of a period. The type can be any type admissable as `pandas.to_datetime`. freq : `str` or None, default None Frequency of the generated time grid which is used to plot the horizontal line segments (points). If None, we use hourly as default (freq = "H") which will be accurate for timestamps which are rounded up to an hour. For finer timestamps user should specify higher frequencies e.g. "min" for minutely. Also for daily, weekly, monthly data, user can use a lower frequency to make the plot size on disk smaller. grouping_col : `str` or None, default None A column which specifies the slicing. Each slice's event / anomaly period will be plotted with a specific color for that slice. Each segment will appear at a different height of the y-axis and its periods would be annotated at that height. min_timestamp : `str` or None, default None A string denoting the starting point (time) the x axis. If None, the minimum of ``start_time_col`` will be used. max_timestamp : `str` or None, default None A string denoting the end point (time) for the x axis. If None, the maximum of ``end_time_col`` will be used. title : `str` or None, default None Plot title. If None, default is based on axis labels. new_cols_tag : `str`, default "_is_anomaly" The tag used in the column names for each group. The column name has this format: f"{group}{new_cols_tag}". For example if a group is "impressions", with the default value of this argument the added column name is "impressions_is_anomaly" Returns ------- result : `dict` - "fig" : `plotly.graph_objects.Figure` Interactive plotly graph of periods given for each group. - "labels_df" : `pandas.DataFrame` A dataframe which includes timestamps as one column (TIME_COL) and one dummy string column for each group. The values of the new columns are None, except for the time periods specified in each corresponding group. - "groups" : `list` [`str`] The distinct values seen in ``df[grouping_col]`` which are used for slicing of data. - "new_cols" : `list` [`str`] The new columns generated and added to ``labels_df``. Each column corresponds to one slice of the data as specified in ``grouping_col``. - "ts" : `list` [`pandas._libs.tslibs.timestamps.Timestamp`] A time-grid generated by ``pandas.date_range`` - "min_timestamp" : `str` or None, default None A string denoting the starting point (time) the x axis. - "max_timestamp" : `str` or None, default None A string denoting the end point (time) for the x axis. - "marker_colors" : `list` [`str`] A list of strings denoting the colors used for various slices. |
167,463 | import pandas as pd
import plotly.graph_objects as go
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import ANOMALY_COL
from greykite.common.constants import END_TIME_COL
from greykite.common.constants import PREDICTED_ANOMALY_COL
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import START_TIME_COL
from greykite.common.constants import TIME_COL
from greykite.common.features.adjust_anomalous_data import label_anomalies_multi_metric
from greykite.common.viz.colors_utils import get_distinct_colors
from greykite.common.viz.timeseries_plotting import plot_forecast_vs_actual
def plot_lines_markers(
df,
x_col,
line_cols=None,
marker_cols=None,
band_cols=None,
band_cols_dict=None,
line_colors=None,
marker_colors=None,
band_colors=None,
title=None):
"""A lightweight, easy-to-use function to create a plotly figure of given
- lines (curves)
- markers (points)
- filled bands (e.g. error bands)
from the columns of a dataframe with a legend which matches the column names.
This can be used for example to annotate multiple curves, markers and bands
with an easy function call.
Parameters
----------
df : `pandas.DataFrame`
Data frame with ``x_col`` and value columns specified in ``line_cols`` and ``marker_cols``.
x_col : `str`
The column used for the x-axis.
line_cols : `list` [`str`] or None, default None
The list of y-axis variables to be plotted as lines / curves.
marker_cols : `list` [`str`] or None, default None
The list of y-axis variables to be plotted as markers / points.
band_cols : `list` [`str`] or None, default None
The list of y-axis variables to be plotted as bands.
Each column is expected to have tuples, each of which denote the upper
and lower bounds.
band_cols_dict : `dict` [`str`: [`str`]] or None, default None
This is another way to specify bands.
In this case:
- each key will be the name for the band
- the value contains the two bound colums of `df` for the band.
For example `{
"forecast": ["forecast_upper", "forecast_lower"],
"w": ["w1", "w2"]}`
Specifies two bands, one is based on the forecast prediction intervals
and one is based on a variables denoted by "w" which has two corresponding
columns in df: `"w1"` and `"w2"`.
line_colors : `list` [`str`] or None, default None
The list of colors to be used for each corresponding line column given in ``line_cols``.
marker_colors : `list` [`str`] or None, default None
The list of colors to be used for each corresponding marker column given in ``line_cols``.
band_colors : `list` [`str`] or None, default None
The list of colors to be used for each corresponding band column given in ``band_cols``.
Each of these colors are used as filler for each band.
title : `str` or None, default None
Plot title. If None, no title will appear.
Returns
-------
fig : `plotly.graph_objects.Figure`
Interactive plotly graph of one or more columns in ``df`` against ``x_col``.
"""
if line_colors is not None and line_cols is not None:
if len(line_colors) < len(line_cols):
raise ValueError(
"If `line_colors` is passed, its length must be at least `len(line_cols)`")
if marker_colors is not None and marker_cols is not None:
if len(marker_colors) < len(marker_cols):
raise ValueError(
"If `marker_colors` is passed, its length must be at least `len(marker_cols)`")
if band_colors is not None and band_cols is not None:
if len(band_colors) < len(band_cols):
raise ValueError(
"If `band_colors` is passed, its length must be at least `len(band_cols)`")
if band_colors is not None and band_cols_dict is not None:
if len(band_colors) < len(band_cols_dict):
raise ValueError(
"If `band_colors` is passed, its length must be at least `len(band_cols_dict)`")
if (
line_cols is None and
marker_cols is None and
band_cols is None and
band_cols_dict is None):
raise ValueError(
"At least one of `line_cols` or `marker_cols` or `band_cols`"
" or `band_cols_dict` must be passed as a list (not None).")
fig = go.Figure()
# Below we count the number of figure components to assign proper labels to legends.
count_fig_data = -1
if line_cols is not None:
for i, col in enumerate(line_cols):
if line_colors is not None:
line = go.scatter.Line(color=line_colors[i])
else:
line = go.scatter.Line()
fig.add_trace(go.Scatter(
x=df[x_col],
y=df[col],
mode="lines",
line=line,
showlegend=True))
count_fig_data += 1
fig["data"][count_fig_data]["name"] = col
if marker_cols is not None:
for i, col in enumerate(marker_cols):
if marker_colors is not None:
marker = go.scatter.Marker(color=marker_colors[i])
else:
marker = go.scatter.Marker()
fig.add_trace(go.Scatter(
x=df[x_col],
y=df[col],
mode="markers",
marker=marker,
showlegend=True))
count_fig_data += 1
fig["data"][count_fig_data]["name"] = col
if band_cols is not None:
if band_colors is None:
band_colors = get_distinct_colors(
num_colors=len(band_cols),
opacity=0.2)
for i, col in enumerate(band_cols):
fig.add_traces([
go.Scatter(
x=df[x_col],
y=df[col].map(lambda b: b[1]),
mode="lines",
line=line,
line_color="rgba(0, 0, 0, 0)",
showlegend=True),
go.Scatter(
x=df[x_col],
y=df[col].map(lambda b: b[0]),
mode="lines",
line_color="rgba(0, 0, 0, 0)",
line=line,
fill="tonexty",
fillcolor=band_colors[i],
showlegend=True)
])
# The code below adds legend for each band.
# We increment the count by two this time because each band comes with the
# inner filling and lines around it.
# In this case, we have made the lines around each band to be invisible.
# However, they do appear in the figure data and we want to only include
# one legend for each band.
count_fig_data += 2
# This adds the legend corresponding to the band filler color.
fig["data"][len(fig["data"]) - 1]["name"] = col
# The name for this added data is the empty string,
# because we do not want to add a legend for the empty lines
# around the bands.
fig["data"][len(fig["data"]) - 2]["name"] = ""
if band_cols_dict is not None:
if band_colors is None:
band_colors = get_distinct_colors(
num_colors=len(band_cols_dict),
opacity=0.2)
for i, name in enumerate(band_cols_dict):
col1 = band_cols_dict[name][0]
col2 = band_cols_dict[name][1]
fig.add_traces([
go.Scatter(
x=df[x_col],
y=df[col2],
mode="lines",
line=line,
line_color="rgba(0, 0, 0, 0)",
showlegend=True),
go.Scatter(
x=df[x_col],
y=df[col1],
mode="lines",
line_color="rgba(0, 0, 0, 0)",
line=line,
fill="tonexty",
fillcolor=band_colors[i],
showlegend=True)
])
count_fig_data += 2
fig["data"][len(fig["data"]) - 1]["name"] = name
fig["data"][len(fig["data"]) - 2]["name"] = ""
fig.update_layout(title=title)
return fig
def add_multi_vrects(
fig,
periods_df,
grouping_col=None,
start_time_col=START_TIME_COL,
end_time_col=END_TIME_COL,
y_min=None,
y_max=None,
annotation_text_col=None,
annotation_position="top left",
opacity=0.5,
grouping_color_dict=None):
"""Adds vertical rectangle shadings to existing figure.
Each vertical rectangle information is given in rows of data frame ``periods_df``.
The information includes the beginning and end of vertical ranges of each rectangle as well as optional
annotation.
Rectangle colors can be grouped using a grouping given in ``grouping_col`` if available.
Parameters
----------
fig : `plotly.graph_objects.Figure`
Existing plotly object which is going to be augmented with vertical
rectangles and annotations.
periods_df : `pandas.DataFrame`
Data frame with at least ``start_time_col`` and ``end_time_col`` to denote the
beginning and end of each vertical rectangle.
This might also include ``grouping_col`` if the rectangle colors are to be grouped
into same color within the group.
grouping_col : `str` or None, default None
The column which is used for grouping the vertical rectangle colors.
For each group, the same color will be used for all periods in that group.
If None, a dummy column will be added ("metric") with a single value (also "metric")
which results in generating only one color for all rectangles.
start_time_col : `str`, default ``START_TIME_COL``
The column denoting the start of a period. The type can be any type
consistent with the type of existing x axis in ``fig``.
end_time_col : `str`, default ``END_TIME_COL``
The column denoting the start of a period. The type can be any type
consistent with the type of existing x axis in ``fig``.
y_min : `float` or None, default None
The lower limit of the rectangles.
y_max : `float` or None, default None
The upper limit of the rectangles.
annotation_text_col : `str` or None, default None
A column which includes annotation texts for each vertical rectangle.
annotation_position : `str`, default "top left"
The position of annotation texts with respect to the vertical rectangle.
opacity : `float`, default 0.5
The opacity of the colors. Note that the passed colors could have opacity
as well, in which case this opacity will act as a relative opacity.
grouping_color_dict : `dict` [`str`, `str`] or None, default None
A dictionary to specify colors for each group given in ``grouping_col``.
If there is no ``grouping_col`` passed, there will be only one color needed
and in that case a dummy ``grouping_col`` will be created with the name "metric".
Therefore user needs to specify ``grouping_color_dict = {"metric": desired_color}``.
Returns
-------
result : `dict`
- "fig": `plotly.graph_objects.Figure`
Updated plotly object which is augmented with vertical
rectangles and annotations.
- "grouping_color_dict": `dict` [`str`, `str`]
A dictionary with keys being the groups and the values being the colors.
"""
# If there is no grouping column we add a grouping column with only one value ("metric")
if grouping_col is None:
grouping_col = "metric"
periods_df["metric"] = "metric"
if start_time_col not in periods_df.columns:
raise ValueError(
f"start_time_col: {start_time_col} is not found in ``periods_df`` columns: {periods_df.columns}")
if end_time_col not in periods_df.columns:
raise ValueError(
f"end_time_col: {end_time_col} is not found in ``periods_df`` columns: {periods_df.columns}")
if grouping_col is not None and grouping_col not in periods_df.columns:
raise ValueError(
f"grouping_col: {grouping_col} is passed but not found in ``periods_df`` columns: {periods_df.columns}")
if annotation_text_col is not None and annotation_text_col not in periods_df.columns:
raise ValueError(
f"annotation_text_col: {annotation_text_col} is passed but not found in ``periods_df`` columns: {periods_df.columns}")
groups = list(set(periods_df[grouping_col]))
groups.sort()
if grouping_color_dict is None:
colors = get_distinct_colors(
len(groups),
opacity=1.0)
grouping_color_dict = {groups[i]: colors[i] for i in range(len(groups))}
for i, group in enumerate(groups):
ind = (periods_df[grouping_col] == group)
periods_df_group = periods_df.loc[ind]
fillcolor = grouping_color_dict[group]
for j, row in periods_df_group.iterrows():
x0 = row[start_time_col]
x1 = row[end_time_col]
if annotation_text_col is not None:
annotation_text = row[annotation_text_col]
else:
annotation_text = ""
# Adds the vertical rectangles
fig.add_vrect(
x0=x0,
y0=y_min,
x1=x1,
y1=y_max,
fillcolor=fillcolor,
opacity=opacity,
line_width=2,
line_color=fillcolor,
layer="below",
annotation_text=annotation_text,
annotation_position=annotation_position)
return {
"fig": fig,
"grouping_color_dict": grouping_color_dict}
START_TIME_COL = "start_time"
END_TIME_COL = "end_time"
def label_anomalies_multi_metric(
df,
time_col,
value_cols,
anomaly_df,
anomaly_df_grouping_col=None,
start_time_col=START_TIME_COL,
end_time_col=END_TIME_COL):
"""This function operates on a given data frame (``df``) which includes time (given in ``time_col``) and
metrics.
For each metric (given in ``value_cols``), it augments the data with a
- a new column which determines if a value is an anomaly (``f"{metric}_is_anomaly"``)
- a new column which is not NA (`np.nan`) when the value is an anomaly (``f"{metric}_anomaly_value"``)
- a new column which is not NA (`np.nan`) when the value is non-anomalous / "normal" (``f"{metric}_normal_value"``)
The information regarding the anomalies is stored in the input argument ``anomaly_df`` and ``anomaly_df_grouping_col`` determines
which anomaly rows in ``anomaly_df`` correspond to each metric.
Parameters
----------
df : `pandas.DataFrame`
A data frame which at least inludes a timestamp column (``TIME_COL``) and
``value_cols`` which represent the metrics.
time_col : `str`
The column name in ``df`` representing time for the time series data.
The time column can be anything that can be parsed by `pandas.DatetimeIndex`.
value_cols : `list` [`str`]
The columns which include the metrics.
anomaly_df : `pandas.DataFrame`
Data frame with ``start_time_col`` and ``end_time_col`` and ``grouping_col``
(if provided). This contains the anomaly periods for each metric
(one of the ``value_cols``). Each row of this dataframe corresponds
to an anomaly occurring between the times given in ``row[start_time_col]``
and ``row[end_time_col]``.
The ``grouping_col`` (if not None) determines which metric that
anomaly corresponds too (otherwise we assume all anomalies apply to all metrics).
anomaly_df_grouping_col : `str` or None, default None
The column name for grouping the list of the anomalies which is to appear
in ``anomaly_df``.
This column should include some of the metric names
specified in ``value_cols``. The ``grouping_col`` (if not None) determines which metric that
anomaly corresponds too (otherwise we assume all anomalies apply to all metrics).
start_time_col : `str`, default ``START_TIME_COL``
The column name in ``anomaly_df`` representing the start timestamp of
the anomalous period, inclusive.
The format can be anything that can be parsed by pandas DatetimeIndex.
end_time_col : `str`, default ``END_TIME_COL``
The column name in ``anomaly_df`` representing the start timestamp of
the anomalous period, inclusive.
The format can be anything that can be parsed by pandas DatetimeIndex.
Returns
-------
result : `dict`
A dictionary with following items:
- "augmented_df": `pandas.DataFrame`
This is a dataframe obtained by augmenting the input ``df`` with new
columns determining if the metrics appearing in ``df`` are anomaly
or not and the new columns denoting anomaly values and normal values
(described below).
- "is_anomaly_cols": `list` [`str`]
The list of add boolean columns to determine if a value is an anomaly for
a given metric. The format of the columns is ``f"{metric}_is_anomaly"``.
- "anomaly_value_cols": `list` [`str`]
The list of columns containing only anomaly values (`np.nan` otherwise) for each corresponding
metric. The format of the columns is ``f"{metric}_anomaly_value"``.
- "normal_value_cols": `list` [`str`]
The list of columns containing only non-anomalous / normal values (`np.nan` otherwise)
for each corresponding metric. The format of the columns is ``f"{metric}_normal_value"``.
"""
df = df.copy()
anomaly_df = anomaly_df.copy()
if time_col not in df.columns:
raise ValueError(
f"time_col: {time_col} wasn't found in data frame which has columns {df.columns}")
for value_col in value_cols:
if value_col not in df.columns:
raise ValueError(
f"value_col: {value_col} wasn't found in data frame which has columns {df.columns}")
if (start_time_col not in anomaly_df.columns):
raise ValueError(
f"start_time_col: {start_time_col} wasn't found in data frame which has columns {anomaly_df.columns}")
if (end_time_col not in anomaly_df.columns):
raise ValueError(
f"end_time_col: {end_time_col} wasn't found in data frame which has columns {anomaly_df.columns}")
anomaly_df[start_time_col] = pd.to_datetime(anomaly_df[start_time_col])
anomaly_df[end_time_col] = pd.to_datetime(anomaly_df[end_time_col])
df[time_col] = pd.to_datetime(df[time_col])
is_anomaly_cols = []
anomaly_value_cols = []
normal_value_cols = []
def add_anomaly_cols_one_metric(df, value_col):
"""This function adds the new anomaly columns for each metric.
This will be applied to ``df`` once for each metric below.
Parameters
----------
df : `pandas.DataFrame`
A data frame which at least inludes a timestamp column (``TIME_COL``) and
``value_col`` which represent the metric.
value_col : `str`
The column which includes the metric of interest.
Returns
-------
df : `pandas.DataFrame`
A dataframe which has these new columns added to input ``df``:
- a new column which determines if a value is an anomaly (``f"{value_col}_is_anomaly"``)
- a new column which is not NA (`np.nan`) when the value is an anomaly (``f"{value_col}_anomaly_value"``)
- a new column which is not NA (`np.nan`) when the value is non-anomalous / "normal" (``f"{value_col}_normal_value"``)
"""
adj_df_info = adjust_anomalous_data(
df=df,
time_col=time_col,
value_col=value_col,
anomaly_df=anomaly_df,
start_time_col=start_time_col,
end_time_col=end_time_col,
filter_by_value_col=anomaly_df_grouping_col)
df0 = adj_df_info["augmented_df"]
df0[f"{value_col}_is_anomaly"] = df0[ANOMALY_COL]
df0[f"{value_col}_anomaly_value"] = np.nan
anomaly_ind = (df0[ANOMALY_COL] == 1)
normal_ind = (df0[ANOMALY_COL] == 0)
df0.loc[anomaly_ind, f"{value_col}_anomaly_value"] = df0.loc[anomaly_ind, value_col]
df0.loc[normal_ind, f"{value_col}_normal_value"] = df0.loc[normal_ind, value_col]
del df0[ANOMALY_COL]
del df0[f"adjusted_{value_col}"]
is_anomaly_cols.append(f"{value_col}_is_anomaly")
anomaly_value_cols.append(f"{value_col}_anomaly_value")
normal_value_cols.append(f"{value_col}_normal_value")
return df0
for value_col in value_cols:
df = add_anomaly_cols_one_metric(df, value_col)
return {
"augmented_df": df,
"is_anomaly_cols": is_anomaly_cols,
"anomaly_value_cols": anomaly_value_cols,
"normal_value_cols": normal_value_cols}
def get_distinct_colors(
num_colors,
opacity=0.95):
"""Gets ``num_colors`` most distinguishable colors.
Uses color maps "tab10", "tab20" or "viridis" depending on the
number of colors needed.
See above color pallettes here:
https://matplotlib.org/stable/tutorials/colors/colormaps.html
Parameters
----------
num_colors : `int`
The number of colors needed.
opacity : `float`, default 0.95
The opacity of the color. This has to be a number between 0 and 1.
Returns
-------
colors : `list` [`str`]
A list of string colors in RGB.
"""
if opacity < 0 or opacity > 1:
raise ValueError("Opacity must be between 0 and 1.")
if num_colors <= 10:
colors = get_cmap("tab10").colors
elif num_colors <= 20:
colors = get_cmap("tab20").colors
elif num_colors <= 256:
# Removes default opacity by ":3".
colors = get_cmap(name="viridis")(np.linspace(0, 1, num_colors))[:, :3]
else:
raise ValueError("The maximum number of colors is 256.")
result = []
for color in colors:
# Converts the color components to "rgba" format
color = f"rgba{int(color[0] * 255), int(color[1] * 255), int(color[2] * 255), opacity}"
result.append(color)
return result[:num_colors]
The provided code snippet includes necessary dependencies for implementing the `plot_overlay_anomalies_multi_metric` function. Write a Python function `def plot_overlay_anomalies_multi_metric( df, time_col, value_cols, anomaly_df, anomaly_df_grouping_col=None, start_time_col=START_TIME_COL, end_time_col=END_TIME_COL, annotation_text_col=None, annotation_position="top left", lines_opacity=0.6, markers_opacity=0.8, vrect_opacity=0.3)` to solve the following problem:
This function operates on a given data frame (``df``) which includes time (given in ``time_col``) and metrics (given in ``value_cols``), as well as ``anomaly_df`` which includes the anomaly periods corresponding to those metrics. It generates a plot of the metrics annotated with anomaly values as markers on the curves and vertical rectangles for the same periods. Each metric, its anomaly values and vertical rectangles use the same color with varying opacity. Parameters ---------- df : `pandas.DataFrame` A data frame which at least inludes a timestamp column (``TIME_COL``) and ``value_cols`` which represent the metrics. time_col : `str` The column name in ``df`` representing time for the time series data. The time column can be anything that can be parsed by `pandas.DatetimeIndex`. value_cols : `list` [`str`] The columns which include the metrics. anomaly_df : `pandas.DataFrame` Data frame with ``start_time_col`` and ``end_time_col`` and ``grouping_col`` (if provided). This contains the anomaly periods for each metric (one of the ``value_cols``). Each row of this dataframe corresponds to an anomaly occurring between the times given in ``row[start_time_col]`` and ``row[end_time_col]``. The ``grouping_col`` (if not None) determines which metric that anomaly corresponds too (otherwise we assume all anomalies apply to all metrics). anomaly_df_grouping_col : `str` or None, default None The column name for grouping the list of the anomalies which is to appear in ``anomaly_df``. This column should include some of the metric names specified in ``value_cols``. The ``grouping_col`` (if not None) determines which metric that anomaly corresponds too (otherwise we assume all anomalies apply to all metrics). start_time_col : `str`, default ``START_TIME_COL`` The column name in ``anomaly_df`` representing the start timestamp of the anomalous period, inclusive. The format can be anything that can be parsed by pandas DatetimeIndex. end_time_col : `str`, default ``END_TIME_COL`` The column name in ``anomaly_df`` representing the start timestamp of the anomalous period, inclusive. The format can be anything that can be parsed by pandas DatetimeIndex. annotation_text_col : `str` or None, default None A column which includes annotation texts for each vertical rectangle. annotation_position : `str`, default "top left" The position of annotation texts with respect to the vertical rectangle. lines_opacity : `float`, default 0.6 The opacity of the colors used in the lines (curves) which represent the metrics given in ``value_cols``. markers_opacity: `float`, default 0.8 The opacity of the colors used in the markersc which represent the value of the metrics given in ``value_cols`` during anomaly times as specified in ``anomaly_df``. vrect_opacity : `float`, default 0.3 The opacity of the colors for the vertical rectangles. Returns ------- result : `dict` A dictionary with following items: - "fig": `plotly.graph_objects.Figure` Plotly object which includes the metrics augmented with vertical rectangles and annotations. - "augmented_df": `pandas.DataFrame` This is a dataframe obtained by augmenting the input ``df`` with new columns determining if the metrics appearing in ``df`` are anomaly or not and the new columns denoting anomaly values and normal values (described below). - "is_anomaly_cols": `list` [`str`] The list of add boolean columns to determine if a value is an anomaly for a given metric. The format of the columns is ``f"{metric}_is_anomaly"``. - "anomaly_value_cols": `list` [`str`] The list of columns containing only anomaly values (`np.nan` otherwise) for each corresponding metric. The format of the columns is ``f"{metric}_anomaly_value"``. - "normal_value_cols": `list` [`str`] The list of columns containing only non-anomalous / normal values (`np.nan` otherwise) for each corresponding metric. The format of the columns is ``f"{metric}_normal_value"``. - "line_colors": `list` [`str`] The colors generated for the metric lines (curves). - "marker_colors": `list` [`str`] The colors generated for the anomaly values markers. - "vrect_colors": `list` [`str`] The colors generated for the vertical rectangles.
Here is the function:
def plot_overlay_anomalies_multi_metric(
df,
time_col,
value_cols,
anomaly_df,
anomaly_df_grouping_col=None,
start_time_col=START_TIME_COL,
end_time_col=END_TIME_COL,
annotation_text_col=None,
annotation_position="top left",
lines_opacity=0.6,
markers_opacity=0.8,
vrect_opacity=0.3):
"""This function operates on a given data frame (``df``) which includes time (given in ``time_col``) and
metrics (given in ``value_cols``), as well as ``anomaly_df`` which includes the anomaly periods
corresponding to those metrics. It generates a plot of the metrics annotated with anomaly
values as markers on the curves and vertical rectangles for the same periods.
Each metric, its anomaly values and vertical rectangles use the same color with
varying opacity.
Parameters
----------
df : `pandas.DataFrame`
A data frame which at least inludes a timestamp column (``TIME_COL``) and
``value_cols`` which represent the metrics.
time_col : `str`
The column name in ``df`` representing time for the time series data.
The time column can be anything that can be parsed by `pandas.DatetimeIndex`.
value_cols : `list` [`str`]
The columns which include the metrics.
anomaly_df : `pandas.DataFrame`
Data frame with ``start_time_col`` and ``end_time_col`` and ``grouping_col``
(if provided). This contains the anomaly periods for each metric
(one of the ``value_cols``). Each row of this dataframe corresponds
to an anomaly occurring between the times given in ``row[start_time_col]``
and ``row[end_time_col]``.
The ``grouping_col`` (if not None) determines which metric that
anomaly corresponds too (otherwise we assume all anomalies apply to all metrics).
anomaly_df_grouping_col : `str` or None, default None
The column name for grouping the list of the anomalies which is to appear
in ``anomaly_df``.
This column should include some of the metric names
specified in ``value_cols``. The ``grouping_col`` (if not None) determines which metric that
anomaly corresponds too (otherwise we assume all anomalies apply to all metrics).
start_time_col : `str`, default ``START_TIME_COL``
The column name in ``anomaly_df`` representing the start timestamp of
the anomalous period, inclusive.
The format can be anything that can be parsed by pandas DatetimeIndex.
end_time_col : `str`, default ``END_TIME_COL``
The column name in ``anomaly_df`` representing the start timestamp of
the anomalous period, inclusive.
The format can be anything that can be parsed by pandas DatetimeIndex.
annotation_text_col : `str` or None, default None
A column which includes annotation texts for each vertical rectangle.
annotation_position : `str`, default "top left"
The position of annotation texts with respect to the vertical rectangle.
lines_opacity : `float`, default 0.6
The opacity of the colors used in the lines (curves) which represent the
metrics given in ``value_cols``.
markers_opacity: `float`, default 0.8
The opacity of the colors used in the markersc which represent the
value of the metrics given in ``value_cols`` during anomaly times as
specified in ``anomaly_df``.
vrect_opacity : `float`, default 0.3
The opacity of the colors for the vertical rectangles.
Returns
-------
result : `dict`
A dictionary with following items:
- "fig": `plotly.graph_objects.Figure`
Plotly object which includes the metrics augmented with vertical
rectangles and annotations.
- "augmented_df": `pandas.DataFrame`
This is a dataframe obtained by augmenting the input ``df`` with new
columns determining if the metrics appearing in ``df`` are anomaly
or not and the new columns denoting anomaly values and normal values
(described below).
- "is_anomaly_cols": `list` [`str`]
The list of add boolean columns to determine if a value is an anomaly for
a given metric. The format of the columns is ``f"{metric}_is_anomaly"``.
- "anomaly_value_cols": `list` [`str`]
The list of columns containing only anomaly values (`np.nan` otherwise) for each corresponding
metric. The format of the columns is ``f"{metric}_anomaly_value"``.
- "normal_value_cols": `list` [`str`]
The list of columns containing only non-anomalous / normal values (`np.nan` otherwise)
for each corresponding metric. The format of the columns is ``f"{metric}_normal_value"``.
- "line_colors": `list` [`str`]
The colors generated for the metric lines (curves).
- "marker_colors": `list` [`str`]
The colors generated for the anomaly values markers.
- "vrect_colors": `list` [`str`]
The colors generated for the vertical rectangles.
"""
# Adds anomaly information columns to the data
# For every column specified in ``value_cols``, there will be 3 new columns are added to ``df``:
# ``f"{value_col}_is_anomaly"``
# ``f"{value_col}_anomaly_value"``
# ``f"{value_col}_normal_value"``
augmenting_data_res = label_anomalies_multi_metric(
df=df,
time_col=time_col,
value_cols=value_cols,
anomaly_df=anomaly_df,
anomaly_df_grouping_col=anomaly_df_grouping_col,
start_time_col=start_time_col,
end_time_col=end_time_col)
augmented_df = augmenting_data_res["augmented_df"]
is_anomaly_cols = augmenting_data_res["is_anomaly_cols"]
anomaly_value_cols = augmenting_data_res["anomaly_value_cols"]
normal_value_cols = augmenting_data_res["normal_value_cols"]
line_colors = get_distinct_colors(
len(value_cols),
opacity=lines_opacity)
marker_colors = get_distinct_colors(
len(value_cols),
opacity=markers_opacity)
vrect_colors = get_distinct_colors(
len(value_cols),
opacity=vrect_opacity)
fig = plot_lines_markers(
df=augmented_df,
x_col=time_col,
line_cols=value_cols,
marker_cols=anomaly_value_cols,
line_colors=line_colors,
marker_colors=marker_colors)
grouping_color_dict = {value_cols[i]: vrect_colors[i] for i in range(len(value_cols))}
y_min = df[value_cols].min(numeric_only=True).min()
y_max = df[value_cols].max(numeric_only=True).max()
augmenting_fig_res = add_multi_vrects(
fig=fig,
periods_df=anomaly_df,
grouping_col=anomaly_df_grouping_col,
start_time_col=start_time_col,
end_time_col=end_time_col,
y_min=y_min,
y_max=y_max,
annotation_text_col=annotation_text_col,
annotation_position="top left",
opacity=1.0,
grouping_color_dict=grouping_color_dict)
fig = augmenting_fig_res["fig"]
return {
"fig": fig,
"augmented_df": augmented_df,
"is_anomaly_cols": is_anomaly_cols,
"anomaly_value_cols": anomaly_value_cols,
"normal_value_cols": normal_value_cols,
"line_colors": line_colors,
"marker_colors": marker_colors,
"vrect_colors": vrect_colors
} | This function operates on a given data frame (``df``) which includes time (given in ``time_col``) and metrics (given in ``value_cols``), as well as ``anomaly_df`` which includes the anomaly periods corresponding to those metrics. It generates a plot of the metrics annotated with anomaly values as markers on the curves and vertical rectangles for the same periods. Each metric, its anomaly values and vertical rectangles use the same color with varying opacity. Parameters ---------- df : `pandas.DataFrame` A data frame which at least inludes a timestamp column (``TIME_COL``) and ``value_cols`` which represent the metrics. time_col : `str` The column name in ``df`` representing time for the time series data. The time column can be anything that can be parsed by `pandas.DatetimeIndex`. value_cols : `list` [`str`] The columns which include the metrics. anomaly_df : `pandas.DataFrame` Data frame with ``start_time_col`` and ``end_time_col`` and ``grouping_col`` (if provided). This contains the anomaly periods for each metric (one of the ``value_cols``). Each row of this dataframe corresponds to an anomaly occurring between the times given in ``row[start_time_col]`` and ``row[end_time_col]``. The ``grouping_col`` (if not None) determines which metric that anomaly corresponds too (otherwise we assume all anomalies apply to all metrics). anomaly_df_grouping_col : `str` or None, default None The column name for grouping the list of the anomalies which is to appear in ``anomaly_df``. This column should include some of the metric names specified in ``value_cols``. The ``grouping_col`` (if not None) determines which metric that anomaly corresponds too (otherwise we assume all anomalies apply to all metrics). start_time_col : `str`, default ``START_TIME_COL`` The column name in ``anomaly_df`` representing the start timestamp of the anomalous period, inclusive. The format can be anything that can be parsed by pandas DatetimeIndex. end_time_col : `str`, default ``END_TIME_COL`` The column name in ``anomaly_df`` representing the start timestamp of the anomalous period, inclusive. The format can be anything that can be parsed by pandas DatetimeIndex. annotation_text_col : `str` or None, default None A column which includes annotation texts for each vertical rectangle. annotation_position : `str`, default "top left" The position of annotation texts with respect to the vertical rectangle. lines_opacity : `float`, default 0.6 The opacity of the colors used in the lines (curves) which represent the metrics given in ``value_cols``. markers_opacity: `float`, default 0.8 The opacity of the colors used in the markersc which represent the value of the metrics given in ``value_cols`` during anomaly times as specified in ``anomaly_df``. vrect_opacity : `float`, default 0.3 The opacity of the colors for the vertical rectangles. Returns ------- result : `dict` A dictionary with following items: - "fig": `plotly.graph_objects.Figure` Plotly object which includes the metrics augmented with vertical rectangles and annotations. - "augmented_df": `pandas.DataFrame` This is a dataframe obtained by augmenting the input ``df`` with new columns determining if the metrics appearing in ``df`` are anomaly or not and the new columns denoting anomaly values and normal values (described below). - "is_anomaly_cols": `list` [`str`] The list of add boolean columns to determine if a value is an anomaly for a given metric. The format of the columns is ``f"{metric}_is_anomaly"``. - "anomaly_value_cols": `list` [`str`] The list of columns containing only anomaly values (`np.nan` otherwise) for each corresponding metric. The format of the columns is ``f"{metric}_anomaly_value"``. - "normal_value_cols": `list` [`str`] The list of columns containing only non-anomalous / normal values (`np.nan` otherwise) for each corresponding metric. The format of the columns is ``f"{metric}_normal_value"``. - "line_colors": `list` [`str`] The colors generated for the metric lines (curves). - "marker_colors": `list` [`str`] The colors generated for the anomaly values markers. - "vrect_colors": `list` [`str`] The colors generated for the vertical rectangles. |
167,464 | import pandas as pd
import plotly.graph_objects as go
from greykite.common.constants import ACTUAL_COL
from greykite.common.constants import ANOMALY_COL
from greykite.common.constants import END_TIME_COL
from greykite.common.constants import PREDICTED_ANOMALY_COL
from greykite.common.constants import PREDICTED_COL
from greykite.common.constants import START_TIME_COL
from greykite.common.constants import TIME_COL
from greykite.common.features.adjust_anomalous_data import label_anomalies_multi_metric
from greykite.common.viz.colors_utils import get_distinct_colors
from greykite.common.viz.timeseries_plotting import plot_forecast_vs_actual
def get_distinct_colors(
num_colors,
opacity=0.95):
"""Gets ``num_colors`` most distinguishable colors.
Uses color maps "tab10", "tab20" or "viridis" depending on the
number of colors needed.
See above color pallettes here:
https://matplotlib.org/stable/tutorials/colors/colormaps.html
Parameters
----------
num_colors : `int`
The number of colors needed.
opacity : `float`, default 0.95
The opacity of the color. This has to be a number between 0 and 1.
Returns
-------
colors : `list` [`str`]
A list of string colors in RGB.
"""
if opacity < 0 or opacity > 1:
raise ValueError("Opacity must be between 0 and 1.")
if num_colors <= 10:
colors = get_cmap("tab10").colors
elif num_colors <= 20:
colors = get_cmap("tab20").colors
elif num_colors <= 256:
# Removes default opacity by ":3".
colors = get_cmap(name="viridis")(np.linspace(0, 1, num_colors))[:, :3]
else:
raise ValueError("The maximum number of colors is 256.")
result = []
for color in colors:
# Converts the color components to "rgba" format
color = f"rgba{int(color[0] * 255), int(color[1] * 255), int(color[2] * 255), opacity}"
result.append(color)
return result[:num_colors]
The provided code snippet includes necessary dependencies for implementing the `plot_precision_recall_curve` function. Write a Python function `def plot_precision_recall_curve( df, grouping_col=None, recall_col="recall", precision_col="precision", axis_font_size=18, title_font_size=20, title="Precision - Recall Curve", opacity=0.95)` to solve the following problem:
Plots a Precision - Recall curve, where the x axis is recall and the y axis is precision. If ``grouping_col`` is None, it creates one Precision - Recall curve given the data in ``df``. Otherwise, this function creates an overlay plot for multiple Precision - Recall curves, one for each level in the ``grouping_col``. Parameters ---------- df : `pandas.DataFrame` The input dataframe. Must contain the columns: - ``recall_col``: `float` - ``precision_col``: `float` If ``grouping_col`` is not None, it must also contain the column ``grouping_col``. grouping_col : `str` or None, default None Column name for the grouping column. recall_col : `str`, default "recall" Column name for recall. precision_col : `str`, default "precision" Column name for precision. axis_font_size : `int`, default 18 Axis font size. title_font_size : 20 Title font size. title : `str`, default "Precision - Recall Curve" Plot title. opacity : `float`, default 0.95 The opacity of the color. This has to be a number between 0 and 1. Returns ------- fig : `plotly.graph_objs._figure.Figure` Plot figure.
Here is the function:
def plot_precision_recall_curve(
df,
grouping_col=None,
recall_col="recall",
precision_col="precision",
axis_font_size=18,
title_font_size=20,
title="Precision - Recall Curve",
opacity=0.95):
"""Plots a Precision - Recall curve, where the x axis is recall and the y axis is precision.
If ``grouping_col`` is None, it creates one Precision - Recall curve given the data in ``df``.
Otherwise, this function creates an overlay plot for multiple Precision - Recall curves, one for each level in the ``grouping_col``.
Parameters
----------
df : `pandas.DataFrame`
The input dataframe. Must contain the columns:
- ``recall_col``: `float`
- ``precision_col``: `float`
If ``grouping_col`` is not None, it must also contain the column ``grouping_col``.
grouping_col : `str` or None, default None
Column name for the grouping column.
recall_col : `str`, default "recall"
Column name for recall.
precision_col : `str`, default "precision"
Column name for precision.
axis_font_size : `int`, default 18
Axis font size.
title_font_size : 20
Title font size.
title : `str`, default "Precision - Recall Curve"
Plot title.
opacity : `float`, default 0.95
The opacity of the color. This has to be a number between 0 and 1.
Returns
-------
fig : `plotly.graph_objs._figure.Figure`
Plot figure.
"""
if any([col not in df.columns for col in [recall_col, precision_col]]):
raise ValueError(f"`df` must contain the `recall_col`: '{recall_col}' and the `precision_col`: '{precision_col}' specified!")
# Stores the curves to be plotted.
data = []
# Creates the curve(s).
if grouping_col is None: # Creates one precision - recall curve.
num_colors = 1
df.sort_values(recall_col, inplace=True)
line = go.Scatter(
x=df[recall_col].tolist(),
y=df[precision_col].tolist())
data.append(line)
else: # Creates precision - recall curve for every level in `grouping_col`.
if grouping_col not in df.columns:
raise ValueError(f"`grouping_col` = '{grouping_col}' is not found in the columns of `df`!")
num_colors = 0
for level, indices in df.groupby(grouping_col).groups.items():
df_subset = df.loc[indices].reset_index(drop=True).sort_values(recall_col)
line = go.Scatter(
name=f"{level}",
x=df_subset[recall_col].tolist(),
y=df_subset[precision_col].tolist())
data.append(line)
num_colors += 1
# Creates a list of colors for the curve(s).
color_list = get_distinct_colors(
num_colors=num_colors,
opacity=opacity)
if color_list is not None:
if len(color_list) < len(data):
raise ValueError("`color_list` must not be shorter than the number of traces in this figure!")
for i, v in enumerate(data):
v.line.color = color_list[i]
# Creates the layout.
range_epsilon = 0.05 # Space at the beginning and end of the margins.
layout = go.Layout(
xaxis=dict(
title=recall_col.title(),
titlefont=dict(size=axis_font_size),
range=[0 - range_epsilon, 1 + range_epsilon], # Sets the range of xaxis.
tickfont_size=axis_font_size,
tickformat=".0%",
hoverformat=",.1%"), # Keeps 1 decimal place.
yaxis=dict(
title=precision_col.title(),
titlefont=dict(size=axis_font_size),
range=[0 - range_epsilon, 1 + range_epsilon], # Sets the range of yaxis.
tickfont_size=axis_font_size,
tickformat=".0%",
hoverformat=",.1%"), # Keeps 1 decimal place.
title=title.title(),
title_x=0.5,
titlefont=dict(size=title_font_size),
autosize=False,
width=1000,
height=800)
# Creates the figure.
fig = go.Figure(data=data, layout=layout)
fig.update_yaxes(
constrain="domain", # Compresses the yaxis by decreasing its "domain".
automargin=True,
rangemode="tozero")
fig.update_xaxes(
constrain="domain", # Compresses the xaxis by decreasing its "domain".
automargin=True,
rangemode="tozero")
fig.add_hline(y=0.0, line_width=1, line_color="gray")
fig.add_vline(x=0.0, line_width=1, line_color="gray")
return fig | Plots a Precision - Recall curve, where the x axis is recall and the y axis is precision. If ``grouping_col`` is None, it creates one Precision - Recall curve given the data in ``df``. Otherwise, this function creates an overlay plot for multiple Precision - Recall curves, one for each level in the ``grouping_col``. Parameters ---------- df : `pandas.DataFrame` The input dataframe. Must contain the columns: - ``recall_col``: `float` - ``precision_col``: `float` If ``grouping_col`` is not None, it must also contain the column ``grouping_col``. grouping_col : `str` or None, default None Column name for the grouping column. recall_col : `str`, default "recall" Column name for recall. precision_col : `str`, default "precision" Column name for precision. axis_font_size : `int`, default 18 Axis font size. title_font_size : 20 Title font size. title : `str`, default "Precision - Recall Curve" Plot title. opacity : `float`, default 0.95 The opacity of the color. This has to be a number between 0 and 1. Returns ------- fig : `plotly.graph_objs._figure.Figure` Plot figure. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.