The Wayback Machine - https://web.archive.org/web/20241010164042/https://www.geeksforgeeks.org/introduction-to-anomaly-detection-with-python/
Open In App

Introduction to Anomaly Detection with Python

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

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 library.

What is Anomaly Detection?

Anomaly detection, also called outlier detection, is the process of finding patterns in any dataset that deviate significantly from the expected or ‘normal behavior.’ The difference between ‘normal’ and ‘abnormal’ varies depending on the context. Usually, the basic approach of anomaly detection is defining a boundary around the ‘normal’ data points that separates them from the outliers. However, several factors make this approach very challenging, and it’s not effective when dealing with large and multiple datasets.

Techniques in Python

In Python, many approaches can be used to detect these anomalies, such as using ML models, algorithms, or Python libraries, packages, or toolkits. For example:

  • Anomaly Detection Toolkit (ADTK): A Python package for unsupervised or rule-based time series anomaly detection.
  • PyOD: A popular Python library for anomaly detection.

Types of Anomalies

  1. Point Anomalies: Individual data points that deviate significantly from the rest of the data. For example, detecting credit card fraud based on an unusually high ‘amount spent’.
  2. Contextual Anomalies: Depend on the surrounding context. In time-series data, what’s normal at one time might be abnormal at another.
  3. Collective Anomalies: A set of data points together indicate an anomaly. For example, unexpected data transfer activities might indicate a potential cyberattack.

Note: Anomaly detection is considered to be similar to noise removal and novelty detection but not entirely the same.

What are Outliers?

In anomaly detection, outliers are data points that deviate significantly from the rest of the data. They are usually considered the ‘odd ones out’ that don’t conform to the expected patterns or behaviors, falling far outside the typical range of values for a particular feature or set of features.

Types of Outliers

  1. Univariate Outliers: Occur within a single variable. For example, a highly unusual purchase amount.
  2. Multivariate Outliers: Identified by considering multiple variables together. For example, a customer with typical age, location, and purchase behavior.

Techniques and Approaches to Detect Anomaly

1. Univariate Outlier Detection

  1. Z-score: Measures how many standard deviations a point is from the mean. Points exceeding a threshold (e.g., 3 standard deviations) are flagged as outliers.
  2. Interquartile Range (IQR): Uses quartiles to define a range. Points outside the range are considered outliers.
  3. Modified Z-scores: Uses the median and Median Absolute Deviation (MAD) instead of mean and standard deviation, more robust for skewed data.

2. Multivariate Outlier Detection

  1. Isolation Forest: Isolates anomalies faster than normal data during random partitioning.
  2. Local Outlier Factor (LOF): Identifies outliers based on local density deviation from neighbors.
  3. Clustering Techniques (K-means, Hierarchical): Detect points far from established clusters or in small clusters.
  4. Angle-based Outlier Detection (ABOD): Analyzes angles between data points in high dimensions.

3. Machine Learning Based Approach

  1. Density-Based Anomaly Detection:
    • K-Nearest Neighbors (k-NN): Classifies based on nearest neighbors.
    • Local Outlier Factor (LOF): Scores data points based on neighbors’ density compared to their own.
  2. Clustering-Based Anomaly Detection:
    • K-means Algorithm: Common technique to group similar data points into clusters. Data points far from any cluster are flagged as anomalies.
  3. Support Vector Machine-Based Anomaly Detection:
    • One-Class SVM: Learns a boundary around normal data points, identifies anomalies as points falling outside the boundary.
  4. Moving Average Using Discrete Linear Convolution:
    • Smooths data to identify anomalies or deviations from the trend.

4. Gaussian Distribution

  • Assumes data follows a bell-shaped normal distribution curve. Fits a Gaussian distribution model to the data and identifies points with very low probability as anomalies.

5. Autoencoders (in Neural Networks)

  • Encode and reconstruct data points, trained to minimize reconstruction error and flag anomalies. Implemented with libraries like Keras and PyTorch.

Steps for Anomaly Detection Using PyOD

Step 1: Install Required Libraries

First, we need to install the pyod library along with other necessary libraries for data handling and visualization.

!pip install pyod

Step 2: Import Required Libraries

Import the necessary libraries such as pandas for data handling, numpy for numerical computations, and matplotlib and seaborn for data visualization. Additionally, import relevant functions and classes from pyod.

Python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

# Using PyOD
from pyod.utils.data import generate_data, get_outliers_inliers
from pyod.models.pca import PCA
from pyod.utils.data import evaluate_print
from pyod.utils.example import visualize


Step 3: Generate Data

Create a dataset using the generate_data function from pyod. This function generates a synthetic dataset for training, where outliers and inliers are labeled.

Python
# Start by creating a dataset using generate_data() from pyod
X_train, y_train = generate_data(train_only=True)


Step 4: Create DataFrame

Convert the generated data into a Pandas DataFrame for easier handling and visualization. Add a column for the labels.

Python
# Create dataframe from Pandas using the generated data
df_train = pd.DataFrame(X_train)
df_train['y'] = y_train

# Display first few rows
df_train.head()

Step 5: Visualize Data

Visualize the generated dataset using Seaborn’s scatter plot. The color of each point represents its label (outlier or not).

Python
sns.scatterplot(x=0, y=1, hue='y', data=df_train, palette="hls", legend="full")
plt.title('Ground Truth')

Output:

download-(15)


Step 6: Create PCA Model

Initialize a PCA model from pyod. PCA (Principal Component Analysis) is used for anomaly detection by identifying outliers based on principal components.

Python
# Create PCA model
clf = PCA()


Step 7: Train PCA Model

Train the PCA model using the generated data. The fit method is used to train the model.

Python
# Trains PCA model
clf.fit(X_train)


Step 8: Store Predictions

Store the predictions for inliers and outliers in arrays as 0s and 1s. The labels_ attribute contains the predicted labels, and the decision_scores_ attribute contains the anomaly scores.

Python
# Store predictions for inlier and outlier in array as 0s and 1s
y_train_pred = clf.labels_
y_train_scores = clf.decision_scores_


Step 9: Visualize Anomaly Scores

Visualize the anomaly scores using Seaborn’s scatter plot. The color of each point represents its anomaly score.

Python
ax = sns.scatterplot(x=0, y=1, hue=y_train_scores, data=df_train, palette="RdBu_r")

# Using legends, results look bit varied
legend_labels = [f"{score:.2f}" for score in np.unique(y_train_scores)]  # Format scores up to 2 decimal places
ax.legend(title="Anomaly Scores", labels=legend_labels)  # Create legend with title and labels
plt.title('Anomaly Scores by PCA')

Output:

download-(14)

Interpretation of the Output Graph with Anomaly Scores:

  • Dense Clusters: The dense cluster of points in the center with lower anomaly scores (dark blue) indicates normal data points that follow the expected pattern.
  • Scattered Points: The scattered points with higher anomaly scores (red) indicate potential anomalies or outliers that deviate significantly from the normal pattern.
  • Anomaly Detection: This visualization helps in identifying which data points are considered anomalies by the PCA model. Points far from the dense cluster and with higher anomaly scores are flagged as anomalies.

By using this plot, you can visually inspect and analyze the anomalies detected by the PCA model, aiding in understanding and validating the results of your anomaly detection process.

Conclusion

Anomaly detection, also called outlier detection, is a process of finding patterns in any dataset that tends to deviate significantly from the expected or ‘normal behavior’. So far we have discussed about the different types of anomalies (point, contextual, collective) and outliers and implementing anomaly detection in Python.



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
Anomaly Detection in Time Series Data
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 s
7 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
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
Introduction to Object Detection Using Image Processing
Object detection is a crucial task in computer vision that involves identifying and locating objects within an image or video. This task is fundamental for various applications, including autonomous driving, video surveillance, and medical imaging. This article delves into the techniques and methodologies used in object detection, focusing on image
7 min read
Python | Smile detection using OpenCV
Emotion detectors are used in many industries, one being the media industry where it is important for the companies to determine the public reaction to their products. In this article, we are going to build a smile detector using OpenCV which takes in live feed from webcam. The smile/happiness detector that we are going to implement would be a raw
3 min read
Python | Haar Cascades for Object Detection
Object Detection is a computer technology related to computer vision, image processing and deep learning that deals with detecting instances of objects in images and videos. We will do object detection in this article using something known as haar cascades. What are Haar Cascades? Haar Cascade classifiers are an effective way for object detection.
2 min read
Gun Detection using Python-OpenCV
Gun Detection using Object Detection is a helpful tool to have in your repository. It forms the backbone of many fantastic industrial applications. We can use this project for real threat detection in companies or organizations. Prerequisites: Python OpenCV OpenCV(Open Source Computer Vision Library) is a highly optimized library with a focus on Re
4 min read
Python - Eye blink detection project
In this tutorial you will learn about detecting a blink of human eye with the feature mappers knows as haar cascades. Here in the project, we will use the python language along with the OpenCV library for the algorithm execution and image processing respectively. The haar cascades we are going to use in the project are pretrained and stored along w
4 min read
Tumor Detection using classification - Machine Learning and Python
In this article, we will be making a project through Python language which will be using some Machine Learning Algorithms too. It will be an exciting one as after this project you will understand the concepts of using AI & ML with a scripting language. The following libraries/packages will be used in this project: numpy: It's a Python library t
9 min read
Python - Face detection and sending notification
Nowadays python has become one of the most popular languages as well as favorite programming language among developers. The simplified syntax and pattern of this language make the presence of this language in the trending list. The biggest strength of Python is a huge collection of standard library which can be used for the following: Machine Learn
4 min read
Face and Hand Landmarks Detection using Python - Mediapipe, OpenCV
In this article, we will use mediapipe python library to detect face and hand landmarks. We will be using a Holistic model from mediapipe solutions to detect all the face and hand landmarks. We will be also seeing how we can access different landmarks of the face and hands which can be used for different computer vision applications such as sign la
4 min read
FaceMask Detection using TensorFlow in Python
In this article, we’ll discuss our two-phase COVID-19 face mask detector, detailing how our computer vision/deep learning pipeline will be implemented. We’ll use this Python script to train a face mask detector and review the results. Given the trained COVID-19 face mask detector, we’ll proceed to implement two more additional Python scripts used t
9 min read
Online Payment Fraud Detection using Machine Learning in Python
As we are approaching modernity, the trend of paying online is increasing tremendously. It is very beneficial for the buyer to pay online as it saves time, and solves the problem of free money. Also, we do not need to carry cash with us. But we all know that Good thing are accompanied by bad things. The online payment method leads to fraud that can
5 min read
Pneumonia Detection Using CNN in Python
In this article, we will learn how to build a classifier using a simple Convolution Neural Network which can classify the images of patient's xray to detect whether the patient is Normal or affected by Pneumonia. To get more understanding, follow the steps accordingly. Importing Libraries The libraries we will using are : Pandas- The pandas library
10 min read
Z score for Outlier Detection - Python
Z score is an important concept in statistics. Z score is also called standard score. This score helps to understand if a data value is greater or smaller than mean and how far away it is from the mean. More specifically, Z score tells how many standard deviations away a data point is from the mean. Z score = (x -mean) / std. deviationA normal dist
2 min read
Plagiarism Detection using Python
In this article, we are going to learn how to check plagiarism using Python. Plagiarism: Plagiarism basically refers to cheating. It means stealing someone's else work, ideas, or information from the resources without providing the necessary credits to the author. For example, copying text from different resources from word to word without mentioni
10 min read
HBOS: Efficient Outlier Detection with Python
Outlier detection is a crucial task in data analysis, helping to identify rare and anomalous instances that deviate significantly from the majority of the data. One efficient method for unsupervised anomaly detection is the Histogram-Based Outlier Score (HBOS). This article will delve into the principles, implementation, and applications of HBOS in
4 min read
Fake News Detection Model using TensorFlow in Python
Fake News means incorporating information that leads people to the wrong paths. It can have real-world adverse effects that aim to intentionally deceive, gain attention, manipulate public opinion, or damage reputation. It is necessary to detect fake news mainly for media outlets to have the ability to attract viewers to their website to generate on
4 min read
SMS Spam Detection using TensorFlow in Python
In today's society, practically everyone has a mobile phone, and they all get communications (SMS/ email) on their phone regularly. But the essential point is that majority of the messages received will be spam, with only a few being ham or necessary communications. Scammers create fraudulent text messages to deceive you into giving them your perso
8 min read
Age and Gender Detection Using OpenCV in Python
In this article, we will discuss the process of creating an Age and Gender Predictor using OpenCV. Let's divide the task into 2 parts: Age prediction - The prediction will be in the form of categories where categories are a few age intervals like 0-6,18-25, etc.Gender prediction - The prediction is a classifier based where categories are Male and F
3 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
Object Detection vs Object Recognition vs Image Segmentation
Object Recognition: Object recognition is the technique of identifying the object present in images and videos. It is one of the most important applications of machine learning and deep learning. The goal of this field is to teach machines to understand (recognize) the content of an image just like humans do. Object Recognition Using Machine Learni
5 min read