Main Content

Code Generation for a Deep Learning Simulink Model to Classify ECG Signals

This example demonstrates how you can use powerful signal processing techniques and Convolutional Neural Networks together to classify ECG signals. We will also showcase how CUDA® code can be generated from the Simulink® model. This example uses the pretrained CNN network from theClassify Time Series Using Wavelet Analysis and Deep Learningexample of the Wavelet Toolbox™ to classify ECG signals based on images from the CWT of the time series data. For information on training, seeClassify Time Series Using Wavelet Analysis and Deep Learning(Wavelet Toolbox).

For a video demonstration on how to perform software-in-the-loop (SIL), processor-in-the-loop (PIL) simulation, and deploying this example to NVIDIA Jetson® board, see//www.tatmou.com/videos/deep-learning-in-simulink-for-nvidia-gpus-classification-of-ecg-signals-1621401016961.html.

This example illustrates the following concepts:

  • Model the classification application in Simulink. UseMATLAB Functionblocks to perform preprocessing and wavelet transforms of the ECG data. Use theImage Classifierblock from the Deep Learning Toolbox™ for loading the pretrained network and performing the classification of the ECG data.

  • Configure the model for code generation.

  • Generate a CUDA executable for the Simulink model.

Third-Party Prerequisites

Verify GPU Environment

To verify that the compilers and libraries necessary for running this example are set up correctly, use thecoder.checkGpuInstallfunction.

envCfg = coder.gpuEnvConfig('host'); envCfg.DeepLibTarget ='cudnn'; envCfg.DeepCodegen = 1; envCfg.Quiet = 1; coder.checkGpuInstall(envCfg);

ECG Data Description

This example uses ECG data fromPhysioNetdatabase. It contains data from three groups of people:

  1. Persons with cardiac arrhythmia (ARR)

  2. Persons with congestive heart failure (CHF)

  3. 人与正常窦性节律(NSR)

It includes 96 recordings from persons with ARR, 30 recordings from persons with CHF, and 36 recordings from persons with NSR. Theecg_signalsMAT-file contains the test ECG data in time series format. The image classifier in this example distinguishes between ARR, CHF, and NSR.

Algorithmic Workflow

The block diagram for the algorithmic workflow of the Simulink model is shown.

ECG Deep Learning Simulink Model

The Simulink model for classifying the ECG signals is shown. When the model runs, theVideo Viewerblock displays the classified ECG signal.

open_system('ecg_dl_cwt');

ECG Preprocessing Subsystem

TheECG Preprocessingsubsystem contains aMATLAB Functionblock that performs CWT to obtain scalogram of the ECG signal and then processes the scalogram to obtain an image and anImage Classifierblock that loads the pretrained network fromtrainedNet.matand performs prediction for image classification based on SqueezeNet deep learning CNN.

open_system('ecg_dl_cwt/ECG Preprocessing');

TheScalogramFromECGfunction block defines a function calledecg_to_scalogramthat:

  • Uses 65536 samples of double-precision ECG data as input.

  • Create time frequency representation from the ECG data by applying Wavelet transform.

  • Obtain scalogram from the wavelet coefficients.

  • Convert the scalogram to image of size (227x227x3).

The function signature ofecg_to_scalogramis shown.

typeecg_to_scalogram
function ecg_image = ecg_to_scalogram(ecg_signal) % Copyright 2020 The MathWorks, Inc. persistent jetdata; if(isempty(jetdata)) jetdata = ecgColorMap(128,'single'); end % Obtain wavelet coefficients from ECG signal cfs = cwt_ecg(ecg_signal); % Obtain scalogram from wavelet coefficients image = ind2rgb(im2uint8(rescale(cfs)),jetdata); ecg_image = im2uint8(imresize(image,[227,227])); end

ECG Postprocessing

TheECG PostprocessingMATLAB function block defines thelabel_prob_imagefunction that finds the label for the scalogram image based on the highest score from the scores outputed by the image classifier. It outputs the scalogram image with the label and confidence printed on it.

typelabel_prob_image
function final_image = label_prob_image(ecg_image, scores, labels) % Copyright 2020-2021 The MathWorks, Inc. scores = double(scores); % Obtain maximum confidence [prob,index] = max(scores); confidence = prob*100; % Obtain label corresponding to maximum confidence label = erase(char(labels(index)),'_label'); text = cell(2,1); text{1} = ['Classification: ' label]; text{2} = ['Confidence: ' sprintf('%0.2f',confidence) '%']; position = [135 20 0 0; 130 40 0 0]; final_image = insertObjectAnnotation(ecg_image,'rectangle',position,... text,'TextBoxOpacity',0.9,'FontSize',9); end

Run the Simulation

Open Configuration Parameters dialog box.

InSimulation Targetpane, selectGPU acceleration. In theDeep Learninggroup, select the target library ascuDNN.

To verify the algorithm and display the labels and confidence score of the test ECG signal loaded in the workspace, run the simulation.

set_param('ecg_dl_cwt',“SimulationMode','Normal'); sim('ecg_dl_cwt');

Generate and Build the Simulink Model

InCode Generationpane, select theLanguageasC++and enableGenerate GPU code.

OpenCode Generation > GPU Codepane. In the subcategoryLibraries, enablecuBLAS,cuSOLVERandcuFFT.

Generate and build the Simulink model on the host GPU by using theslbuildcommand. The code generator places the files in abuild folder, a subfolder namedecg_dl_cwt_ert_rtwunder your current working folder.

status = evalc("slbuild('ecg_dl_cwt')");

Generated CUDA® Code

The subfolder namedecg_dl_cwt_ert_rtwcontains the generated C++ codes corresponding to the different blocks in the Simulink model and the specific operations being performed in those blocks. For example, the filetrainedNet0_ecg_dl_cwt0.hcontains the C++ class which contains certain attributes such asnumLayersand member functions such asgetBatchSize(),predict(). This class represents the pretrainedSqueezeNetwhich has been loaded in the Simulink model.

Cleanup

Close the Simulink model.

close_system('ecg_dl_cwt/ECG Preprocessing'); close_system('ecg_dl_cwt');

See Also

Functions

Related Topics