Exemple #1
0
        def test_prophet_model_default_with_prophet_constructor(self):
            from prophet import Prophet as FBProphet

            model = Prophet()
            assert (
                model._model_builder == FBProphet
            ), "model should use Facebook Prophet"
def predict_series(df_delito_state, delito):
    df_pred = df_delito_state.copy()
    df_pred = pd.DataFrame(df_pred)
    
    df_pred['Year'] = pd.date_range('2015-01', '2021-01', freq='M')
    series = TimeSeries.from_dataframe(df_pred, 'Year', delito)
    #train, val = series.split_before(pd.Timestamp('20200201'))
    train, val = series.split_before(pd.Timestamp('20191230'))

    model = Prophet()
    #model = ExponentialSmoothing()
    model.fit(train)
    prediction = model.predict(len(val))
    prediction = prediction.pd_dataframe()
    prediction[prediction < 0] = 0
    return prediction
Exemple #3
0
        def helper_test_freq_coversion(self, test_cases):
            for freq, period in test_cases.items():
                ts_sine = tg.sine_timeseries(
                    value_frequency=1 / period, length=3, freq=freq
                )
                # this should not raise an error if frequency is known
                _ = Prophet._freq_to_days(freq=ts_sine.freq_str)

            self.assertAlmostEqual(
                Prophet._freq_to_days(freq="30S"),
                30 * Prophet._freq_to_days(freq="S"),
                delta=10e-9,
            )

            # check bad frequency string
            with self.assertRaises(ValueError):
                _ = Prophet._freq_to_days(freq="30SS")
Exemple #4
0
        def test_prophet_model_with_stdout_suppression(self):
            model = Prophet(suppress_stdout_stderror=True)
            model._execute_and_suppress_output = Mock(return_value=True)
            model._model_builder = Mock(return_value=Mock(fit=Mock(return_value=True)))
            df = pd.DataFrame(
                {
                    "ds": pd.date_range(start="2022-01-01", periods=30, freq="D"),
                    "y": np.linspace(0, 10, 30),
                }
            )
            ts = TimeSeries.from_dataframe(df, time_col="ds", value_cols="y")
            model.fit(ts)

            model._execute_and_suppress_output.assert_called_once(), "Suppression should be called once"
Exemple #5
0
from darts.models import AutoARIMA
model_aarima = AutoARIMA()
model_aarima.fit(train)
prediction_aarima = model_aarima.predict(len(val))

series.plot(label='actual', lw=3)
prediction_aarima.plot(label='forecast', lw=3)
plt.legend()
plt.xlabel('Year')

"""Backtesting for comparing two models"""

from darts.backtesting import backtest_forecasting
from darts.models import Prophet
models = [ExponentialSmoothing(), Prophet()]
backtests = [backtest_forecasting(series,
                                  model,
                                  pd.Timestamp('19550101'),
                                  fcast_horizon_n=3)
             for model in models]

"""To compute error metrics — mean absolute percentage error(mape):"""

from darts.metrics import mape
series.plot(label='data')
for i, m in enumerate(models):
    err = mape(backtests[i], series)
    backtests[i].plot(lw=3, label='{}, MAPE={:.2f}%'.format(m, err))
plt.title('Backtests with 3-months forecast horizon')
plt.legend()
Exemple #6
0
        def test_add_seasonality_calls(self):
            # test if adding seasonality at model creation and with method model.add_seasonality() are equal
            kwargs_mandatory = {
                "name": "custom",
                "seasonal_periods": 48,
                "fourier_order": 4,
            }
            kwargs_mandatory2 = {
                "name": "custom2",
                "seasonal_periods": 24,
                "fourier_order": 1,
            }
            kwargs_all = dict(
                kwargs_mandatory, **{"prior_scale": 1.0, "mode": "additive"}
            )
            model1 = Prophet(add_seasonalities=kwargs_all)
            model2 = Prophet()
            model2.add_seasonality(**kwargs_all)
            self.assertEqual(model1._add_seasonalities, model2._add_seasonalities)

            # add multiple seasonalities
            model3 = Prophet(add_seasonalities=[kwargs_mandatory, kwargs_mandatory2])
            self.assertEqual(len(model3._add_seasonalities), 2)

            # seasonality already exists
            with self.assertRaises(ValueError):
                model1.add_seasonality(**kwargs_mandatory)

            # missing mandatory arguments
            with self.assertRaises(ValueError):
                for kw, arg in kwargs_mandatory.items():
                    Prophet(add_seasonalities={kw: arg})

            # invalid keywords
            with self.assertRaises(ValueError):
                Prophet(
                    add_seasonalities=dict(
                        kwargs_mandatory, **{"some_random_keyword": "custom"}
                    )
                )

            # invalid value dtypes
            with self.assertRaises(ValueError):
                Prophet(add_seasonalities=dict({kw: None for kw in kwargs_mandatory}))

            with self.assertRaises(ValueError):
                Prophet(add_seasonalities=dict([]))
Exemple #7
0
        def helper_test_prophet_model(self, period, freq, compare_all_models=False):
            """Test which includes adding custom seasonalities and future covariates. The tests compare the output of
            univariate and stochastic forecasting with the validation timeseries and Prophet's base model output.

            The underlying curve to forecast is a sine timeseries multiplied with another sine timeseries.
            The curve shape repeats every 2*period timesteps (i.e. for period=24 hours -> seasonal_periods=48).
            We take the second sine wave as a covariate for the model.
            With the added custom seasonality and covariate, the model should have a very accurate forecast.
            """
            repetitions = 8
            ts_sine1 = tg.sine_timeseries(
                value_frequency=1 / period, length=period * repetitions, freq=freq
            )
            ts_sine2 = tg.sine_timeseries(
                value_frequency=1 / (period * 2), length=period * repetitions, freq=freq
            )
            ts_sine = ts_sine1 * ts_sine2
            covariate = ts_sine2

            split = int(-period * repetitions / 2)
            train, val = ts_sine[:split], ts_sine[split:]
            train_cov, val_cov = covariate[:split], covariate[split:]

            supress_auto_seasonality = {
                "daily_seasonality": False,
                "weekly_seasonality": False,
                "yearly_seasonality": False,
            }
            custom_seasonality = {
                "name": "custom",
                "seasonal_periods": int(2 * period),
                "fourier_order": 4,
            }
            model = Prophet(
                add_seasonalities=custom_seasonality,
                seasonality_mode="additive",
                **supress_auto_seasonality
            )

            model.fit(train, future_covariates=train_cov)

            # univariate, stochastic and Prophet's base model forecast
            pred_darts = model.predict(
                n=len(val), num_samples=1, future_covariates=val_cov
            )
            compare_preds = [pred_darts]

            if compare_all_models:
                pred_darts_stochastic = model.predict(
                    n=len(val), num_samples=200, future_covariates=val_cov
                )
                pred_raw_df = model.predict_raw(n=len(val), future_covariates=val_cov)
                pred_raw = TimeSeries.from_dataframe(
                    pred_raw_df[["ds", "yhat"]], time_col="ds"
                )
                compare_preds += [
                    pred_darts_stochastic.quantile_timeseries(0.5),
                    pred_raw,
                ]

            # all predictions should fit the underlying curve very well
            for pred in compare_preds:
                for val_i, pred_i in zip(
                    val.univariate_values(), pred.univariate_values()
                ):
                    self.assertAlmostEqual(val_i, pred_i, delta=0.1)
Exemple #8
0
        (RandomForest(lags=12, n_estimators=200, max_depth=3), 15.5),
    ]

# forecasting models with exogenous variables support
multivariate_models = [
    (VARIMA(1, 0, 0), 55.6),
    (VARIMA(1, 1, 1), 57.0),
    (KalmanForecaster(dim_x=30), 30.0),
]

dual_models = [ARIMA(), StatsForecastAutoARIMA(period=12)]

try:
    from darts.models import Prophet

    models.append((Prophet(), 13.5))
    dual_models.append(Prophet())
except ImportError:
    logger.warning("Prophet not installed - will be skipping Prophet tests")

try:
    from darts.models import BATS, TBATS, AutoARIMA

    models.append((AutoARIMA(), 12.2))
    models.append((TBATS(use_trend=True,
                         use_arma_errors=True,
                         use_box_cox=True), 8.0))
    models.append((BATS(use_trend=True, use_arma_errors=True,
                        use_box_cox=True), 10.0))
    dual_models.append(AutoARIMA())
    PMDARIMA_AVAILABLE = True
Exemple #9
0
     'frequency': None,
     'changepoint_range': 0.95,
 }
 if cat == 'Daily':
     prophet_args['daily_seasonality'] = True
 elif cat == 'Hourly':
     prophet_args['daily_seasonality'] = True
 elif cat == 'Weekly':
     prophet_args['weekly_seasonality'] = True
 elif cat == 'Monthly':
     prophet_args['yearly_seasonality'] = True
 elif cat == 'Quarterly':
     prophet_args['yearly_seasonality'] = True
 elif cat == 'Yearly':
     prophet_args['yearly_seasonality'] = True
 prophet = Prophet(**prophet_args)
 derivate = np.diff(train.univariate_values(), n=1)
 jump = derivate.max() / (train.max().max() - train.min().min())
 try:
     if jump <= 0.5:
         prophet.fit(train)
     else:
         prophet.fit(
             train.drop_before(
                 train.time_index[np.argmax(derivate) + 1]))
 except ValueError as e:
     raise e
 forecast_prophet = prophet.predict(len(test))
 m = info_dataset.Frequency[cat[0] + "1"]
 mase_all.append(
     np.vstack([