Skip to content

SeasonalNaive

yohou.point.naive.SeasonalNaive

Bases: BasePointForecaster

Seasonal naive forecaster that repeats values from previous season.

Parameters

Name Type Description Default
seasonality int

The seasonal period length. For example, 7 for weekly seasonality in daily data, or 12 for monthly seasonality in monthly data.

1
panel_strategy ('global', multivariate)

How to handle panel data. See BaseForecaster for details.

"global"

Attributes

Name Type Description
interval_ str

Detected time interval of the training data.

Examples

>>> import polars as pl
>>> from datetime import datetime
>>> from yohou.point import SeasonalNaive
>>>
>>> df = pl.DataFrame({
...     "time": pl.datetime_range(
...         start=datetime(2021, 1, 1),
...         end=datetime(2021, 1, 10),
...         interval="1d",
...         eager=True,
...     ),
...     "value": [1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0],
... })
>>> forecaster = SeasonalNaive(seasonality=3)
>>> _ = forecaster.fit(y=df, forecasting_horizon=3)
>>> y_pred = forecaster.predict(forecasting_horizon=3)
>>> len(y_pred)
3

Notes

Predictions repeat the last seasonality observed values cyclically. For example, with seasonality=7 the forecast for each day equals the observation from the same weekday in the last observed week.

See Also

Source Code

Show/Hide source
class SeasonalNaive(BasePointForecaster):
    """Seasonal naive forecaster that repeats values from previous season.

    Parameters
    ----------
    seasonality : int, default=1
        The seasonal period length. For example, 7 for weekly seasonality
        in daily data, or 12 for monthly seasonality in monthly data.
    panel_strategy : {"global", "multivariate"}, default="global"
        How to handle panel data. See `BaseForecaster` for details.

    Attributes
    ----------
    interval_ : str
        Detected time interval of the training data.

    Examples
    --------
    >>> import polars as pl
    >>> from datetime import datetime
    >>> from yohou.point import SeasonalNaive
    >>>
    >>> df = pl.DataFrame({
    ...     "time": pl.datetime_range(
    ...         start=datetime(2021, 1, 1),
    ...         end=datetime(2021, 1, 10),
    ...         interval="1d",
    ...         eager=True,
    ...     ),
    ...     "value": [1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0],
    ... })
    >>> forecaster = SeasonalNaive(seasonality=3)
    >>> _ = forecaster.fit(y=df, forecasting_horizon=3)
    >>> y_pred = forecaster.predict(forecasting_horizon=3)
    >>> len(y_pred)
    3

    Notes
    -----
    Predictions repeat the last ``seasonality`` observed values
    cyclically.  For example, with ``seasonality=7`` the forecast for
    each day equals the observation from the same weekday in the last
    observed week.

    See Also
    --------
    - [`MeanSeasonalNaive`][yohou.point.naive.MeanSeasonalNaive] : Averages multiple past seasonal cycles.
    - [`PointReductionForecaster`][yohou.point.reduction.PointReductionForecaster] : ML-based point forecaster.

    """

    _parameter_constraints: dict = {
        **BasePointForecaster._parameter_constraints,
        "seasonality": [Interval(numbers.Integral, 1, None, closed="left")],
    }

    def __init__(
        self,
        seasonality: StrictInt = 1,
        panel_strategy: Literal["global", "multivariate"] = "global",
    ):
        BasePointForecaster.__init__(
            self,
            feature_transformer=None,
            target_transformer=None,
            target_as_feature=None,
            panel_strategy=panel_strategy,
        )

        self.seasonality = seasonality

    def __sklearn_tags__(self) -> Tags:
        """Get estimator tags.

        Returns
        -------
        Tags
            Estimator tags with yohou-specific attributes.

        """
        tags = super().__sklearn_tags__()
        assert tags.forecaster_tags is not None
        tags.forecaster_tags.requires_exogenous = False
        tags.forecaster_tags.stateful = True
        return tags

    @property
    def _observation_horizon(self) -> int:
        """Return seasonality as the observation horizon."""
        return self.seasonality

    def _predict_one(
        self,
        groups: list[str],
        **params,
    ) -> pl.DataFrame:
        """Predicts `_fit_forecasting_horizon` steps from the observation horizon.

        Parameters
        ----------
        groups : list of str
            Panel group names to predict for.
        **params : dict
            Metadata to route to nested estimators.

        Returns
        -------
        pl.DataFrame
            Predicted time series.

        """
        # Non-panel data
        if self.groups_ is None:
            assert isinstance(self._y_observed, pl.DataFrame)
            y_pred = self._y_observed.select(~cs.by_name("time"))
            if self.fit_forecasting_horizon_ > self.seasonality:
                # Number of full repetitions needed
                n_repeats = int((self.fit_forecasting_horizon_ + self.seasonality - 1) // self.seasonality)
                y_pred = pl.concat([y_pred] * n_repeats)

            y_pred = y_pred.head(self.fit_forecasting_horizon_)

        # Panel data
        else:
            assert isinstance(self._y_observed, dict)
            y_pred = []
            for panel_group_name in groups:
                y_group = self._y_observed[panel_group_name]
                assert isinstance(y_group, pl.DataFrame)
                y_pred_group = y_group.select(~cs.by_name("time"))

                if self.fit_forecasting_horizon_ > self.seasonality:
                    # Number of full repetitions needed
                    n_repeats = (self.fit_forecasting_horizon_ + self.seasonality - 1) // self.seasonality
                    y_pred_group = pl.concat([y_pred_group] * n_repeats)

                y_pred_group = y_pred_group.head(self.fit_forecasting_horizon_)

                # Rename columns to add panel prefix
                y_pred_group = y_pred_group.rename({col: f"{panel_group_name}__{col}" for col in y_pred_group.columns})

                y_pred.append(y_pred_group)

            # Concatenate horizontally (side by side)
            y_pred = pl.concat(y_pred, how="horizontal")

        y_pred = self._add_time_columns(y_pred)

        return y_pred

Methods

__sklearn_tags__()

Get estimator tags.

Returns
Type Description
Tags

Estimator tags with yohou-specific attributes.

Source Code
Show/Hide source
def __sklearn_tags__(self) -> Tags:
    """Get estimator tags.

    Returns
    -------
    Tags
        Estimator tags with yohou-specific attributes.

    """
    tags = super().__sklearn_tags__()
    assert tags.forecaster_tags is not None
    tags.forecaster_tags.requires_exogenous = False
    tags.forecaster_tags.stateful = True
    return tags

Tutorials

The following example notebooks use this component:

  • How to Compose Features with FeatureUnion


    Data-Features

    Combine lag features, rolling statistics, EMA, and scaling in parallel with FeatureUnion and automatic observation horizon resolution.

    View · Open in marimo

  • How to Build a Feature Pipeline


    Data-Features

    Nest FeaturePipeline, FeatureUnion, and DecompositionPipeline for multi-level feature engineering with trend-season-residual decomposition.

    View · Open in marimo

  • How to Create a Custom Scorer


    Evaluation-Search

    Implement a custom point scorer with aggregation, panel support, and systematic testing.

    View · Open in marimo

  • How to Score Multi-Vintage Forecasts


    Evaluation-Search

    Generate multi-vintage predictions with observe_predict, score per step and per vintage, and visualize with heatmap, per-step, and per-vintage plots.

    View · Open in marimo

  • How to Use Point Forecast Metrics


    Evaluation-Search

    Compare MAE, MAPE, MASE, RMSE, and other point metrics across multiple forecasters with componentwise and groupwise aggregation.

    View · Open in marimo

  • How to Combine Interval Forecasters


    Forecasting-Models

    Build interval ensembles with VotingIntervalForecaster using envelope, mean, and median aggregation strategies.

    View · Open in marimo

  • How to Combine Forecasters with VotingPointForecaster


    Forecasting-Models

    Build point ensembles with VotingPointForecaster using mean, weighted, and median aggregation strategies.

    View · Open in marimo

  • How to Choose a Forecasting Method


    Getting-Started

    Interactive decision guide progressing from SeasonalNaive baseline through linear reduction, stationarity transforms, feature enrichment, nonlinear models, decomposition, and prediction intervals.

    View · Open in marimo

  • Conformal Prediction Intervals


    Getting-Started

    Build distribution-free prediction intervals with SplitConformalForecaster using calibration holdouts and configurable conformity scoring functions.

    View · Open in marimo

  • How to Create a Custom Estimator


    Getting-Started

    Implement a LastValueForecaster from scratch, validate it with the check generator, and use it in a forecast pipeline.

    View · Open in marimo

  • Forecasting Workflow


    Getting-Started

    Evaluate forecasters with cross-validation, search hyperparameters with GridSearchCV, and inspect residuals to diagnose model weaknesses.

    View · Open in marimo

  • Naive Forecasters


    Getting-Started

    Baseline forecasting (the first portion of the First Forecast tutorial) with SeasonalNaive using different seasonality periods, the observe/predict streaming workflow, and rolling evaluation patterns.

    View · Open in marimo

  • Panel Data Forecasting


    Getting-Started

    Forecast multiple related time series simultaneously using the __ naming convention, LocalPanelForecaster, and per-group scoring.

    View · Open in marimo

  • How to Save and Load Forecasters


    Getting-Started

    Serialize fitted forecasters with joblib and pickle, reload them in a fresh session, and produce predictions without retraining.

    View · Open in marimo

  • How to Configure LocalPanelForecaster


    Panel-Data

    Wrap any forecaster with LocalPanelForecaster for fully independent per-group clones, parallel fitting via n_jobs, and selective group operations.

    View · Open in marimo

  • How to Forecast Multiple Columns Independently


    Panel-Data

    Use ColumnForecaster to apply a point forecaster independently to each column of a multivariate time series.

    View · Open in marimo

  • How to Build Panel Feature Pipelines


    Panel-Data

    Combine ColumnForecaster, FeaturePipeline, FeatureUnion, and DecompositionPipeline on panel data with per-group scoring on KDD Cup air quality.

    View · Open in marimo

  • Quickstart


    Quickstart

    Comprehensive end-to-end tour of yohou beyond the Getting Started tutorials, covering data loading, baseline forecasting, preprocessing pipelines, decomposition, cross-validation search, and interval prediction.

    View · Open in marimo

  • How to Visualize Forecast Evaluation Results


    Visualization

    Use plot_calibration, plot_score_per_step, and plot_forecast to diagnose forecast accuracy and interval calibration visually.

    View · Open in marimo

  • Forecast Visualization


    Visualization

    Visualise point forecasts from single and multiple models, decomposition pipeline components, and time weight decay functions with interactive Plotly.

    View · Open in marimo

  • How to Visualize Model Selection Results


    Visualization

    Visualise CV fold geometry with expanding and sliding window splitters and hyperparameter search results with plot_splits and plot_cv_results_scatter.

    View · Open in marimo