0
0
ML Pythonml~5 mins

Time series components (trend, seasonality) in ML Python

Choose your learning style9 modes available
Introduction

Time series components help us understand patterns in data collected over time. They show us the main directions and repeating cycles in the data.

When you want to predict sales that change over months or years.
When analyzing temperature changes that repeat every year.
When studying website visits that rise and fall daily or weekly.
When checking stock prices for long-term growth or seasonal effects.
When planning inventory based on regular demand cycles.
Syntax
ML Python
Trend: The long-term increase or decrease in data.
Seasonality: Regular repeating patterns over fixed periods.

Trend shows the overall direction, like a steady rise or fall.

Seasonality repeats at regular intervals, like daily, weekly, or yearly cycles.

Examples
Here, trend is the steady monthly increase, and seasonality is the yearly December spike.
ML Python
Trend: Sales slowly increasing every month.
Seasonality: More sales every December.
Trend shows long-term warming, seasonality shows yearly summer highs.
ML Python
Trend: Temperature rising over decades.
Seasonality: Temperature peaks every summer.
Sample Model

This code creates a fake time series with a clear trend and seasonality. It then breaks the data into parts and shows them with plots and prints.

ML Python
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose

# Create time series data with trend and seasonality
np.random.seed(0)
time = np.arange(100)
trend = time * 0.1  # slowly increasing trend
seasonal = 10 * np.sin(2 * np.pi * time / 20)  # repeating pattern every 20 steps
noise = np.random.normal(scale=1, size=100)
data = trend + seasonal + noise

# Decompose the time series
result = seasonal_decompose(data, model='additive', period=20)

# Plot components
plt.figure(figsize=(10,8))
plt.subplot(411)
plt.plot(data)
plt.title('Original Data')
plt.subplot(412)
plt.plot(result.trend)
plt.title('Trend Component')
plt.subplot(413)
plt.plot(result.seasonal)
plt.title('Seasonal Component')
plt.subplot(414)
plt.plot(result.resid)
plt.title('Residual (Noise)')
plt.tight_layout()
plt.show()

# Print first 5 values of each component
print('First 5 trend values:', result.trend[:5])
print('First 5 seasonal values:', result.seasonal[:5])
print('First 5 residual values:', result.resid[:5])
OutputSuccess
Important Notes

Trend values at the edges may be NaN because of how the method calculates moving averages.

Seasonality repeats exactly every set period (20 here), showing the repeating pattern.

Residual is what is left after removing trend and seasonality, often noise.

Summary

Time series data can be split into trend, seasonality, and residual parts.

Trend shows the overall direction over time.

Seasonality shows repeating cycles at fixed intervals.