The Wayback Machine - https://web.archive.org/web/20240917112956/https://www.geeksforgeeks.org/anomaly-detection-in-time-series-data/
Open In App

Anomaly Detection in Time Series Data

Last Updated : 29 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Anomaly detection is the process of identifying data points or patterns in a dataset that deviate significantly from the norm. A time series is a collection of data points gathered over some time. Anomaly detection in time series data may be helpful in various industries, including manufacturing, healthcare, and finance. Anomaly detection in time series data may be accomplished using unsupervised learning approaches like clustering, PCA (Principal Component Analysis), and autoencoders.

What is an Anomaly Detection Algorithm?

Anomaly detection is the process of identifying data points that deviate from the expected patterns in a dataset. Many applications, including fraud detection, intrusion detection, and failure detection, often use anomaly detection techniques. Finding uncommon or very infrequent events that could point to a possible hazard, issue, or opportunity is the aim of anomaly detection.

The autoencoder algorithm is an unsupervised deep learning algorithm that can be used for anomaly detection in time series data. The autoencoder is a neural network that learns to reconstruct its input data By first compressing input data into a lower-dimensional representation and then extending it back to its original dimensions. An autoencoder may be trained on typical time series data to learn a compressed version of the data for anomaly identification. The anomaly score may then be calculated using the reconstruction error between the original and reconstructed data. Anomalies are data points with considerable reconstruction errors.

Time Series Data and Anamoly Detection

In the case of time series data, anomaly detection algorithms are especially important since they help us spot odd patterns in the data that would not be obvious from just looking at the raw data. Anomalies in time series data might appear as abrupt increases or decrease in values, odd patterns, or unexpected seasonality. Time series data is a collection of observations across time.

  • Time series data may be used to teach anomaly detection algorithms, such as the autoencoder, how to represent typical patterns. These algorithms can then utilize this representation to find anomalies. The approach can learn a compressed version of the data by training an autoencoder on regular time series data. The anomaly score may then be calculated using the reconstruction error between the original and reconstructed data. Anomalies are data points with considerable reconstruction errors.
  • Anomaly detection algorithms may be applied to time series data to find odd patterns that could point to a hazard, issue, or opportunity. For instance, in the context of predictive maintenance, a time series anomaly may point to a prospective equipment failure that may be fixed before it results in a large amount of downtime or safety concerns. Anomalies in time series data may reveal market movements or patterns in financial forecasts that may be capitalized on.

The reason for getting precision, recall, and F1 score of 1.0 is that the “ambient_temperature_system_failure.csv” dataset from the NAB repository contains anomalies. If we had gotten precision, recall, and F1 score of 0.0, then that means the “ambient_temperature_system_failure.csv” dataset from the NAB repository does not contain anomalies.

Importing Libraries and Dataset

Python libraries make it very easy for us to handle the data and perform typical and complex tasks with a single line of code.

  • Pandas – This library helps to load the data frame in a 2D array format and has multiple functions to perform analysis tasks in one go.
  • Numpy – Numpy arrays are very fast and can perform large computations in a very short time.
  • Matplotlib/Seaborn – This library is used to draw visualizations.
  • Sklearn – This module contains multiple libraries having pre-implemented functions to perform tasks from data preprocessing to model development and evaluation.
  • TensorFlow – This is an open-source library that is used for Machine Learning and Artificial intelligence and provides a range of functions to achieve complex functionalities with single lines of code.
Python
import pandas as pd
import tensorflow as tf
from keras.layers import Input, Dense
from keras.models import Model
from sklearn.metrics import precision_recall_fscore_support
import matplotlib.pyplot as plt

In this step, we import the libraries required for the implementation of the anomaly detection algorithm using an autoencoder. We import pandas for reading and manipulating the dataset, TensorFlow and Keras for building the autoencoder model, and scikit-learn for calculating the precision, recall, and F1 score.

Python
data = pd.read_csv(
    'ambient_temperature_system_failure.csv')

# Exclude datetime column
data_values = data.drop('timestamp',
                        axis=1).values

# Convert data to float type
data_values = data_values.astype('float32')

# Create new dataframe with converted values
data_converted = pd.DataFrame(data_values,
                              columns=data.columns[1:])

# Add back datetime column
data_converted.insert(0, 'timestamp',
                      data['timestamp'])

We load a dataset called “ambient_temperature_system_failure.csv” from the Numenta Anomaly Benchmark (NAB) dataset, which contains time-series data of ambient temperature readings from a system that experienced a failure. 

The panda’s library is used to read the CSV file from a remote location on GitHub and store it in a variable called “data”.

  • Now, the code drops the “timestamp” column from the “data” variable, since it is not needed for data analysis purposes. The remaining columns are stored in a variable called “data_values”.
  • Then, the “data_values” are converted to the “float32” data type to reduce memory usage, and a new pandas DataFrame called “data_converted” is created with the converted data. The columns of “data_converted” are labeled with the original column names from “data”, except for the “timestamp” column that was previously dropped.
  • Finally, the code adds the “timestamp” column back to “data_converted” at the beginning using the “insert()” method. The resulting DataFrame “data_converted” has the same data as “data” but without the unnecessary “timestamp” column, and the data is in a format that can be used for analysis and visualization.
Python
data_converted = data_converted.dropna()

We remove any missing or NaN values from the dataset.

Anomaly Detection using Autoencoder

It is a type of neural network that learns to compress and then reconstruct the original data, allowing it to identify anomalies in the data.

Python
# Exclude datetime column again
data_tensor = tf.convert_to_tensor(data_converted.drop(
    'timestamp', axis=1).values, dtype=tf.float32)

# Define the autoencoder model
input_dim = data_converted.shape[1] - 1
encoding_dim = 10

input_layer = Input(shape=(input_dim,))
encoder = Dense(encoding_dim, activation='relu')(input_layer)
decoder = Dense(input_dim, activation='relu')(encoder)
autoencoder = Model(inputs=input_layer, outputs=decoder)

# Compile and fit the model
autoencoder.compile(optimizer='adam', loss='mse')
autoencoder.fit(data_tensor, data_tensor, epochs=50,
                batch_size=32, shuffle=True)

# Calculate the reconstruction error for each data point
reconstructions = autoencoder.predict(data_tensor)
mse = tf.reduce_mean(tf.square(data_tensor - reconstructions),
                     axis=1)
anomaly_scores = pd.Series(mse.numpy(), name='anomaly_scores')
anomaly_scores.index = data_converted.index

We define the autoencoder model and fit it to the cleaned data. The autoencoder is used to identify any deviations from the regular patterns in the data that are learned from the data. To reduce the mean squared error between the input and the output, the model is trained. The reconstruction error for each data point is determined using the trained model and is utilized as an anomaly score.

Python
threshold = anomaly_scores.quantile(0.99)
anomalous = anomaly_scores > threshold
binary_labels = anomalous.astype(int)
precision, recall,\
    f1_score, _ = precision_recall_fscore_support(
        binary_labels, anomalous, average='binary')

Here, we define an anomaly detection threshold and assess the model’s effectiveness using precision, recall, and F1 score. Recall is the ratio of true positives to all real positives, whereas precision is the ratio of genuine positives to all projected positives. The harmonic mean of recall and accuracy is the F1 score.

Python
test = data_converted['value'].values
predictions = anomaly_scores.values

print("Precision: ", precision)
print("Recall: ", recall)
print("F1 Score: ", f1_score)

Output:

Precision:  1.0
Recall:  1.0
F1 Score:  1.0

Visualizing the Anomaly

Now let’s plot the anomalies which are predicted by the model and get a feel for whether the predictions made are correct or not by plotting the anomalous examples with red marks with the complete data.

Python
# Plot the data with anomalies marked in red
plt.figure(figsize=(16, 8))
plt.plot(data_converted['timestamp'],
         data_converted['value'])
plt.plot(data_converted['timestamp'][anomalous],
         data_converted['value'][anomalous], 'ro')
plt.title('Anomaly Detection')
plt.xlabel('Time')
plt.ylabel('Value')
plt.show()

Output:

Ambient-Temperature-System

Anomaly represented with red dots on time series data


Get the Complete Notebook:

Notebook: click here.

Dataset: click here.



Similar Reads

Comparing anomaly detection algorithms for outlier detection on toy datasets in Scikit Learn
Anomaly is a deviation from the expected or normal behavior or pattern. Anomaly detection is the process of identifying these unusual patterns or behaviors in data. It is important because anomalies can indicate important events or problems, such as fraudulent activity, equipment failure, or security breaches. Anomaly detection is used in a variety
9 min read
Machine Learning for Anomaly Detection
Anomaly Detection is the technique of identifying rare events or observations which can raise suspicions by being statistically different from the rest of the observations. Such "anomalous" behaviour typically translates to some kind of a problem like a credit card fraud, failing machine in a server, a cyber attack, etc.An anomaly can be broadly ca
4 min read
Anomaly detection with TensorFlow
With the advancement of technology there is also a signification increment of frauds. In modern days, frauds are very common in monetary departments. Let's assume we have an efficient algorithm which observes data flow actions, learns the patterns and can even predict which are the anomalies or frauds. This efficient algorithm can be the autoencode
7 min read
Anomaly detection using Isolation Forest
Anomaly detection is vital across industries, revealing outliers in data that signal problems or unique insights. Isolation Forests offer a powerful solution, isolating anomalies from normal data. In this tutorial, we will explore the Isolation Forest algorithm's implementation for anomaly detection using the Iris flower dataset, showcasing its eff
7 min read
How to use PyTorch for anomaly detection?
An anomaly is something that deviates from what is standard, normal, or expected. In a broad sense, anomalies can be observed in various contexts, such as in data analysis, science, statistics, engineering, and more. In this article, we will see how we can detect anomalies using PyTorch. What is an anomaly?An anomaly is something that deviates from
6 min read
Support Vector Machine (SVM) for Anomaly Detection
Support Vector Machines (SVMs) are powerful supervised learning models that can also be used for anomaly detection. They can be effective for anomaly detection because they find the hyperplane that best separates the normal data points from the anomalies. Mainly, the one-class support vector machine is an unsupervised model for anomaly or outlier d
8 min read
Introduction to Anomaly Detection with Python
Anomaly detection is the process of identifying data points that deviate significantly from the expected pattern or behavior within a dataset. The article aims to provide a comprehensive understanding of anomaly detection, including its definition, types, and techniques, and to demonstrate how to implement anomaly detection in Python using the PyOD
6 min read
Peak Signal Detection in Real-Time Time-Series Data
Real-time peak detection from within time-series data forms an essential and significant technique or method for a variety of different applications, right from anomaly detection in sensor networks to financial market analytics within the realm of big data analytics. Real-time peak detection is particularly challenging due to the need for immediate
7 min read
Real-Time Peak Detection in Noisy Sinusoidal Time-Series
Peak detection from time-series data is an essential procedure in many branches: from signal processing to finance and environment monitoring. Under linguistics, it may serve as the basis for the following action or conclusion. Additionally, peak detection in accurate noisy sinusoidal signals is always one of the most challenging tasks to conduct.
5 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Seasonality Detection in Time Series Data
Time series analysis is a fundamental area of study in statistics and data science that provides a powerful framework for understanding and predicting patterns in sequential data. Time series data, in particular, captures information over successive intervals of time, which allows analysts to uncover trends, seasonal patterns, and other temporal de
5 min read
Difference Between Outlier and Anomaly
In statistics, data science, and machine learning, the terms "outlier" and "anomaly" are often used interchangeably. However, they represent distinct concepts that are crucial for data analysis. Understanding the difference between these two terms is essential for accurate data interpretation and effective problem-solving. This article will delve i
3 min read
Object Detection with Detection Transformer (DETR) by Facebook
Facebook has just released its State of the art object detection Model on 27 May 2020. They are calling it DERT stands for Detection Transformer as it uses transformers to detect objects.This is the first time that transformer is used for such a task of Object detection along with a Convolutional Neural network. There are other Object detection mod
7 min read
Sobel Edge Detection vs. Canny Edge Detection in Computer Vision
Both Sobel and Canny algorithms are popular methods for edge detection in images, but they are suited for different purposes based on their characteristics and the nature of the application. Understanding when to use each can help you achieve better results for specific tasks in image processing. In this article, we are going to explore the differe
9 min read
How to Plot Multiple Series/Lines in a Time Series Using Plotly in R?
Plotly is a powerful and flexible graphing library that enables the creation of interactive plots in R. It is especially useful for visualizing time series data with multiple lines or series. In this article, we will cover how to plot multiple time series in a single plot using Plotly in R. Multiple Time SeriesMultiple time series involve more than
5 min read
Dynamic Time Warping (DTW) in Time Series
Dynamic Time Warping (DTW) is a powerful algorithm used in time series analysis to measure the similarity between two temporal sequences. Unlike traditional distance metrics like Euclidean distance, DTW can handle sequences of different lengths. It can align sequences that may be out of sync, making it particularly useful in fields such as speech r
8 min read
OpenCV | Real Time Road Lane Detection
Autonomous Driving Car is one of the most disruptive innovations in AI. Fuelled by Deep Learning algorithms, they are continuously driving our society forward and creating new opportunities in the mobility sector. An autonomous car can go anywhere a traditional car can go and does everything that an experienced human driver does. But it's very esse
15+ min read
YOLO : You Only Look Once - Real Time Object Detection
YOLO was proposed by Joseph Redmond et al. in 2015. It was proposed to deal with the problems faced by the object recognition models at that time, Fast R-CNN is one of the state-of-the-art models at that time but it has its own challenges such as this network cannot be used in real-time, because it takes 2-3 seconds to predicts an image and therefo
6 min read
Real-Time Object Detection Using TensorFlow
In November 2015, Google's deep artificial intelligence research division introduced TensorFlow, a cutting-edge machine learning library initially designed for internal purposes. This open-source library revolutionized the field, which helped researchers and developers in building, training, and deploying machine learning models. With TensorFlow, t
11 min read
Components of Time Series Data
Time series data is a sequence of data points recorded or collected at regular time intervals. It is a type of data that tracks the evolution of a variable over time, such as sales, stock prices, temperature, etc. The regular time intervals can be daily, weekly, monthly, quarterly, or annually, and the data is often represented as a line graph or t
11 min read
Similarity Search for Time-Series Data
Time-series analysis is a statistical approach for analyzing data that has been structured through time. It entails analyzing past data to detect patterns, trends, and anomalies, then applying this knowledge to forecast future trends. Time-series analysis has several uses, including in finance, economics, engineering, and the healthcare industry. T
15+ min read
Machine Learning for Time Series Data in R
Machine learning (ML) is a subfield of artificial intelligence (AI) that focuses on the development of algorithms and models that enable computers to learn and make predictions or decisions without being explicitly programmed. In R Programming Language it's a way for computers to learn from data and improve their performance on a specific task over
11 min read
Periodicity in Time Series Data using R
Periodicity refers to the existence of repeating patterns or cycles in the time series data. Periodicity helps users to understand the underlying trends and make some predictions which is a fundamental task in various fields like finance to climate science. In time series data, the R Programming Language and its environment for statistical analysis
4 min read
Handling Missing Values in Time Series Data
Handling missing values in time series data in R is a crucial step in the data preprocessing phase. Time series data often contains gaps or missing observations due to various reasons such as sensor malfunctions, human errors, or other external factors. In R Programming Language dealing with missing values appropriately is essential to ensure the a
5 min read
Understanding Partial Autocorrelation Functions (PACF) in Time Series Data
Partial autocorrelation functions (PACF) play a pivotal role in time series analysis, offering crucial insights into the relationship between variables while mitigating confounding influences. In essence, PACF elucidates the direct correlation between a variable and its lagged values after removing the effects of intermediary time steps. This stati
9 min read
Understanding the Moving average (MA) in Time Series Data
Data is often collected with respect to time, whether for scientific or financial purposes. When data is collected in a chronological order, it is referred to as time series data. Analyzing time series data provides insights into how the data behaves over time, including underlying patterns that can help solve problems in various domains. Time seri
15 min read
Stationarity of Time Series Data using R
In this article, we will discuss about Stationarity of Time Series Data, its characteristics, and types, why stationarity matters, and How to test it using R. Stationarity of Time Series Data Stationarity is an important concept when working with time series data. A stationary time series is one whose statistical properties, such as mean, variance,
7 min read
Time Series Data Transformation using Python
Time series data transformation is a crucial step in time series analysis and forecasting, it involves converting raw time series data into a format that is suitable for analysis and modelling. In this article, we will see how we can use time series data transformation, which will be beneficial to our analysis. Types of transformationsIn univariate
6 min read
Effective Methods for Merging Time Series Data with Metadata in Pandas
Combining time series data with metadata is a common task in data analysis, especially in fields like finance, healthcare, and IoT. This process involves merging time-indexed data with additional information that provides context or attributes to the time series. In this article, we will explore the proper way to combine time series data with metad
5 min read
Monitoring and Assessing the Significance of Changes in Time Series Data
Time series data is ubiquitous in various fields such as finance, meteorology, medicine, and more. Detecting significant changes in time series data is crucial for understanding underlying patterns and making informed decisions. However, it is equally important to determine when these changes are no longer significant. This article delves into the
8 min read