Main Content

deepSignalAnomalyDetectorLSTMForecaster

Detect signal anomalies using LSTM forecaster

Since R2024a

    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

    expand all

    General

    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

    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

    This property is read-only.

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

    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

    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 ith element of the vector sets the number of hidden units in the ith layer.

    Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    Window

    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

    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

    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

    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

    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

    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

    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

    detectDetect anomalies in signals
    getModelGet underlying neural network model of signal anomaly detector
    plotAnomaliesPlot signal anomalies
    plotLossPlot window reconstruction loss
    plotLossDistributionPlot CDF and histogram of aggregated window loss distribution
    resetStateReset model internal states
    saveModelSave detector network and parameters
    trainDetectorTrain signal anomaly detector
    updateDetectorUpdate settings of trained detector and recompute detection threshold

    Examples

    collapse all

    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

    Version History

    Introduced in R2024a