• Stars
    star
    1,151
  • Rank 39,090 (Top 0.8 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 8 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Anomaly Detection and Correlation library

luminol

Python Versions Build Status

Overview

Luminol is a light weight python library for time series data analysis. The two major functionalities it supports are anomaly detection and correlation. It can be used to investigate possible causes of anomaly. You collect time series data and Luminol can:

  • Given a time series, detect if the data contains any anomaly and gives you back a time window where the anomaly happened in, a time stamp where the anomaly reaches its severity, and a score indicating how severe is the anomaly compare to others in the time series.
  • Given two time series, help find their correlation coefficient. Since the correlation mechanism allows a shift room, you are able to correlate two peaks that are slightly apart in time.

Luminol is configurable in a sense that you can choose which specific algorithm you want to use for anomaly detection or correlation. In addition, the library does not rely on any predefined threshold on the values of a time series. Instead, it assigns each data point an anomaly score and identifies anomalies using the scores.

By using the library, we can establish a logic flow for root cause analysis. For example, suppose there is a spike in network latency:

  • Anomaly detection discovers the spike in network latency time series
  • Get the anomaly period of the spike, and correlate with other system metrics(GC, IO, CPU, etc.) in the same time range
  • Get a ranked list of correlated metrics, and the root cause candidates are likely to be on the top.

Investigating the possible ways to automate root cause analysis is one of the main reasons we developed this library and it will be a fundamental part of the future work.


Installation

make sure you have python, pip, numpy, and install directly through pip:

pip install luminol

the most up-to-date version of the library is 0.4.


Quick Start

This is a quick start guide for using luminol for time series analysis.

  1. import the library
import luminol
  1. conduct anomaly detection on a single time series ts.
detector = luminol.anomaly_detector.AnomalyDetector(ts)
anomalies = detector.get_anomalies()
  1. if there is anomaly, correlate the first anomaly period with a secondary time series ts2.
if anomalies:
    time_period = anomalies[0].get_time_window()
    correlator = luminol.correlator.Correlator(ts, ts2, time_period)
  1. print the correlation coefficient
print(correlator.get_correlation_result().coefficient)

These are really simple use of luminol. For information about the parameter types, return types and optional parameters, please refer to the API.


Modules

Modules in Luminol refers to customized classes developed for better data representation, which are Anomaly, CorrelationResult and TimeSeries.

Anomaly

class luminol.modules.anomaly.Anomaly
It contains these attributes:

self.start_timestamp: # epoch seconds represents the start of the anomaly period.
self.end_timestamp: # epoch seconds represents the end of the anomaly period.
self.anomaly_score: # a score indicating how severe is this anomaly.
self.exact_timestamp: # epoch seconds indicates when the anomaly reaches its severity.

It has these public methods:

  • get_time_window(): returns a tuple (start_timestamp, end_timestamp).

CorrelationResult

class luminol.modules.correlation_result.CorrelationResult
It contains these attributes:

self.coefficient: # correlation coefficient.
self.shift: # the amount of shift needed to get the above coefficient.
self.shifted_coefficient: # a correlation coefficient with shift taken into account.

TimeSeries

class luminol.modules.time_series.TimeSeries

__init__(self, series)
  • series(dict): timestamp -> value

It has a various handy methods for manipulating time series, including generator iterkeys, itervalues, and iteritems. It also supports binary operations such as add and subtract. Please refer to the code and inline comments for more information.


API

The library contains two classes: AnomalyDetector and Correlator, and there are two sets of APIs, one corresponding to each class. There are also customized modules for better data representation. The Modules section in this documentation may provide useful information as you walk through the APIs.

AnomalyDetector

class luminol.anomaly_detector.AnomalyDetecor

__init__(self, time_series, baseline_time_series=None, score_only=False, score_threshold=None,
         score_percentile_threshold=None, algorithm_name=None, algorithm_params=None,
         refine_algorithm_name=None, refine_algorithm_params=None)
  • time_series: The metric you want to conduct anomaly detection on. It can have the following three types:
1. string: # path to a csv file
2. dict: # timestamp -> value
3. lumnol.modules.time_series.TimeSeries
  • baseline_time_series: an optional baseline time series of one the types mentioned above.
  • score only(bool): if asserted, anomaly scores for the time series will be available, while anomaly periods will not be identified.
  • score_threshold: if passed, anomaly scores above this value will be identified as anomaly. It can override score_percentile_threshold.
  • score_precentile_threshold: if passed, anomaly scores above this percentile will be identified as anomaly. It can not override score_threshold.
  • algorithm_name(string): if passed, the specific algorithm will be used to compute anomaly scores.
  • algorithm_params(dict): additional parameters for algorithm specified by algorithm_name.
  • refine_algorithm_name(string): if passed, the specific algorithm will be used to compute the time stamp of severity within each anomaly period.
  • refine_algorithm_params(dict): additional parameters for algorithm specified by refine_algorithm_params.

Available algorithms and their additional parameters are:

1.  'bitmap_detector': # behaves well for huge data sets, and it is the default detector.
    {
      'precision'(4): # how many sections to categorize values,
      'lag_window_size'(2% of the series length): # lagging window size,
      'future_window_size'(2% of the series length): # future window size,
      'chunk_size'(2): # chunk size.
    }
2.  'default_detector': # used when other algorithms fails, not meant to be explicitly used.
3.  'derivative_detector': # meant to be used when abrupt changes of value are of main interest.
    {
      'smoothing factor'(0.2): # smoothing factor used to compute exponential moving averages
                                # of derivatives.
    }
4.  'exp_avg_detector': # meant to be used when values are in a roughly stationary range.
                        # and it is the default refine algorithm.
    {
      'smoothing factor'(0.2): # smoothing factor used to compute exponential moving averages.
      'lag_window_size'(20% of the series length): # lagging window size.
      'use_lag_window'(False): # if asserted, a lagging window of size lag_window_size will be used.
    }

It may seem vague for the meanings of some parameters above. Here are some useful insights:

The AnomalyDetector class has the following public methods:

  • get_all_scores(): returns an anomaly score time series of type TimeSeries.
  • get_anomalies(): return a list of Anomaly objects.

Correlator

class luminol.correlator.Correlator

__init__(self, time_series_a, time_series_b, time_period=None, use_anomaly_score=False,
         algorithm_name=None, algorithm_params=None)
  • time_series_a: a time series, for its type, please refer to time_series for AnomalyDetector above.
  • time_series_b: a time series, for its type, please refer to time_series for AnomalyDetector above.
  • time_period(tuple): a time period where to correlate the two time series.
  • use_anomaly_score(bool): if asserted, the anomaly scores of the time series will be used to compute correlation coefficient instead of the original data in the time series.
  • algorithm_name: if passed, the specific algorithm will be used to calculate correlation coefficient.
  • algorithm_params: any additional parameters for the algorithm specified by algorithm_name.

Available algorithms and their additional parameters are:

1.  'cross_correlator': # when correlate two time series, it tries to shift the series around so that it
                       # can catch spikes that are slightly apart in time.
    {
      'max_shift_seconds'(60): # maximal allowed shift room in seconds,
      'shift_impact'(0.05): # weight of shift in the shifted coefficient.
    }

The Correlator class has the following public methods:

  • get_correlation_result(): return a CorrelationResult object.
  • is_correlated(threshold=0.7): if coefficient above the passed in threshold, return a CorrelationResult object. Otherwise, return false.

Example

  1. Calculate anomaly scores.
from luminol.anomaly_detector import AnomalyDetector

ts = {0: 0, 1: 0.5, 2: 1, 3: 1, 4: 1, 5: 0, 6: 0, 7: 0, 8: 0}

my_detector = AnomalyDetector(ts)
score = my_detector.get_all_scores()
for timestamp, value in score.iteritems():
    print(timestamp, value)

""" Output:
0 0.0
1 0.873128250131
2 1.57163085024
3 2.13633686334
4 1.70906949067
5 2.90541813415
6 1.17154110935
7 0.937232887479
8 0.749786309983
"""
  1. Correlate ts1 with ts2 on every anomaly.
from luminol.anomaly_detector import AnomalyDetector
from luminol.correlator import Correlator

ts1 = {0: 0, 1: 0.5, 2: 1, 3: 1, 4: 1, 5: 0, 6: 0, 7: 0, 8: 0}
ts2 = {0: 0, 1: 0.5, 2: 1, 3: 0.5, 4: 1, 5: 0, 6: 1, 7: 1, 8: 1}

my_detector = AnomalyDetector(ts1, score_threshold=1.5)
score = my_detector.get_all_scores()
anomalies = my_detector.get_anomalies()
for a in anomalies:
    time_period = a.get_time_window()
    my_correlator = Correlator(ts1, ts2, time_period)
    if my_correlator.is_correlated(threshold=0.8):
        print("ts2 correlate with ts1 at time period (%d, %d)" % time_period)

""" Output:
ts2 correlates with ts1 at time period (2, 5)
"""

Contributing

Clone source and install package and dev requirements:

pip install -r requirements.txt
pip install pytest pytest-cov pylama

Tests and linting run with:

python -m pytest --cov=src/luminol/ src/luminol/tests/
python -m pylama -i E501 src/luminol/

More Repositories

1

school-of-sre

At LinkedIn, we are using this curriculum for onboarding our entry-level talents into the SRE role.
HTML
7,649
star
2

css-blocks

High performance, maintainable stylesheets.
TypeScript
6,334
star
3

Burrow

Kafka Consumer Lag Checking
Go
3,644
star
4

databus

Source-agnostic distributed change data capture system
Java
3,587
star
5

qark

Tool to look for several security related Android application vulnerabilities
Python
3,117
star
6

dustjs

Asynchronous Javascript templating for the browser and server
JavaScript
2,917
star
7

cruise-control

Cruise-control is the first of its kind to fully automate the dynamic workload rebalance and self-healing of a Kafka cluster. It provides great value to Kafka users by simplifying the operation of Kafka clusters.
Java
2,634
star
8

rest.li

Rest.li is a REST+JSON framework for building robust, scalable service architectures using dynamic discovery and simple asynchronous APIs.
Java
2,435
star
9

kafka-monitor

Xinfra Monitor monitors the availability of Kafka clusters by producing synthetic workloads using end-to-end pipelines to obtain derived vital statistics - E2E latency, service produce/consume availability, offsets commit availability & latency, message loss rate and more.
Java
1,991
star
10

dexmaker

A utility for doing compile or runtime code generation targeting Android's Dalvik VM
Java
1,843
star
11

greykite

A flexible, intuitive and fast forecasting library
Python
1,788
star
12

ambry

Distributed object store
Java
1,717
star
13

shiv

shiv is a command line utility for building fully self contained Python zipapps as outlined in PEP 441, but with all their dependencies included.
Python
1,693
star
14

swift-style-guide

LinkedIn's Official Swift Style Guide
1,436
star
15

dr-elephant

Dr. Elephant is a job and flow-level performance monitoring and tuning tool for Apache Hadoop and Apache Spark
Java
1,341
star
16

detext

DeText: A Deep Neural Text Understanding Framework for Ranking and Classification Tasks
Python
1,254
star
17

parseq

Asynchronous Java made easier
Java
1,158
star
18

oncall

Oncall is a calendar tool designed for scheduling and managing on-call shifts. It can be used as source of dynamic ownership info for paging systems like http://iris.claims.
Python
1,095
star
19

test-butler

Reliable Android Testing, at your service
Java
1,040
star
20

goavro

Go
948
star
21

PalDB

An embeddable write-once key-value store written in Java
Java
934
star
22

brooklin

An extensible distributed system for reliable nearline data streaming at scale
Java
891
star
23

iris

Iris is a highly configurable and flexible service for paging and messaging.
Python
791
star
24

photon-ml

A scalable machine learning library on Apache Spark
Terra
790
star
25

Hakawai

A powerful, extensible UITextView.
Objective-C
780
star
26

URL-Detector

A Java library to detect and normalize URLs in text
Java
778
star
27

eyeglass

NPM Modules for Sass
TypeScript
741
star
28

opticss

A CSS Optimizer
TypeScript
715
star
29

coral

Coral is a translation, analysis, and query rewrite engine for SQL and other relational languages.
Java
714
star
30

LiTr

Lightweight hardware accelerated video/audio transcoder for Android.
Java
590
star
31

pygradle

Using Gradle to build Python projects
Java
584
star
32

kafka-tools

A collection of tools for working with Apache Kafka.
Python
581
star
33

flashback

mock the internet
Java
578
star
34

LayoutTest-iOS

Write unit tests which test the layout of a view in multiple configurations
Objective-C
565
star
35

FeatureFu

Library and tools for advanced feature engineering
Java
564
star
36

FastTreeSHAP

Fast SHAP value computation for interpreting tree-based models
Python
493
star
37

venice

Venice, Derived Data Platform for Planet-Scale Workloads.
Java
413
star
38

Spyglass

A library for mentions on Android
Java
381
star
39

dagli

Framework for defining machine learning models, including feature generation and transformations, as directed acyclic graphs (DAGs).
Java
353
star
40

ml-ease

ADMM based large scale logistic regression
Java
333
star
41

cruise-control-ui

Cruise Control Frontend (CCFE): Single Page Web Application to Manage Large Scale of Kafka Clusters
Vue
329
star
42

transport

A framework for writing performant user-defined functions (UDFs) that are portable across a variety of engines including Apache Spark, Apache Hive, and Presto.
Java
288
star
43

dph-framework

HTML
285
star
44

spark-tfrecord

Read and write Tensorflow TFRecord data from Apache Spark.
Scala
276
star
45

openhouse

Open Control Plane for Tables in Data Lakehouse
Java
256
star
46

isolation-forest

A Spark/Scala implementation of the isolation forest unsupervised outlier detection algorithm.
Scala
217
star
47

LiFT

The LinkedIn Fairness Toolkit (LiFT) is a Scala/Spark library that enables the measurement of fairness in large scale machine learning workflows.
Scala
167
star
48

shaky-android

Shake to send feedback for Android.
Java
157
star
49

pyexchange

Python wrapper for Microsoft Exchange
Python
151
star
50

asciietch

A graphing library with the goal of making it simple to graphs using ascii characters.
Python
137
star
51

python-avro-json-serializer

Serializes data into a JSON format using AVRO schema.
Python
136
star
52

li-apache-kafka-clients

li-apache-kafka-clients is a wrapper library for the Apache Kafka vanilla clients. It provides additional features such as large message support and auditing to the Java producer and consumer in the open source Apache Kafka.
Java
132
star
53

gdmix

A deep ranking personalization framework
Python
131
star
54

dynamometer

A tool for scale and performance testing of HDFS with a specific focus on the NameNode.
Java
129
star
55

Avro2TF

Avro2TF is designed to fill the gap of making users' training data ready to be consumed by deep learning training frameworks.
Scala
125
star
56

linkedin-gradle-plugin-for-apache-hadoop

Groovy
117
star
57

datahub-gma

General Metadata Architecture
Java
112
star
58

dex-test-parser

Find all test methods in an Android instrumentation APK
Kotlin
104
star
59

cassette

An efficient, file-based FIFO Queue for iOS and macOS.
Objective-C
95
star
60

spaniel

LinkedIn's JavaScript viewport tracking library and IntersectionObserver polyfill
JavaScript
91
star
61

Hoptimator

Multi-hop declarative data pipelines
Java
77
star
62

migz

Multithreaded, gzip-compatible compression and decompression, available as a platform-independent Java library and command-line utilities.
Java
76
star
63

sysops-api

sysops-api is a framework designed to provide visability from tens of thousands of machines in seconds.
Python
75
star
64

avro-util

Collection of utilities to allow writing java code that operates across a wide range of avro versions.
Java
73
star
65

iceberg

A temporary home for LinkedIn's changes to Apache Iceberg (incubating)
Java
60
star
66

kube2hadoop

Secure HDFS Access from Kubernetes
Java
59
star
67

linkedin.github.com

Listing of all our public GitHub projects.
JavaScript
59
star
68

dynoyarn

DynoYARN is a framework to run simulated YARN clusters and workloads for YARN scale testing.
Java
58
star
69

Tachyon

An Android library that provides a customizable calendar day view UI widget.
Java
57
star
70

DuaLip

DuaLip: Dual Decomposition based Linear Program Solver
Scala
56
star
71

iris-relay

Stateless reverse proxy for thirdparty service integration with Iris API.
Python
49
star
72

Cytodynamics

Classloader isolation library.
Java
48
star
73

concurrentli

Classes for multithreading that expand on java.util.concurrent, adding convenience, efficiency and new tools to multithreaded Java programs
Java
43
star
74

iris-mobile

A mobile interface for linkedin/iris, built for iOS and Android on the Ionic platform
TypeScript
41
star
75

instantsearch-tutorial

Sample code for building an end-to-end instant search solution
JavaScript
39
star
76

lambda-learner

Lambda Learner is a library for iterative incremental training of a class of supervised machine learning models.
Python
37
star
77

self-focused

Helps make a single page application more friendly to screen readers.
JavaScript
35
star
78

tracked-queue

An autotracked implementation of a ring-buffer-backed double-ended queue
TypeScript
35
star
79

PASS-GNN

Python
35
star
80

QueryAnalyzerAgent

Analyze MySQL queries with negligible overhead
Go
35
star
81

TE2Rules

Python library to explain Tree Ensemble models (TE) like XGBoost, using a rule list.
Python
31
star
82

performance-quality-models

Personalizing Performance model repository
Jupyter Notebook
31
star
83

Iris-message-processor

Iris-message-processor is a fully distributed Go application meant to replace the sender functionality of Iris and provide reliable, scalable, and extensible incident and out of band message processing and sending.
Go
26
star
84

smart-arg

Smart Arguments Suite (smart-arg) is a slim and handy python lib that helps one work safely and conveniently with command line arguments.
Python
23
star
85

data-integration-library

The Data Integration Library project provides a library of generic components based on a multi-stage architecture for data ingress and egress.
Java
22
star
86

linkedin-calcite

LinkedIn's version of Apache Calcite
Java
22
star
87

atscppapi

This library provides wrappers around the existing Apache Traffic Server API which will vastly simplify the process of writing Apache Traffic Server plugins.
C++
20
star
88

high-school-trainee

LinkedIn Women in Tech High School Trainee Program
Python
18
star
89

play-parseq

Play-ParSeq is a Play module which seamlessly integrates ParSeq with Play Framework
Scala
17
star
90

forthic

Python
17
star
91

icon-magic

Automated icon build system for iOS, Android and Web
TypeScript
17
star
92

QuantEase

QuantEase, a layer-wise quantization framework, frames the problem as discrete-structured non-convex optimization. Our work leverages Coordinate Descent techniques, offering high-quality solutions without the need for matrix inversion or decomposition.
Python
15
star
93

kafka-remote-storage-azure

Java
13
star
94

play-restli

A library that simplifies building restli services on top of the play server.
Java
12
star
95

spark-inequality-impact

Scala
11
star
96

AlerTiger

Jupyter Notebook
9
star
97

Li-Airflow-Backfill-Plugin

Li-Airflow-Backfill-Plugin is a plugin to work with Apache Airflow to provide data backfill feature, ie. to rerun pipelines for a certain date range.
Python
8
star
98

gobblin-elr

This is a read-only mirror of apache/gobblin
Java
5
star
99

o19-bmc-firmware

OpenBMC is an open software framework to build a complete Linux image for a Board Management Controller (BMC)
C
4
star
100

linkedin-gtm-community-template

Smarty
4
star