# deepSignalAnomalyDetectorLSTMForecaster

## Description

The `deepSignalAnomalyDetectorLSTMForecaster`

object uses a long short-term memory (LSTM)
forecaster model to detect signal anomalies.

## Creation

Create a `deepSignalAnomalyDetectorLSTMForecaster`

object using `deepSignalAnomalyDetector`

and specifying `"lstmforecaster"`

as
the model type.

## Properties

### General

`IsTrained`

— Training status

`0`

(`false`

) | `1`

(`true`

)

This property is read-only.

Training status, returned as `0`

(`false`

) or
`1`

(`true`

). Once you train the detector,
`IsTrained`

is equal to `1`

.

**Data Types: **`logical`

`NumChannels`

— Number of channels

positive integer

This property is read-only.

Number of channels in each input signal, returned as a positive integer.

**Data Types: **`single`

| `double`

| `int8`

| `int16`

| `int32`

| `int64`

| `uint8`

| `uint16`

| `uint32`

| `uint64`

### Model

`ModelType`

— Type of deep learning model

`"lstmforecaster"`

This property is read-only.

Type of deep learning model implemented by the detector, returned as
`"lstmforecaster"`

.

`ForecastSteps`

— Number of steps forward for forecasting

`1`

(default) | positive integer scalar

This property is read-only.

Number of steps forward for forecasting, returned as a positive integer scalar.

**Data Types: **`single`

| `double`

| `int8`

| `int16`

| `int32`

| `int64`

| `uint8`

| `uint16`

| `uint32`

| `uint64`

`NumHiddenUnits`

— Number of hidden units of LSTM layers

`16`

(default) | positive integer scalar | vector of positive integers

This property is read-only.

Number of hidden units of LSTM layers, returned as a positive integer scalar or a
vector of positive integers. The *i*th element of the vector sets the
number of hidden units in the *i*th layer.

**Data Types: **`single`

| `double`

| `int8`

| `int16`

| `int32`

| `int64`

| `uint8`

| `uint16`

| `uint32`

| `uint64`

### Window

`WindowLength`

— Window length

`1`

(default) | positive integer | `"fullSignal"`

This property is read-only.

Window length of each signal segment, returned as a positive integer or as
`"fullSignal"`

.

If

`WindowLength`

is an integer, the detector divides each input signal into segments. The length of each segment is equal to the`WindowLength`

value in samples.If

`WindowLength`

is`"fullSignal"`

, the detector treats each input signal as a single segment.

Use `updateDetector`

to modify this and other window properties.

**Data Types: **`single`

| `double`

| `int8`

| `int16`

| `int32`

| `int64`

| `uint8`

| `uint16`

| `uint32`

| `uint64`

| `char`

| `string`

`OverlapLength`

— Number of overlapped samples

`"auto"`

(default) | positive integer

This property is read-only.

Number of overlapped samples between window segments, returned as a positive integer
or as `"auto"`

.

If

`OverlapLength`

is a positive integer, the detector sets the number of overlapped samples equal to the`OverlapLength`

value.If

`OverlapLength`

is`"auto"`

, the detector sets the number of overlapped samples equal to`WindowLength`

– 1.

**Data Types: **`single`

| `double`

| `int8`

| `int16`

| `int32`

| `int64`

| `uint8`

| `uint16`

| `uint32`

| `uint64`

| `char`

| `string`

`WindowLossAggregation`

— Method to aggregate sample loss

`"mean"`

(default) | `"max"`

| `"min"`

| `"median"`

This property is read-only.

Method to aggregate sample loss within each window segment, returned as one of these:

`"max"`

— Compute the aggregated window loss as the maximum value of all the sample losses within the window.`"mean"`

— Compute the aggregated window loss as the mean value of all the sample losses within the window.`"median"`

— Compute the aggregated window loss as the median value of all the sample losses within the window.`"min"`

— Compute the aggregated window loss as the minimum value of all the sample losses within the window.

**Data Types: **`char`

| `string`

### Threshold

`ThresholdMethod`

— Method to compute detection threshold

`"contaminationFraction"`

(default) | `"max"`

| `"median"`

| `"mean"`

| `"manual"`

| `"customFunction"`

This property is read-only.

Method to compute the detection threshold, returned as one of these:

`"contaminationFraction"`

— Value corresponding to the detection of anomalies within a specified fraction of windows. The fraction value is specified by`ThresholdParameter`

.`"max"`

— Maximum window loss measured over the entire training data set and multiplied by`ThresholdParameter`

.`"median"`

— Median window loss measured over the entire training data set and multiplied by`ThresholdParameter`

.`"mean"`

— Mean window loss measured over the entire training data set and multiplied by`ThresholdParameter`

.`"manual"`

— Manual detection threshold value based on`Threshold`

.`"customFunction"`

— Custom detection threshold value based on`ThresholdFunction`

.

Use `updateDetector`

to modify this and other threshold properties.

**Data Types: **`char`

| `string`

`ThresholdParameter`

— Detection threshold

real scalar

This property is read-only.

Detection threshold, returned as a nonnegative scalar when you set
`ThresholdMethod`

to `"contaminationFraction"`

,
and as positive scalar when you set `ThresholdMethod`

to
`"max"`

, `"median"`

, or
`"mean"`

.

**Data Types: **`single`

| `double`

| `int8`

| `int16`

| `int32`

| `int64`

| `uint8`

| `uint16`

| `uint32`

| `uint64`

`Threshold`

— Manual detection threshold

positive scalar

This property is read-only.

Manual detection threshold, retuned as a positive scalar. This property applies only when you
set `ThresholdMethod`

to `"manual"`

.

**Data Types: **`single`

| `double`

| `int8`

| `int16`

| `int32`

| `int64`

| `uint8`

| `uint16`

| `uint32`

| `uint64`

`ThresholdFunction`

— Function to compute custom detection threshold

function handle

This property is read-only.

Function to compute custom detection threshold, returned as a function handle. This property
applies only when you set `ThresholdMethod`

to
`"customFunction"`

.

**Data Types: **`function_handle`

## Object Functions

`detect` | Detect anomalies in signals |

`getModel` | Get underlying neural network model of signal anomaly detector |

`plotAnomalies` | Plot signal anomalies |

`plotLoss` | Plot window reconstruction loss |

`plotLossDistribution` | Plot CDF and histogram of aggregated window loss distribution |

`resetState` | Reset model internal states |

`saveModel` | Save detector network and parameters |

`trainDetector` | Train signal anomaly detector |

`updateDetector` | Update settings of trained detector and recompute detection threshold |

## Examples

### Detect Anomalies in Streaming Sinusoids

Load the file `sineWaveAnomalyData.mat`

, which contains two sets of synthetic three-channel sinusoidal signals.

`sineWaveNormal`

contains the 10 sinusoids used to train the convolutional anomaly detector. Each signal has a series of small-amplitude impact-like imperfections but otherwise has stable amplitude and frequency.`sineWaveAbnormal`

contains three signals of similar length and amplitude to the training data. One of the signals has an abrupt, finite-time change in frequency. Another signal has a finite-duration amplitude change in one of its channels. A third has random spikes in each channel.

Plot three normal signals and the three signals with anomalies.

load sineWaveAnomalyData tiledlayout(3,2,TileSpacing="compact",Padding="compact") rnd = randperm(length(sineWaveNormal)); for kj = 1:length(sineWaveAbnormal) nexttile plot(sineWaveNormal{rnd(kj)}) title("Normal Signal") nexttile plot(sineWaveAbnormal{kj}) title("Signal with Anomalies") end

Create a long short-term memory (LSTM) forecaster object to detect the anomalies in the abnormal signals. Specify a window length of 10 samples.

`D = deepSignalAnomalyDetector(3,"lstmforecaster",windowLength=10);`

Train the forecaster using the anomaly-free sinusoids. Use the training options for the adaptive moment estimation (Adam) optimizer and specify a maximum number of 100 epochs. For more information, see `trainingOptions`

(Deep Learning Toolbox).

opts = trainingOptions("adam",MaxEpochs=100,ExecutionEnvironment="cpu"); trainDetector(D,sineWaveNormal,opts)

Iteration Epoch TimeElapsed LearnRate TrainingLoss _________ _____ ___________ _________ ____________ 1 1 00:00:01 0.001 0.6369 50 50 00:00:08 0.001 0.19706 100 100 00:00:17 0.001 0.064225 Training stopped: Max epochs completed Computing threshold... Threshold computation completed.

Use the trained detector to find the anomalies in the first signal. Reset the state of the detector. Stream the data one sample at a time and have the detector keep its state after each reading. Compute the reconstruction loss for each one-sample frame. Categorize signal regions where the loss exceeds a specified threshold as anomalous.

resetState(D) sg = sineWaveAbnormal{1}; anoms = NaN(size(sg)); losss = zeros(size(sg)); for kj = 1:length(sg) frame = sg(kj,:); [lb,lo] = detect(D,frame, ... KeepState=true,ExecutionEnvironment="cpu"); anoms(kj) = lb; losss(kj) = lo; end

Plot the anomalous signal, the reconstruction loss, and the categorical array that declares each sample of the signal as being anomalous or not.

figure tiledlayout("vertical") nexttile plot(sg) nexttile plot(losss) nexttile stem(anoms,".")

Reset the state of the detector. Find the anomalies in the third signal. Plot the anomalous signal, the reconstruction loss, and the categorical array that declares each sample of the signal as being anomalous or not.

resetState(D) sg = sineWaveAbnormal{3}; anoms = NaN(size(sg)); losss = zeros(size(sg)); for kj = 1:length(sg) frame = sg(kj,:); [lb,lo] = detect(D,frame, ... KeepState=true,ExecutionEnvironment="cpu"); anoms(kj) = lb; losss(kj) = lo; end figure tiledlayout("vertical") nexttile plot(sg) nexttile plot(losss) nexttile stem(anoms,".")

## Extended Capabilities

### GPU Arrays

Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.

Usage notes and limitations:

The

`ExecutionEnvironment`

option must be`"gpu"`

or`"auto"`

when the input data is:A

`gpuArray`

A cell array containing

`gpuArray`

objectsA datastore that outputs cell arrays containing

`gpuArray`

objects

For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).

## Version History

**Introduced in R2024a**

## See Also

### Functions

### Objects

### Topics

- Detect Anomalies in Signals Using deepSignalAnomalyDetector
- Detect Anomalies in Machinery Using LSTM Autoencoder
- Detect Anomalies in ECG Data Using Wavelet Scattering and LSTM Autoencoder in Simulink
- Anomaly Detection in Industrial Machinery Using Three-Axis Vibration Data (Predictive Maintenance Toolbox)

## MATLAB Command

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

## How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

### Americas

- América Latina (Español)
- Canada (English)
- United States (English)

### Europe

- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)

- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)