Beispiel #1
0
    def test_seasonality_inference(self):

        # test `seasonal_periods` inference for datetime indices
        freq_str_seasonality_periods_tuples = [
            ("D", 7),
            ("H", 24),
            ("M", 12),
            ("W", 52),
            ("Q", 4),
            ("B", 5),
        ]
        for tuple in freq_str_seasonality_periods_tuples:
            self.helper_test_seasonality_inference(*tuple)

        # test default selection for integer index
        series = TimeSeries.from_values(np.arange(1, 30, 1))
        model = ExponentialSmoothing()
        model.fit(series)
        self.assertEqual(model.seasonal_periods, 12)

        # test whether a model that inferred a seasonality period before will do it again for a new series
        series1 = tg.sine_timeseries(length=100, freq="M")
        series2 = tg.sine_timeseries(length=100, freq="D")
        model = ExponentialSmoothing()
        model.fit(series1)
        model.fit(series2)
        self.assertEqual(model.seasonal_periods, 7)
Beispiel #2
0
 def test_input_models_local_models(self):
     with self.assertRaises(ValueError):
         NaiveEnsembleModel([])
     with self.assertRaises(ValueError):
         NaiveEnsembleModel(
             [NaiveDrift, NaiveSeasonal, Theta, ExponentialSmoothing])
     with self.assertRaises(ValueError):
         NaiveEnsembleModel(
             [NaiveDrift(), NaiveSeasonal,
              Theta(),
              ExponentialSmoothing()])
     NaiveEnsembleModel(
         [NaiveDrift(),
          NaiveSeasonal(),
          Theta(),
          ExponentialSmoothing()])
Beispiel #3
0
 def test_multivariate_input(self):
     es_model = ExponentialSmoothing()
     ts_passengers_enhanced = self.ts_passengers.add_datetime_attribute(
         "month")
     with self.assertRaises(AssertionError):
         es_model.fit(ts_passengers_enhanced)
     es_model.fit(ts_passengers_enhanced["#Passengers"])
     with self.assertRaises(KeyError):
         es_model.fit(ts_passengers_enhanced["2"])
Beispiel #4
0
 def test_fit_univar_ts_with_covariates_for_local_models(self):
     naive = NaiveEnsembleModel(
         [NaiveDrift(),
          NaiveSeasonal(),
          Theta(),
          ExponentialSmoothing()])
     with self.assertRaises(ValueError):
         naive.fit(self.series1, self.series2)
Beispiel #5
0
 train_des = train
 seasonOut = 1
 if m > 1:
     if check_seasonality(train, m=m, max_lag=2 * m):
         _, season = extract_trend_and_seasonality(
             train, m, model=ModelMode.MULTIPLICATIVE)
         train_des = remove_from_series(
             train, season, model=ModelMode.MULTIPLICATIVE)
         seasonOut = season[-m:].shift(m)
         seasonOut = seasonOut.append_values(seasonOut.values())
         seasonOut = seasonOut[:len(test)]
 naive = NaiveDrift()
 naive2 = NaiveSeasonal(K=1)
 naiveSeason = NaiveSeasonal(K=m)
 ses = ExponentialSmoothing(trend=None,
                            seasonal=None,
                            seasonal_periods=m)
 holt = ExponentialSmoothing(seasonal=None,
                             damped=False,
                             trend='additive',
                             seasonal_periods=m)
 damp = ExponentialSmoothing(seasonal=None,
                             damped=True,
                             trend='additive',
                             seasonal_periods=m)
 naive.fit(train)
 naive2.fit(train_des)
 naiveSeason.fit(train)
 try:
     ses.fit(train_des)
 except ValueError:
Beispiel #6
0
import matplotlib.pyplot as plt
plt.style.use("fivethirtyeight")# for pretty graphs

#Upload training data
from google.colab import files
uploaded    = files.upload()
data        = pd.read_csv(io.BytesIO(uploaded['AirPassengers.csv']))

series = TimeSeries.from_dataframe(data, 'Month', '#Passengers')
train, val = series.split_after(pd.Timestamp('19590101'))

"""ExponentialSmoothing implementation"""

from darts.models import ExponentialSmoothing

model = ExponentialSmoothing()
model.fit(train)
prediction_exponential = model.predict(len(val))

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

ARIMA implementation

from darts.models import AutoARIMA
model_aarima = AutoARIMA()
model_aarima.fit(train)
prediction_aarima = model_aarima.predict(len(val))
Beispiel #7
0
logger = get_logger(__name__)

try:
    from darts.models import LinearRegressionModel, RandomForest

    TORCH_AVAILABLE = True
except ImportError:
    logger.warning(
        "Torch not installed - some local forecasting models tests will be skipped"
    )
    TORCH_AVAILABLE = False

# (forecasting models, maximum error) tuples
models = [
    (ExponentialSmoothing(), 5.6),
    (ARIMA(12, 2, 1), 10),
    (ARIMA(1, 1, 1), 40),
    (StatsForecastAutoARIMA(period=12), 4.8),
    (Croston(version="classic"), 34),
    (Croston(version="tsb", alpha_d=0.1, alpha_p=0.1), 34),
    (Theta(), 11.3),
    (Theta(1), 20.2),
    (Theta(-1), 9.8),
    (FourTheta(1), 20.2),
    (FourTheta(-1), 9.8),
    (FourTheta(trend_mode=TrendMode.EXPONENTIAL), 5.5),
    (FourTheta(model_mode=ModelMode.MULTIPLICATIVE), 11.4),
    (FourTheta(season_mode=SeasonalityMode.ADDITIVE), 14.2),
    (FFT(trend="poly"), 11.4),
    (NaiveSeasonal(), 32.4),
Beispiel #8
0
        for train, test in _build_tqdm_iterator(zip(ts_train, ts_test), verbose=True):
            # remove seasonality
            train_des = train
            seasonOut = 1
            season = constant_timeseries(length=len(train), freq=train.freq_str, start_ts=train.start_time())
            if m > 1:
                if check_seasonality(train, m=m, max_lag=2 * m):
                    pass
                    _, season = extract_trend_and_seasonality(train, m, model=ModelMode.MULTIPLICATIVE)
                    train_des = remove_from_series(train, season, model=ModelMode.MULTIPLICATIVE)
                    seasonOut = season[-m:].shift(m)
                    seasonOut = seasonOut.append_values(seasonOut.values())[:len(test)]
            # model selection
            naiveSeason = NaiveSeasonal(K=m)
            naive2 = NaiveSeasonal(K=1)
            ses = ExponentialSmoothing(trend=None, seasonal=None, seasonal_periods=m)
            holt = ExponentialSmoothing(seasonal=None, damped=False, trend='additive', seasonal_periods=m)
            damp = ExponentialSmoothing(seasonal=None, damped=True, trend='additive', seasonal_periods=m)

            fourtheta = FourTheta.select_best_model(train, [1, 2, 3], m)
            theta = Theta(theta=0, season_mode=SeasonalityMode.MULTIPLICATIVE, seasonality_period=m)

            models_simple = [naiveSeason, theta, fourtheta]
            models_des = [naive2, ses, holt, damp]

            # Linear Regression (with constraints)

            def train_pred(id_start=None, id_end=None):
                for m in models_simple:
                    m.fit(train[id_start:id_end])
                for m in models_des:
Beispiel #9
0
 def helper_test_seasonality_inference(self, freq_string,
                                       expected_seasonal_periods):
     series = tg.sine_timeseries(length=200, freq=freq_string)
     model = ExponentialSmoothing()
     model.fit(series)
     self.assertEqual(model.seasonal_periods, expected_seasonal_periods)
import pandas as pd

df = pd.read_csv('data/covid-19/pcr_positive_daily.csv', delimiter=",")

from darts import TimeSeries

series = TimeSeries.from_dataframe(df,
                                   time_col='日付',
                                   value_cols='PCR 検査陽性者数(単日)')

# ここでtraining setとtest setに分割
train, val = series.split_after(pd.Timestamp('20200810'))

from darts.models import ExponentialSmoothing

model = ExponentialSmoothing()
model.fit(train)
prediction = model.predict(len(val))

import matplotlib.pyplot as plt

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

from darts.models.prophet import Prophet

models = [ExponentialSmoothing(), Prophet()]
backtests = [
    model.backtest(series, start=pd.Timestamp('20200810'), forecast_horizon=3)
Beispiel #11
0
ts_var = 'Memory_Used'
time_df = df.filter(['date', ts_var])

#convert variable from object dtype to numeric dtype
time_df[ts_var] = pd.to_numeric(time_df[ts_var], errors='coerce')

#generate time series using darts
series = TimeSeries.from_dataframe(time_df, 'date', ts_var, freq='S')

#treat missing values
filler = MissingValuesFiller()
series = filler.transform(series)

#scale the values
scaler = Scaler()
rescaled = scaler.fit_transform(series)

#training and testing dataset
train, val = rescaled.split_after(pd.Timestamp('2020-01-23 19:41:50'))

#Exponential smoothing model
model = ExponentialSmoothing()
model.fit(train)
prediction = model.predict(len(val))

#Evaluation metrics
rescaled.plot(label='actual')
prediction.plot(label='forecast', lw=3)
plt.legend()
print("MAPE:", mape(prediction, val))