Coverage for mlinsights/timeseries/ar.py: 100%

16 statements  

« prev     ^ index     » next       coverage.py v6.4.2, created at 2022-08-09 08:45 +0200

1""" 

2@file 

3@brief Auto-regressor for timeseries. 

4""" 

5from .base import BaseTimeSeries, TimeSeriesRegressorMixin 

6from .dummies import DummyTimeSeriesRegressor 

7 

8 

9class ARTimeSeriesRegressor(BaseTimeSeries, TimeSeriesRegressorMixin): 

10 """ 

11 Base class to build a regressor on timeseries. 

12 The class computes one or several predictions at each time, 

13 between *delay1* and *delay2*. It computes: 

14 :math:`\\hat{Y_{t+d} = f(Y_{t-1}, ..., Y_{t-p})}` 

15 with *d* in *[delay1, delay2[* and 

16 :math:`1 \\leqslant p \\leqslant past`. 

17 """ 

18 

19 def __init__(self, estimator="dummy", past=1, delay1=1, delay2=2, 

20 use_all_past=False, preprocessing=None): 

21 """ 

22 @param estimator estimator to use for regression, 

23 :epkg:`sklearn:linear_model:LinearRegression` 

24 implements a linear auto-regressor, 

25 ``'dummy'`` use past value as predictions 

26 @param past values to use to predict 

27 @param delay1 the model computes the first prediction for 

28 *time=t + delay1* 

29 @param delay2 the model computes the last prediction for 

30 *time=t + delay2* excluded 

31 @param use_all_past use all past features, not only the timeseries 

32 @param preprocessing preprocessing to apply before predicting, 

33 only the timeseries itselves, it can be 

34 a difference, it must be of type 

35 @see cl BaseReciprocalTimeSeriesTransformer 

36 """ 

37 TimeSeriesRegressorMixin.__init__(self) 

38 BaseTimeSeries.__init__(self, past=past, delay1=delay1, delay2=delay2, 

39 use_all_past=use_all_past, preprocessing=preprocessing) 

40 if estimator == "dummy": 

41 self.estimator = DummyTimeSeriesRegressor( 

42 past=past, delay1=delay1, delay2=delay2, use_all_past=use_all_past) 

43 if not hasattr(self.estimator, "fit"): 

44 raise TypeError( # pragma: no cover 

45 f"estimator is not an estimator but {type(estimator)}") 

46 

47 def fit(self, X, y, sample_weight=None): 

48 """ 

49 Trains the model. 

50 

51 :param X: output of 

52 X may be empty (None) 

53 :param y: timeseries (one single vector), array [n_obs] 

54 :param sample_weight: weights None or array [n_obs] 

55 :return: self 

56 """ 

57 X, y, sample_weight = self._base_fit_predict(X, y, sample_weight) 

58 self.estimator_ = (self.estimator.fit(X, y) 

59 if sample_weight is None 

60 else self.estimator.fit(X, y, sample_weight=sample_weight)) 

61 return self 

62 

63 def predict(self, X, y): 

64 """ 

65 Returns the prediction 

66 """ 

67 X, y, _ = self._base_fit_predict(X, y, None) 

68 return self.estimator_.predict(X, y)