0
0
ML Pythonml~20 mins

Moving averages in ML Python - ML Experiment: Train & Evaluate

Choose your learning style9 modes available
Experiment - Moving averages
Problem:You want to smooth noisy time series data using moving averages to better see trends.
Current Metrics:Raw data has high variance and noise, making trend detection difficult.
Issue:The data is too noisy, so simple plots are unclear and predictions based on raw data are unstable.
Your Task
Apply moving averages to smooth the time series data and reduce noise while preserving trend information.
Use only simple moving average (SMA) or exponential moving average (EMA).
Do not use complex models or external smoothing libraries.
Hint 1
Hint 2
Hint 3
Solution
ML Python
import numpy as np
import matplotlib.pyplot as plt

# Generate noisy time series data
np.random.seed(42)
time = np.arange(100)
true_signal = np.sin(0.2 * time)  # underlying trend
noise = np.random.normal(0, 0.5, size=time.shape)
noisy_data = true_signal + noise

# Simple Moving Average function
def simple_moving_average(data, window_size):
    return np.convolve(data, np.ones(window_size)/window_size, mode='valid')

# Exponential Moving Average function
def exponential_moving_average(data, alpha):
    ema = [data[0]]
    for point in data[1:]:
        ema.append(alpha * point + (1 - alpha) * ema[-1])
    return np.array(ema)

# Apply SMA with window size 5
sma_5 = simple_moving_average(noisy_data, 5)

# Apply EMA with alpha 0.2
ema_02 = exponential_moving_average(noisy_data, 0.2)

# Plot results
plt.figure(figsize=(10,6))
plt.plot(time, noisy_data, label='Noisy Data', alpha=0.5)
plt.plot(time, true_signal, label='True Signal', linewidth=2)
plt.plot(time[4:], sma_5, label='SMA (window=5)', linewidth=2)
plt.plot(time, ema_02, label='EMA (alpha=0.2)', linewidth=2)
plt.legend()
plt.title('Moving Averages for Smoothing Noisy Time Series')
plt.xlabel('Time')
plt.ylabel('Value')
plt.show()
Added simple moving average function with adjustable window size.
Added exponential moving average function with smoothing factor alpha.
Applied both methods to noisy data to reduce noise and highlight trend.
Visualized original noisy data, true signal, and smoothed results for comparison.
Results Interpretation

Before: The noisy data fluctuates widely around the true signal, making it hard to see the trend.

After: The moving averages smooth out the noise, showing a clearer trend line closer to the true signal.

Moving averages help reduce noise in time series data, making trends easier to identify without complex models.
Bonus Experiment
Try using different window sizes for SMA and different alpha values for EMA to see how smoothing strength affects trend clarity.
💡 Hint
Larger SMA windows smooth more but may lag behind trends; higher EMA alpha reacts faster but may keep more noise.