Contenuto principale

Generate Code for Time Series Anomaly Detection

This example shows how to generate mex code for deploying a trained anomaly detector.

Create and Train TSAD Anomaly Detector

For this example, create an anomaly detector based on the machine learning isolation forest detector with three channels.

detector = timeSeriesIforestAD(3);

Load training data that includes both normal data (for training) and abnormal data (for testing).

load sineWaveAnomalyData

Train the detector with the normal data and using the default model options. Then, save the detector in detector.mat.

detector = train(detector,sineWaveNormal);
save detector.mat detector

Initialize Code Generation Process

Configure the codegen configuration for mex code generation.

cfg = coder.config('mex');

Examine the attached entry-point function. This is the function from which you want to generate code that executes the same functions in a deployment scenario as the detector workflow within MATLAB®. This function works for both machine learning and most deep learning detectors.

type mTSADCodegen_Detect.m
function [result] = mTSADCodegen_Detect(matfile, data, varargin)
% Load the detector that is stored in the file "detector.mat"
s = coder.load(matfile);
detector = s.detector;
% Call the detect function to evaluate the current deployed data stream for anomalies and return the results in result. varargin contains the name-value arguments for detect.
result = detector.detect(data, varargin{:});

end

Generate Code for Deployed Anomaly Detection

Use the codegen command to generate code using your trained detector and your entry-point function.

In the command, change the setting of the Resolution name-value argument from its default value of "window" to "sample". Surround input arguments that have fixed values, such as detector.mat, with coder.Constant().

codegen mTSADCodegen_Detect -args {coder.Constant("detector.mat"),sineWaveAbnormal,coder.Constant("Resolution"),coder.Constant("sample")}
Code generation successful.

The message "Code generation successful" confirms that you generated valid mex code.

Validate Generated Mex Code

To validate the generated code, at the MATLAB command prompt, run the entry-point MATLAB function on the abnormal data.

detectionResults = mTSADCodegen_Detect("detector.mat",sineWaveAbnormal,Resolution="sample")
detectionResults=3×1 cell array
    1307×3 table
    1307×3 table
    1307×3 table

Then, run the generated MEX file on the same data and confirm that the results are the same.

detectionResultsMex = mTSADCodegen_Detect_mex("detector.mat",sineWaveAbnormal,Resolution="sample")
detectionResultsMex=3×1 cell array
    1307×3 table
    1307×3 table
    1307×3 table

Compare results for the two functions where there are label transitions from true to false

rows = 386:394;
detectionResults{1,1}(rows, ["Labels", "AnomalyScores", "StartIndices"])
ans=9×3 table
    false    0.4644    386
    false    0.4644    387
    false    0.4644    388
    false    0.4644    389
    false    0.4644    390
     true    0.5961    391
     true    0.5961    392
     true    0.5961    393
     true    0.5961    394

detectionResultsMex{1,1}(rows, ["Labels", "AnomalyScores", "StartIndices"])
ans=9×3 table
    false    0.4644    386
    false    0.4644    387
    false    0.4644    388
    false    0.4644    389
    false    0.4644    390
     true    0.5961    391
     true    0.5961    392
     true    0.5961    393
     true    0.5961    394

You can use a similar approach to modify the detection properties such as Threshold for an existing deployed detector by generating code for updateDetector.