merlion.models package

Broadly, Merlion contains two types of models: anomaly detection (merlion.models.anomaly) and forecasting (merlion.models.forecast). Note that there is a distinct subset of anomaly detection models that use forecasting models at their core (merlion.models.anomaly.forecast_based).

We implement an abstract ModelBase class which provides the following functionality for all models:

  1. model = ModelClass(config)

    • initialization with a model-specific config (which inherits from Config)

    • configs contain:

      • a (potentially trainable) data pre-processing transform from merlion.transform; note that model.transform is a property which refers to model.config.transform

      • model-specific hyperparameters

  2. model.save(dirname, save_config=None)

    • saves the model to the specified directory. The model’s configuration is saved to <dirname>/config.json, while the model’s binary data is (by default) saved in binary form to <dirname>/model.pkl. Note that if you edit the saved <dirname>/config.json on disk, the changes will be loaded when you call ModelClass.load(dirname)!

    • this method heavily exploits the fact that many objects in Merlion are JSON-serializable

  3. ModelClass.load(dirname, **kwargs)

    • this class method initializes an instance of ModelClass from the config file saved in <dirname>/config.json, (overriding any parameters of the config with kwargs where relevant), loads the remaining binary data into the model object, and returns the fully initialized model.

For users who aren’t familiar with the specific details of various models, we provide default models for anomaly detection and forecasting in merlion.models.defaults.

We also provide a ModelFactory which can be used to conveniently instantiate models from their name and a set of keyword arguments, or to load them directly from disk. For example, we may have the following workflow:

from merlion.models.factory import ModelFactory
from merlion.models.anomaly.windstats import WindStats, WindStatsConfig

# creates the same kind of model in 2 equivalent ways
model1a = WindStats(WindStatsConfig(wind_sz=60))
model1b = ModelFactory.create("WindStats", wind_sz=60)

# save the model & load it in 2 equivalent ways
model1a.save("tmp")
model2a = WindStats.load("tmp")
model2b = ModelFactory.load("tmp")

Finally, we support ensembles of models in merlion.models.ensemble.

factory

Contains the ModelFactory.

base

Contains the base classes for all models.

layers

Base class for layered models.

defaults

Default models for anomaly detection & forecasting that balance speed and performance.

anomaly

Contains all anomaly detection models.

anomaly.change_point

Contains all change point detection algorithms.

anomaly.forecast_based

Contains all forecaster-based anomaly detectors.

forecast

Contains all forecasting models.

ensemble

Ensembles of models and automated model selection.

automl

Contains all AutoML layers.

Subpackages

Submodules

merlion.models.factory module

Contains the ModelFactory.

class merlion.models.factory.ModelFactory

Bases: object

classmethod get_model_class(name)
Return type

Type[ModelBase]

classmethod create(name, return_unused_kwargs=False, **kwargs)
Return type

Union[ModelBase, Tuple[ModelBase, Dict]]

classmethod load(name, model_path, **kwargs)
Return type

ModelBase

classmethod load_bytes(obj, **kwargs)
Return type

ModelBase

merlion.models.base module

Contains the base classes for all models.

class merlion.models.base.Config(transform=None, **kwargs)

Bases: object

Abstract class which defines a model config.

Parameters

transform (Optional[TransformBase]) – Transformation to pre-process input time series.

filename = 'config.json'
transform: TransformBase = None
dim: Optional[int] = None
property base_model

The base model of a base model is itself.

to_dict(_skipped_keys=None)
Returns

dict with keyword arguments used to initialize the config class.

classmethod from_dict(config_dict, return_unused_kwargs=False, dim=None, **kwargs)

Constructs a Config from a Python dictionary of parameters.

Parameters
  • config_dict (Dict[str, Any]) – dict that will be used to instantiate this object.

  • return_unused_kwargs – whether to return any unused keyword args.

  • dim – the dimension of the time series. handled as a special case.

  • kwargs – any additional parameters to set (overriding config_dict).

Returns

Config object initialized from the dict.

get_unused_kwargs(**kwargs)
class merlion.models.base.NormalizingConfig(normalize=None, transform=None, **kwargs)

Bases: Config

Model config where the transform must return normalized values. Applies additional normalization after the initial data pre-processing transform.

Parameters
  • normalize (Optional[Rescale]) – Pre-trained normalization transformation (optional).

  • transform – Transformation to pre-process input time series.

property full_transform

Returns the full transform, including the pre-processing step, lags, and final mean/variance normalization.

property transform
class merlion.models.base.ModelBase(config)

Bases: object

Abstract base class for models.

filename = 'model.pkl'
config_class

alias of Config

train_data: Optional[TimeSeries] = None

The data used to train the model.

reset()

Resets the model’s internal state.

property dim
property transform
Returns

The data pre-processing transform to apply on any time series, before giving it to the model.

property timedelta
Returns

the gap (as a pandas.Timedelta or pandas.DateOffset) between data points in the training data

property last_train_time
Returns

the last time (as a pandas.Timestamp) that the model was trained on

train_pre_process(train_data, require_even_sampling, require_univariate)

Applies pre-processing steps common for training most models.

Parameters
  • train_data (TimeSeries) – the original time series of training data

  • require_even_sampling (bool) – whether the model assumes that training data is sampled at a fixed frequency

  • require_univariate (bool) – whether the model only works with univariate time series

Return type

TimeSeries

Returns

the training data, after any necessary pre-processing has been applied

transform_time_series(time_series, time_series_prev=None)

Applies the model’s pre-processing transform to time_series and time_series_prev.

Parameters
  • time_series (TimeSeries) – The time series

  • time_series_prev (Optional[TimeSeries]) – A time series of context, immediately preceding time_series. Optional.

Return type

Tuple[TimeSeries, Optional[TimeSeries]]

Returns

The transformed time_series.

abstract train(train_data, train_config=None)

Trains the model on the specified time series, optionally with some additional implementation-specific config options train_config.

Parameters
  • train_data (TimeSeries) – a TimeSeries to use as a training set

  • train_config – additional configurations (if needed)

save(dirname, **save_config)
Parameters
  • dirname (str) – directory to save the model & its config

  • save_config – additional configurations (if needed)

classmethod load(dirname, **kwargs)
Parameters
  • dirname (str) – directory to load model (and config) from

  • kwargs – config params to override manually

Returns

ModelBase object loaded from file

to_bytes(**save_config)

Converts the entire model state and configuration to a single byte object.

Returns

bytes object representing the model.

classmethod from_bytes(obj, **kwargs)

Creates a fully specified model from a byte object

Parameters

obj – byte object to convert into a model

Returns

ModelBase object loaded from obj

merlion.models.layers module

Base class for layered models. These are models which act as a wrapper around another model, often with additional functionality. This is the basis for default models and AutoML models.

class merlion.models.layers.LayeredModelConfig(model, model_kwargs=None, transform=None, **kwargs)

Bases: Config

Config object for a LayeredModel. See LayeredModel documentation for more details.

Parameters
  • model (Union[ModelBase, Dict]) – The model being wrapped, or a dict representing it.

  • model_kwargs – Keyword arguments used specifically to initialize the underlying model. Only used if model is a dict. Will override keys in the model dict if specified.

  • transform – Transformation to pre-process input time series.

  • kwargs – Any other keyword arguments (e.g. for initializing a base class). If model is a dict, we will also try to pass these arguments when creating the actual underlying model. However, they will not override arguments in either the model dict or model_kwargs dict.

property base_model

The base model at the heart of the full layered model.

to_dict(_skipped_keys=None)
Returns

dict with keyword arguments used to initialize the config class.

classmethod from_dict(config_dict, return_unused_kwargs=False, dim=None, **kwargs)

Constructs a Config from a Python dictionary of parameters.

Parameters
  • config_dict (Dict[str, Any]) – dict that will be used to instantiate this object.

  • return_unused_kwargs – whether to return any unused keyword args.

  • dim – the dimension of the time series. handled as a special case.

  • kwargs – any additional parameters to set (overriding config_dict).

Returns

Config object initialized from the dict.

get_unused_kwargs(**kwargs)
class merlion.models.layers.LayeredModel(config=None, model=None, **kwargs)

Bases: ModelBase

Abstract class implementing a model which wraps around another internal model.

The actual underlying model is stored in model.config.model, and model.model is a property which references this. This is to allow the model to retain the initializer LayeredModel(config), and to ensure that various attributes do not become de-synchronized (e.g. if we were to store config.model_config and model.model separately).

We define the base model as the non-layered model at the base of the overall model hierarchy.

The layered model is allowed to access any callable attribute of the base model, e.g. model.set_seasonality(...) resolves to``model.base_model.set_seasonality(…)`` for a SeasonalityModel. If the base model is a forecaster, the layered model will automatically inherit from ForecasterBase; similarly for DetectorBase or ForecastingDetectorBase. The abstract methods (forecast and get_anomaly_score) are overridden to call the underlying model.

If the base model is a forecaster, the top-level config model.config does not duplicate attributes of the underlying forecaster config (e.g. max_forecast_steps or target_seq_index). Instead, model.config.max_forecast_steps will resolve to model.config.base_model.max_forecast_steps. As a result, you will only need to specify this parameter once. The same holds true for DetectorConfig attributes (e.g. threshold or calibrator) when the base model is an anomaly detector.

Note

For the time being, every layer of the model is allowed to have its own transform.

config_class

alias of LayeredModelConfig

require_even_sampling = False
require_univariate = False
property model
property base_model
property train_data
reset()

Resets the model’s internal state.

train(train_data, *args, **kwargs)

Trains the model on the specified time series, optionally with some additional implementation-specific config options train_config.

Parameters
  • train_data (TimeSeries) – a TimeSeries to use as a training set

  • train_config – additional configurations (if needed)

class merlion.models.layers.LayeredDetector(config=None, model=None, **kwargs)

Bases: LayeredModel, DetectorBase

Base class for a layered anomaly detector. Only to be used as a subclass.

Parameters

config (Optional[LayeredModelConfig]) – model configuration

get_anomaly_score(time_series, time_series_prev=None)

Returns the model’s predicted sequence of anomaly scores.

Parameters
  • time_series (TimeSeries) – the TimeSeries we wish to predict anomaly scores for.

  • time_series_prev (Optional[TimeSeries]) – a TimeSeries immediately preceding time_series. If given, we use it to initialize the time series anomaly detection model. Otherwise, we assume that time_series immediately follows the training data.

Return type

TimeSeries

Returns

a univariate TimeSeries of anomaly scores

class merlion.models.layers.LayeredForecaster(config=None, model=None, **kwargs)

Bases: LayeredModel, ForecasterBase

Base class for a layered forecaster. Only to be used as a subclass.

forecast(time_stamps, time_series_prev=None, *args, **kwargs)

Returns the model’s forecast on the timestamps given. Note that if self.transform is specified in the config, the forecast is a forecast of transformed values! It is up to you to manually invert the transform if desired.

Parameters
  • time_stamps – Either a list of timestamps we wish to forecast for, or the number of steps (int) we wish to forecast for.

  • time_series_prev (Optional[TimeSeries]) – a list of (timestamp, value) pairs immediately preceding time_series. If given, we use it to initialize the time series model. Otherwise, we assume that time_series immediately follows the training data.

  • return_iqr – whether to return the inter-quartile range for the forecast. Note that not all models support this option.

  • return_prev – whether to return the forecast for time_series_prev (and its stderr or IQR if relevant), in addition to the forecast for time_stamps. Only used if time_series_prev is provided.

Returns

(forecast, forecast_stderr) if return_iqr is false, (forecast, forecast_lb, forecast_ub) otherwise.

  • forecast: the forecast for the timestamps given

  • forecast_stderr: the standard error of each forecast value.

    May be None.

  • forecast_lb: 25th percentile of forecast values for each timestamp

  • forecast_ub: 75th percentile of forecast values for each timestamp

class merlion.models.layers.LayeredForecastingDetector(config=None, model=None, **kwargs)

Bases: LayeredForecaster, LayeredDetector, ForecastingDetectorBase

Base class for a layered forecasting detector. Only to be used as a subclass.

Parameters

config (Optional[LayeredModelConfig]) – model configuration

merlion.models.defaults module

Default models for anomaly detection & forecasting that balance speed and performance.

class merlion.models.defaults.DefaultDetectorConfig(model=None, granularity=None, n_threads=1, model_kwargs=None, transform=None, **kwargs)

Bases: LayeredModelConfig

Config object for default anomaly detection model.

Parameters
  • model – The model being wrapped, or a dict representing it.

  • granularity – the granularity at which the input time series should be sampled, e.g. “5min”, “1h”, “1d”, etc.

  • n_threads (int) – the number of parallel threads to use for relevant models

  • model_kwargs – Keyword arguments used specifically to initialize the underlying model. Only used if model is a dict. Will override keys in the model dict if specified.

  • transform – Transformation to pre-process input time series.

  • kwargs – Any other keyword arguments (e.g. for initializing a base class). If model is a dict, we will also try to pass these arguments when creating the actual underlying model. However, they will not override arguments in either the model dict or model_kwargs dict.

class merlion.models.defaults.DefaultDetector(config=None, model=None, **kwargs)

Bases: LayeredDetector

Default anomaly detection model that balances efficiency with performance.

Parameters

config (Optional[LayeredModelConfig]) – model configuration

config_class

alias of DefaultDetectorConfig

property granularity
train(train_data, anomaly_labels=None, train_config=None, post_rule_train_config=None)

Trains the model on the specified time series, optionally with some additional implementation-specific config options train_config.

Parameters
  • train_data (TimeSeries) – a TimeSeries to use as a training set

  • train_config – additional configurations (if needed)

Return type

TimeSeries

class merlion.models.defaults.DefaultForecasterConfig(model=None, max_forecast_steps=100, target_seq_index=None, granularity=None, model_kwargs=None, transform: TransformBase = None, **kwargs)

Bases: LayeredModelConfig

Config object for default forecasting model.

Parameters
  • model – The model being wrapped, or a dict representing it.

  • max_forecast_steps – Max # of steps we would like to forecast for. Required for some models like MSES and LGBMForecaster.

  • target_seq_index – The index of the univariate (amongst all univariates in a general multivariate time series) whose value we would like to forecast.

  • granularity – the granularity at which the input time series should be sampled, e.g. “5min”, “1h”, “1d”, etc.

  • model_kwargs – Keyword arguments used specifically to initialize the underlying model. Only used if model is a dict. Will override keys in the model dict if specified.

  • transform – Transformation to pre-process input time series.

  • kwargs – Any other keyword arguments (e.g. for initializing a base class). If model is a dict, we will also try to pass these arguments when creating the actual underlying model. However, they will not override arguments in either the model dict or model_kwargs dict.

class merlion.models.defaults.DefaultForecaster(config=None, model=None, **kwargs)

Bases: LayeredForecaster

Default forecasting model that balances efficiency with performance.

config_class

alias of DefaultForecasterConfig

property granularity
train(train_data, train_config=None)

Trains the model on the specified time series, optionally with some additional implementation-specific config options train_config.

Parameters
  • train_data (TimeSeries) – a TimeSeries to use as a training set

  • train_config – additional configurations (if needed)

Return type

Tuple[TimeSeries, Optional[TimeSeries]]