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:
Initia... | 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 ac... | 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_fil... | 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_... | 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 e... |
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_windo... | 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 ... |
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_windo... | 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. Parameter... |
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.featur... | 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 w... |
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.featur... | 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, forecas... |
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.featur... | 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 ``coverag... |
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.featur... | 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 infer... |
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 im... | 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... |
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 im... | 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... |
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 im... | 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 fo... |
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 s... | 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 e... |
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 s... | 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`. Ret... |
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 s... | 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 contai... |
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 whi... | 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 ... |
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 ... | 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 use... |
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... | 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 "a... |
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
... | 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 ... |
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
... | 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. Paramet... |
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 Ridg... | 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 ------- co... |
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 impor... | 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 impor... | 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 impor... | 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.s... |
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 impor... | 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`,... |
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... | 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 interc... |
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... | 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_s... |
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... | 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_s... |
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... | 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.g... |
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.ens... | 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... |
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.ens... | 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 eac... |
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 include... | 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 ... |
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... | 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 Wh... |
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... | 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. Par... |
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... | 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... |
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... | 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 ----------... |
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... | 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 w... |
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... | 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_seasonal... |
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... | 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 point... |
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... | 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 compone... |
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... | 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... | 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 g... |
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
fr... | 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.... |
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 ... | 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 pena... |
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
fro... | 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 ... |
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
fro... | 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 co... |
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
fro... | 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... |
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
fro... | 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.co... |
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
fro... | 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``[``constrai... |
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
fro... | 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 ... |
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
fro... | 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 ... |
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
fro... | 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 id... |
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_... | 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.d... |
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
IN... | 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
T... | 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 t... |
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
T... | 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 gen... |
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
T... | 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, ... |
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
T... | 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
de... | 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 fo... |
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
d... | 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 predict... |
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
d... | 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 ... |
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 p... | 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, ty... |
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):... | 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 data... |
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_l... | 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. Origin... |
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 skl... | 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 skl... | 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 skl... | 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 skl... | 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 skl... | 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 skl... | 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 skl... | 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 skl... | 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 :re... |
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 skl... | 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... |
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 skl... | 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, num... |
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 skl... | 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 skl... | 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 skl... | 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 skl... | 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 skl... | 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 skl... | 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 skl... | 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_to... |
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 skl... | 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 o... | 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.... |
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.commo... | 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 ... |
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.commo... | 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.commo... | 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... |
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.commo... | 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_sta... |
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.commo... | 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_... |
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.commo... | 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.commo... | 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 cap... |
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)
... | 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 v... |
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_c... | 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 `t... |
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",
... | 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 ... |
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( d... | 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 e... |
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... | 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 su... |
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... | 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_la... |
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... | 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_d... |
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... | 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 ... |
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... | 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``. Pa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.