https://github.com/salesforce/merlion

Merlion: A Machine Learning Framework for Time Series Intelligence

https://github.com/salesforce/merlion

Science Score: 33.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
  • DOI references
  • Academic publication links
    Links to: arxiv.org
  • Committers with academic emails
    1 of 17 committers (5.9%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (17.4%) to scientific vocabulary

Keywords

anomaly-detection automl benchmarking ensemble-learning forecasting machine-learning time-series
Last synced: 5 months ago · JSON representation

Repository

Merlion: A Machine Learning Framework for Time Series Intelligence

Basic Info
  • Host: GitHub
  • Owner: salesforce
  • License: bsd-3-clause
  • Language: Python
  • Default Branch: main
  • Homepage:
  • Size: 101 MB
Statistics
  • Stars: 4,349
  • Watchers: 63
  • Forks: 344
  • Open Issues: 37
  • Releases: 18
Topics
anomaly-detection automl benchmarking ensemble-learning forecasting machine-learning time-series
Created over 4 years ago · Last pushed over 1 year ago
Metadata Files
Readme Contributing License Code of conduct Codeowners Security Authors

README.md

Logo
Tests Coverage PyPI Version docs

Merlion: A Machine Learning Library for Time Series

Table of Contents

  1. Introduction
  2. Comparison with Related Libraries
  3. Installation
  4. Documentation
  5. Getting Started
    1. Anomaly Detection
    2. Forecasting
  6. Evaluation and Benchmarking
  7. Technical Report and Citing Merlion

Introduction

Merlion is a Python library for time series intelligence. It provides an end-to-end machine learning framework that includes loading and transforming data, building and training models, post-processing model outputs, and evaluating model performance. It supports various time series learning tasks, including forecasting, anomaly detection, and change point detection for both univariate and multivariate time series. This library aims to provide engineers and researchers a one-stop solution to rapidly develop models for their specific time series needs, and benchmark them across multiple time series datasets.

Merlion's key features are - Standardized and easily extensible data loading & benchmarking for a wide range of forecasting and anomaly detection datasets. This includes transparent support for custom datasets. - A library of diverse models for anomaly detection, forecasting, and change point detection, all unified under a shared interface. Models include classic statistical methods, tree ensembles, and deep learning approaches. Advanced users may fully configure each model as desired. - Abstract DefaultDetector and DefaultForecaster models that are efficient, robustly achieve good performance, and provide a starting point for new users. - AutoML for automated hyperaparameter tuning and model selection. - Unified API for using a wide range of models to forecast with exogenous regressors. - Practical, industry-inspired post-processing rules for anomaly detectors that make anomaly scores more interpretable, while also reducing the number of false positives. - Easy-to-use ensembles that combine the outputs of multiple models to achieve more robust performance. - Flexible evaluation pipelines that simulate the live deployment & re-training of a model in production, and evaluate performance on both forecasting and anomaly detection. - Native support for visualizing model predictions, including with a clickable visual UI. - Distributed computation backend using PySpark, which can be used to serve time series applications at industrial scale.

Comparison with Related Libraries

The table below provides a visual overview of how Merlion's key features compare to other libraries for time series anomaly detection and/or forecasting.

| | Merlion | Prophet | Alibi Detect | Kats | darts | statsmodels | nixtla | GluonTS | RRCF | STUMPY | Greykite |pmdarima :--- | :---: | :---:| :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :----: | :---: | Univariate Forecasting | ✅ | ✅| | ✅ | ✅ | ✅ | ✅ | ✅ | | |✅| ✅ | Multivariate Forecasting | ✅ | | | ✅ | ✅ | ✅| ✅ | ✅ | | | | | | Univariate Anomaly Detection | ✅ | ✅ | ✅ | ✅ | ✅ | | | | ✅ | ✅ | ✅ | ✅ | | Multivariate Anomaly Detection | ✅ | | ✅ | ✅ | ✅ | | | | ✅ | ✅ | | | | | Pre Processing | ✅ | | ✅ | ✅ | ✅ | | ✅ | ✅ | | | ✅ | ✅ | Post Processing | ✅ | | ✅ | | | | | | | | | | | AutoML | ✅ | | | ✅ | | | | | | | | ✅ | | ✅ | Ensembles | ✅ | | | ✅ | ✅ | | | | | ✅ | | | | | Benchmarking | ✅ | | | | ✅ | ✅ | ✅ | | | | ✅ | | Visualization | ✅ | ✅ | | ✅ | ✅ | | | | | | ✅ |

The following features are new in Merlion 2.0:

| | Merlion | Prophet | Alibi Detect | Kats | darts | statsmodels | nixtla | GluonTS | RRCF | STUMPY | Greykite |pmdarima :--- | :---: | :---:| :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :----: | :---: | Exogenous Regressors | ✅ | ✅ | | |✅ | ✅ | | | | | ✅ | ✅ | Change Point Detection | ✅ | ✅ | ✅ | ✅ | | | | | | | ✅ | | Clickable Visual UI | ✅ | | | | | | | | | | | | Distributed Backend | ✅ | | | | | | ✅ | | | | |

Installation

Merlion consists of two sub-repos: merlion implements the library's core time series intelligence features, and ts_datasets provides standardized data loaders for multiple time series datasets. These loaders load time series as pandas.DataFrame s with accompanying metadata.

You can install merlion from PyPI by calling pip install salesforce-merlion. You may install from source by cloning this repoand calling pip install Merlion/, or pip install -e Merlion/ to install in editable mode. You may install additional dependencies via pip install salesforce-merlion[all], or by calling pip install "Merlion/[all]" if installing from source. Individually, the optional dependencies include dashboard for a GUI dashboard, spark for a distributed computation backend with PySpark, and deep-learning for all deep learning models.

To install the data loading package ts_datasets, clone this repo and call pip install -e Merlion/ts_datasets/. This package must be installed in editable mode (i.e. with the -e flag) if you don't want to manually specify the root directory of every dataset when initializing its data loader.

Note the following external dependencies:

  1. Some of our forecasting models depend on OpenMP. If using conda, please conda install -c conda-forge lightgbm before installing our package. This will ensure that OpenMP is configured to work with the lightgbm package (one of our dependencies) in your conda environment. If using Mac, please install Homebrew and call brew install libomp so that the OpenMP libary is available for the model.

  2. Some of our anomaly detection models depend on the Java Development Kit (JDK). For Ubuntu, call sudo apt-get install openjdk-11-jdk. For Mac OS, install Homebrew and call brew tap adoptopenjdk/openjdk && brew install --cask adoptopenjdk11. Also ensure that java can be found on your PATH, and that the JAVA_HOME environment variable is set.

Documentation

For example code and an introduction to Merlion, see the Jupyter notebooks in examples, and the guided walkthrough here. You may find detailed API documentation (including the example code) here. The technical report outlines Merlion's overall architecture and presents experimental results on time series anomaly detection & forecasting for both univariate and multivariate time series.

Getting Started

The easiest way to get started is to use the GUI web-based dashboard. This dashboard provides a great way to quickly experiment with many models on your own custom datasets. To use it, install Merlion with the optional dashboard dependency (i.e. pip install salesforce-merlion[dashboard]), and call python -m merlion.dashboard from the command line. You can view the dashboard at http://localhost:8050. Below, we show some screenshots of the dashboard for both anomaly detection and forecasting.

anomaly dashboard

forecast dashboard

To help you get started with using Merlion in your own code, we provide below some minimal examples using Merlion default models for both anomaly detection and forecasting.

Anomaly Detection

Here, we show the code to replicate the results from the anomaly detection dashboard above. We begin by importing Merlion’s TimeSeries class and the data loader for the Numenta Anomaly Benchmark NAB. We can then divide a specific time series from this dataset into training and testing splits.

```python from merlion.utils import TimeSeries from ts_datasets.anomaly import NAB

Data loader returns pandas DataFrames, which we convert to Merlion TimeSeries

timeseries, metadata = NAB(subset="realKnownCause")[3] traindata = TimeSeries.frompd(timeseries[metadata.trainval]) testdata = TimeSeries.frompd(timeseries[~metadata.trainval]) testlabels = TimeSeries.from_pd(metadata.anomaly[~metadata.trainval]) ```

We can then initialize and train Merlion’s DefaultDetector, which is an anomaly detection model that balances performance with efficiency. We also obtain its predictions on the test split.

python from merlion.models.defaults import DefaultDetectorConfig, DefaultDetector model = DefaultDetector(DefaultDetectorConfig()) model.train(train_data=train_data) test_pred = model.get_anomaly_label(time_series=test_data)

Next, we visualize the model's predictions.

python from merlion.plot import plot_anoms import matplotlib.pyplot as plt fig, ax = model.plot_anomaly(time_series=test_data) plot_anoms(ax=ax, anomaly_labels=test_labels) plt.show() anomaly figure

Finally, we can quantitatively evaluate the model. The precision and recall come from the fact that the model fired 3 alarms, with 2 true positives, 1 false negative, and 1 false positive. We also evaluate the mean time the model took to detect each anomaly that it correctly detected.

python from merlion.evaluate.anomaly import TSADMetric p = TSADMetric.Precision.value(ground_truth=test_labels, predict=test_pred) r = TSADMetric.Recall.value(ground_truth=test_labels, predict=test_pred) f1 = TSADMetric.F1.value(ground_truth=test_labels, predict=test_pred) mttd = TSADMetric.MeanTimeToDetect.value(ground_truth=test_labels, predict=test_pred) print(f"Precision: {p:.4f}, Recall: {r:.4f}, F1: {f1:.4f}\n" f"Mean Time To Detect: {mttd}") Precision: 0.6667, Recall: 0.6667, F1: 0.6667 Mean Time To Detect: 1 days 10:22:30

Forecasting

Here, we show the code to replicate the results from the forecasting dashboard above. We begin by importing Merlion’s TimeSeries class and the data loader for the M4 dataset. We can then divide a specific time series from this dataset into training and testing splits.

```python from merlion.utils import TimeSeries from ts_datasets.forecast import M4

Data loader returns pandas DataFrames, which we convert to Merlion TimeSeries

timeseries, metadata = M4(subset="Hourly")[0] traindata = TimeSeries.frompd(timeseries[metadata.trainval]) testdata = TimeSeries.frompd(time_series[~metadata.trainval]) ```

We can then initialize and train Merlion’s DefaultForecaster, which is an forecasting model that balances performance with efficiency. We also obtain its predictions on the test split.

python from merlion.models.defaults import DefaultForecasterConfig, DefaultForecaster model = DefaultForecaster(DefaultForecasterConfig()) model.train(train_data=train_data) test_pred, test_err = model.forecast(time_stamps=test_data.time_stamps)

Next, we visualize the model’s predictions.

python import matplotlib.pyplot as plt fig, ax = model.plot_forecast(time_series=test_data, plot_forecast_uncertainty=True) plt.show() forecast figure

Finally, we quantitatively evaluate the model. sMAPE measures the error of the prediction on a scale of 0 to 100 (lower is better), while MSIS evaluates the quality of the 95% confidence band on a scale of 0 to 100 (lower is better).

```python

Evaluate the model's predictions quantitatively

from scipy.stats import norm from merlion.evaluate.forecast import ForecastMetric

Compute the sMAPE of the predictions (0 to 100, smaller is better)

smape = ForecastMetric.sMAPE.value(groundtruth=testdata, predict=test_pred)

Compute the MSIS of the model's 95% confidence interval (0 to 100, smaller is better)

lb = TimeSeries.frompd(testpred.topd() + norm.ppf(0.025) * testerr.topd().values) ub = TimeSeries.frompd(testpred.topd() + norm.ppf(0.975) * testerr.topd().values) msis = ForecastMetric.MSIS.value(groundtruth=testdata, predict=testpred, insample=traindata, lb=lb, ub=ub) print(f"sMAPE: {smape:.4f}, MSIS: {msis:.4f}") sMAPE: 4.1944, MSIS: 18.9331 ```

Evaluation and Benchmarking

One of Merlion's key features is an evaluation pipeline that simulates the live deployment of a model on historical data. This enables you to compare models on the datasets relevant to them, under the conditions that they may encounter in a production environment. Our evaluation pipeline proceeds as follows: 1. Train an initial model on recent historical training data (designated as the training split of the time series) 1. At a regular interval (e.g. once per day), retrain the entire model on the most recent data. This can be either the entire history of the time series, or a more limited window (e.g. 4 weeks). 1. Obtain the model's predictions (anomaly scores or forecasts) for the time series values that occur between re-trainings. You may customize whether this should be done in batch (predicting all values at once), streaming (updating the model's internal state after each data point without fully re-training it), or some intermediate cadence. 1. Compare the model's predictions against the ground truth (labeled anomalies for anomaly detection, or the actual time series values for forecasting), and report quantitative evaluation metrics.

We provide scripts that allow you to use this pipeline to evaluate arbitrary models on arbitrary datasets. For example, invoking shell script python benchmark_anomaly.py --dataset NAB_realAWSCloudwatch --model IsolationForest --retrain_freq 1d will evaluate the anomaly detection performance of the IsolationForest (retrained once a day) on the "realAWSCloudwatch" subset of the NAB dataset. Similarly, invoking shell script python benchmark_forecast.py --dataset M4_Hourly --model ETS will evaluate the batch forecasting performance (i.e. no retraining) of ETS on the "Hourly" subset of the M4 dataset. You can find the results produced by running these scripts in the Experiments section of the technical report.

Technical Report and Citing Merlion

You can find more details in our technical report: https://arxiv.org/abs/2109.09265

If you're using Merlion in your research or applications, please cite using this BibTeX: @article{bhatnagar2021merlion, title={Merlion: A Machine Learning Library for Time Series}, author={Aadyot Bhatnagar and Paul Kassianik and Chenghao Liu and Tian Lan and Wenzhuo Yang and Rowan Cassius and Doyen Sahoo and Devansh Arpit and Sri Subramanian and Gerald Woo and Amrita Saha and Arun Kumar Jagota and Gokulakrishnan Gopalakrishnan and Manpreet Singh and K C Krithika and Sukumar Maddineni and Daeki Cho and Bo Zong and Yingbo Zhou and Caiming Xiong and Silvio Savarese and Steven Hoi and Huan Wang}, year={2021}, eprint={2109.09265}, archivePrefix={arXiv}, primaryClass={cs.LG} }

To Dos

We are striving to leverage the time-series modeling with GPUs to further improve the speed and throughput of Merlion. Stay tuned ...

Owner

  • Name: Salesforce
  • Login: salesforce
  • Kind: organization
  • Email: osscore@salesforce.com

Premier Open Source projects released and supported by Salesforce.

GitHub Events

Total
  • Issues event: 5
  • Watch event: 942
  • Issue comment event: 11
  • Pull request event: 2
  • Fork event: 43
Last Year
  • Issues event: 5
  • Watch event: 942
  • Issue comment event: 11
  • Pull request event: 2
  • Fork event: 43

Committers

Last synced: 9 months ago

All Time
  • Total Commits: 82
  • Total Committers: 17
  • Avg Commits per committer: 4.824
  • Development Distribution Score (DDS): 0.293
Past Year
  • Commits: 4
  • Committers: 3
  • Avg Commits per committer: 1.333
  • Development Distribution Score (DDS): 0.5
Top Committers
Name Email Commits
Aadyot Bhatnagar a****r@s****m 58
Paul Kassianik p****s 4
Ivan i****v@g****m 3
Chenghao Liu 7****9 2
Shiyu Wang 4****g 2
Tian Lan 3****1 2
Angela Tao a****3@g****m 1
Jon Wiggins 3****s 1
Rafael Leiniö r****r@g****m 1
Rohith_Papani 4****0 1
Ryosuke Horiuchi 3****i 1
Shrey s****d@r****m 1
Yang Wenzhuo 5****8 1
Yihao Feng 9****s 1
mattfernandez-salesforce 1****e 1
mr-price 4****e 1
svc-scm 4****m 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 68
  • Total pull requests: 60
  • Average time to close issues: about 1 month
  • Average time to close pull requests: 13 days
  • Total issue authors: 53
  • Total pull request authors: 17
  • Average comments per issue: 1.46
  • Average comments per pull request: 0.82
  • Merged pull requests: 52
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 7
  • Pull requests: 2
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Issue authors: 6
  • Pull request authors: 2
  • Average comments per issue: 0.29
  • Average comments per pull request: 0.0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • MBasalla (3)
  • sunxin000 (3)
  • bkowshik (2)
  • anton164 (2)
  • Sharaddition (2)
  • ravenrip (2)
  • nebiyebulan (2)
  • darinkist (2)
  • AtanasGruev (2)
  • GuidoBorrelli (2)
  • FlorinAndrei (2)
  • yangyang919 (2)
  • muazhari (2)
  • bayd (1)
  • varunsridhar1 (1)
Pull Request Authors
  • aadyotb (37)
  • shi-yu-wang (7)
  • IMRO832000 (4)
  • isenilov (3)
  • Emerald01 (3)
  • mr-price (2)
  • uchiiii (2)
  • anjanashankar9 (2)
  • jonwiggins (1)
  • rafaelleinio (1)
  • yihaocs (1)
  • Rajpratik71 (1)
  • cnll0075 (1)
  • chenghaoliu89 (1)
  • eltociear (1)
Top Labels
Issue Labels
Pull Request Labels
cla:signed (15) cla:missing (5)

Packages

  • Total packages: 5
  • Total downloads:
    • pypi 48,454 last-month
  • Total dependent packages: 4
    (may contain duplicates)
  • Total dependent repositories: 20
    (may contain duplicates)
  • Total versions: 72
  • Total maintainers: 3
pypi.org: salesforce-merlion

Merlion: A Machine Learning Framework for Time Series Intelligence

  • Versions: 20
  • Dependent Packages: 4
  • Dependent Repositories: 19
  • Downloads: 48,441 Last month
Rankings
Stargazers count: 1.3%
Dependent packages count: 1.6%
Average: 2.9%
Forks count: 3.2%
Dependent repos count: 3.4%
Downloads: 5.2%
Maintainers (3)
Last synced: 6 months ago
proxy.golang.org: github.com/salesforce/Merlion
  • Versions: 18
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Dependent packages count: 6.4%
Average: 6.6%
Dependent repos count: 6.8%
Last synced: 6 months ago
proxy.golang.org: github.com/salesforce/merlion
  • Versions: 18
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Dependent packages count: 6.4%
Average: 6.6%
Dependent repos count: 6.8%
Last synced: 6 months ago
pypi.org: sfdc-merlion

Merlion: A Machine Learning Framework for Time Series Intelligence

  • Versions: 1
  • Dependent Packages: 0
  • Dependent Repositories: 1
  • Downloads: 13 Last month
Rankings
Stargazers count: 1.3%
Forks count: 3.2%
Dependent packages count: 7.4%
Average: 21.7%
Dependent repos count: 22.2%
Downloads: 74.5%
Maintainers (1)
Last synced: 6 months ago
conda-forge.org: salesforce-merlion

Merlion is a Python library for time series intelligence. It features a unified interface for many commonly used models and datasets for anomaly detection and forecasting on both univariate and multivariate time series, along with standard pre-processing and post-processing layers. It has several modules to improve ease-of-use, including visualization, anomaly score calibration to improve interpetability, AutoML for hyperparameter tuning and model selection, and model ensembling. Merlion also provides a unique evaluation framework that simulates the live deployment and re-training of a model in production. This library aims to provide engineers and researchers a one-stop solution to rapidly develop models for their specific time series needs, and benchmark them across multiple time series datasets.

  • Versions: 15
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Stargazers count: 6.9%
Forks count: 10.5%
Average: 25.7%
Dependent repos count: 34.0%
Dependent packages count: 51.2%
Last synced: 6 months ago

Dependencies

.github/workflows/docs.yml actions
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
  • peaceiris/actions-gh-pages v3 composite
.github/workflows/publish.yml actions
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
  • pypa/gh-action-pypi-publish release/v1 composite
.github/workflows/tests.yml actions
  • actions/checkout v3 composite
  • actions/setup-java v3 composite
  • actions/setup-python v4 composite
  • emibcn/badge-action v1.2.1 composite
  • nick-fields/retry v2 composite
  • s0/git-publish-subdir-action v2.5.1 composite
docker/Dockerfile docker
  • python 3.9-slim build
docker/dashboard/Dockerfile docker
  • python 3.9-slim build
docker/spark-on-k8s/Dockerfile docker
  • gcr.io/spark-operator/spark-py v3.1.1 build
docs/requirements.txt pypi
  • GitPython *
  • beautifulsoup4 *
  • docutils ==0.16
  • ipykernel *
  • nbsphinx *
  • pandoc *
  • sphinx <6
  • sphinx_autodoc_typehints *
  • sphinx_rtd_theme *
setup.py pypi
  • GitPython *
  • cython *
  • dill *
  • lightgbm *
  • matplotlib *
  • numpy >=1.21
  • packaging *
  • pandas >=1.1.0
  • plotly >=4.13
  • prophet >=1.1
  • py4j *
  • scikit-learn >=0.22
  • scipy >=1.6.0
  • statsmodels >=0.12.2
  • tqdm *
ts_datasets/setup.py pypi
  • cython *