0
0
ML Pythonml~5 mins

Moving averages in ML Python

Choose your learning style9 modes available
Introduction

Moving averages help smooth out data to see trends better. They reduce noise from random ups and downs.

To understand the general trend of stock prices over time.
To smooth sensor data that has random fluctuations.
To analyze temperature changes over days or months.
To prepare data before feeding it into a machine learning model.
To detect changes or shifts in time series data.
Syntax
ML Python
def moving_average(data, window_size):
    return [sum(data[i:i+window_size]) / window_size for i in range(len(data) - window_size + 1)]

The window_size is how many data points you average at once.

The output list is shorter than the input because the window slides over the data.

Examples
This calculates the average of every 3 numbers in the list.
ML Python
data = [1, 2, 3, 4, 5]
window_size = 3
averages = moving_average(data, window_size)
print(averages)
Here, the moving average uses a window of 2, so it averages pairs of numbers.
ML Python
data = [10, 20, 30, 40, 50, 60]
window_size = 2
averages = moving_average(data, window_size)
print(averages)
Sample Model

This program smooths daily temperature data using a moving average with a window size of 3.

ML Python
def moving_average(data, window_size):
    return [sum(data[i:i+window_size]) / window_size for i in range(len(data) - window_size + 1)]

# Example data: daily temperatures
temperatures = [22, 24, 19, 23, 25, 21, 20]
window = 3
smoothed = moving_average(temperatures, window)
print(f"Original temperatures: {temperatures}")
print(f"Smoothed temperatures with window {window}: {smoothed}")
OutputSuccess
Important Notes

Choosing a larger window size smooths data more but can hide quick changes.

Moving averages work best with evenly spaced data points.

There are different types like simple, weighted, and exponential moving averages.

Summary

Moving averages help see trends by smoothing data.

They average a fixed number of points called the window size.

Useful for preparing and understanding time series data.