Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented moving average #926

Merged
merged 9 commits into from
Jul 27, 2020
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions src/gluonts/model/trivial/mean.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,54 @@ def predict_item(self, item: DataEntry) -> SampleForecast:
)


class MovingAveragePredictor(RepresentablePredictor):
"""
A :class:`Predictor` that predicts the moving average based on the
last `context_length` elements of the input target.

If `prediction_length` = 1, the output is the moving average
based on the last `context_length` elements of the input target.

If `prediction_length` > 1, the output is the moving average based on the
last `context_length` elements of the input target, where
previously calculated moving averages are appended at the end of the input target.
Hence, for `prediction_length` larger than `context_length`, there will be
cases where the moving average is calculated on top of previous moving averages.

Parameters
----------
context_length
Length of the target context used to condition the predictions.
prediction_length
Length of the prediction horizon.
freq
Frequency of the predicted data.
"""

@validated()
def __init__(
self, prediction_length: int, freq: str, context_length: int,
melopeo marked this conversation as resolved.
Show resolved Hide resolved
) -> None:
super().__init__(freq=freq, prediction_length=prediction_length)
self.context_length = context_length

def predict_item(self, item: DataEntry) -> SampleForecast:

target = item["target"].tolist()

for _ in range(self.prediction_length):
window = target[-self.context_length :]
target.append(np.nanmean(window))

start_date = frequency_add(item["start"], len(item["target"]))
melopeo marked this conversation as resolved.
Show resolved Hide resolved
return SampleForecast(
samples=np.array([target[-self.prediction_length :]]),
start_date=start_date,
freq=self.freq,
item_id=item.get(FieldName.ITEM_ID),
)


class MeanEstimator(Estimator):
"""
An `Estimator` that computes the mean targets in the training data,
Expand Down