Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Sktime Pytorch forecasting MovingAvg

From Leeroopedia


Knowledge Sources
Domains Time_Series, Forecasting, Deep_Learning
Last Updated 2026-02-08 08:00 GMT

Overview

MovingAvg is a moving average filter block that smooths time series data by computing a sliding average, primarily used for trend extraction in series decomposition.

Description

The MovingAvg class applies a 1D average pooling operation over the temporal dimension of a time series tensor. To preserve the original sequence length, it pads the input by replicating the first and last values at the boundaries before pooling. The padding is computed dynamically based on whether the kernel size is even or odd, ensuring consistent output dimensions regardless of the kernel configuration.

Usage

Use MovingAvg as part of a series decomposition pipeline where the time series needs to be split into trend and seasonal components. It is commonly used within the SeriesDecomposition layer in models such as DLinear and Autoformer, where the moving average extracts the low-frequency trend component and the residual captures the seasonal pattern.

Code Reference

Source Location

Signature

class MovingAvg(nn.Module):
    def __init__(self, kernel_size, stride):
        ...

    def forward(self, x):
        ...

Import

from pytorch_forecasting.layers._filter._moving_avg_filter import MovingAvg

I/O Contract

Inputs

__init__ Parameters

Name Type Required Description
kernel_size int Yes Size of the moving average kernel (window). Determines how many time steps are averaged together.
stride int Yes Stride for the average pooling operation, typically set to 1 to maintain temporal resolution.

forward Parameters

Name Type Required Description
x torch.Tensor Yes Input tensor of shape (batch_size, seq_len, n_features).

Outputs

Name Type Description
x_out torch.Tensor Smoothed output tensor of the same shape as the input: (batch_size, seq_len, n_features).

Usage Examples

import torch
from pytorch_forecasting.layers._filter._moving_avg_filter import MovingAvg

# Create a moving average filter with kernel size 25, stride 1
moving_avg = MovingAvg(kernel_size=25, stride=1)

# Input: batch of 16 samples, 96 time steps, 7 features
x = torch.randn(16, 96, 7)

# Apply the moving average filter
trend = moving_avg(x)
print(trend.shape)  # torch.Size([16, 96, 7])

# Extract seasonal component as residual
seasonal = x - trend
print(seasonal.shape)  # torch.Size([16, 96, 7])

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment