speech command recognition code generation on raspberry pi -凯发k8网页登录
this example shows how to deploy feature extraction and a convolutional neural network (cnn) for speech command recognition to raspberry pi™. to generate the feature extraction and network code, you use matlab coder™, matlab® support package for raspberry pi hardware, and the arm® compute library. in this example, the generated code is an executable on your raspberry pi, which is called by a matlab script that displays the predicted speech command along with the signal and auditory spectrogram. interaction between the matlab script and the executable on your raspberry pi is handled using the user datagram protocol (udp). for details about audio preprocessing and network training, see .
prerequisites
matlab coder interface for deep learning libraries
arm processor that supports the neon extension
arm compute library version 20.02.1 (on the target arm hardware)
environment variables for the compilers and libraries
for supported versions of libraries and for information about setting up environment variables, see (matlab coder).
streaming demonstration in matlab
use the same parameters for the feature extraction pipeline and classification as developed in .
define the same sample rate the network was trained on (16 khz). define the classification rate and the number of audio samples input per frame. the feature input to the network is a bark spectrogram that corresponds to 1 second of audio data. the bark spectrogram is calculated for 25 ms windows with 10 ms hops. calculate the number of individual spectrums in each spectrogram.
fs = 16000; classificationrate = 20; samplespercapture = fs/classificationrate; segmentduration = 1; segmentsamples = round(segmentduration*fs); frameduration = 0.025; framesamples = round(frameduration*fs); hopduration = 0.010; hopsamples = round(hopduration*fs); numspectrumperspectrogram = floor((segmentsamples-framesamples)/hopsamples) 1;
create an audiofeatureextractor
object to extract 50-band bark spectrograms without window normalization. calculate the number of elements in each spectrogram.
afe = audiofeatureextractor( ... 'samplerate',fs, ... 'fftlength',512, ... 'window',hann(framesamples,'periodic'), ... 'overlaplength',framesamples - hopsamples, ... 'barkspectrum',true); numbands = 50; setextractorparameters(afe,'barkspectrum','numbands',numbands,'windownormalization',false); numelementsperspectrogram = numspectrumperspectrogram*numbands;
load the pretrained cnn and labels.
load('commandnet.mat') labels = trainednet.layers(end).classes; numlabels = numel(labels); backgroundidx = find(labels == 'background');
define buffers and decision thresholds to post process network predictions.
probbuffer = single(zeros([numlabels,classificationrate/2])); ybuffer = single(numlabels * ones(1, classificationrate/2)); countthreshold = ceil(classificationrate*0.2); probthreshold = single(0.7);
create an object to read audio from your device. create a object to buffer the audio into chunks.
adr = audiodevicereader('samplerate',fs,'samplesperframe',samplespercapture,'outputdatatype','single'); audiobuffer = dsp.asyncbuffer(fs);
create a object and a object to display the results.
matrixviewer = dsp.matrixviewer("colorbarlabel","power per band (db/band)",... "xlabel","frames",... "ylabel","bark bands", ... "position",[400 100 600 250], ... "colorlimits",[-4 2.6445], ... "axisorigin","lower left corner", ... "name","speech command recognition using deep learning"); timescope = timescope("samplerate",fs, ... "ylimits",[-1 1], ... "position",[400 380 600 250], ... "name","speech command recognition using deep learning", ... "timespansource","property", ... "timespan",1, ... "bufferlength",fs, ... "ylabel","amplitude", ... "showgrid",true);
show the time scope and matrix viewer. detect commands as long as both the time scope and matrix viewer are open or until the time limit is reached. to stop the live detection before the time limit is reached, close the time scope window or matrix viewer window.
show(timescope) show(matrixviewer) timelimit = 10; tic while isvisible(timescope) && isvisible(matrixviewer) && toc < timelimit % capture audio x = adr(); write(audiobuffer,x); y = read(audiobuffer,fs,fs-samplespercapture); % compute auditory features features = extract(afe,y); auditoryfeatures = log10(features 1e-6); % perform prediction probs = predict(trainednet, auditoryfeatures); [~, ypredicted] = max(probs); % perform statistical post processing ybuffer = [ybuffer(2:end),ypredicted]; probbuffer = [probbuffer(:,2:end),probs(:)]; [ymodeidx, count] = mode(ybuffer); maxprob = max(probbuffer(ymodeidx,:)); if ymodeidx == single(backgroundidx) || single(count) < countthreshold || maxprob < probthreshold speechcommandidx = backgroundidx; else speechcommandidx = ymodeidx; end % update plots matrixviewer(auditoryfeatures'); timescope(x); if (speechcommandidx == backgroundidx) timescope.title = ' '; else timescope.title = char(labels(speechcommandidx)); end drawnow limitrate end
hide the scopes.
hide(matrixviewer) hide(timescope)
prepare matlab code for deployment
to create a function to perform feature extraction compatible with code generation, call on the audiofeatureextractor
object. the generatematlabfunction
object function creates a standalone function that performs equivalent feature extraction and is compatible with code generation.
generatematlabfunction(afe,'extractspeechfeatures')
the supporting function encapsulates the feature extraction and network prediction process demonstrated previously. so that the feature extraction is compatible with code generation, feature extraction is handled by the generated extractspeechfeatures
function. so that the network is compatible with code generation, the supporting function uses the (matlab coder) function to load the network. the supporting function uses a system object to send the auditory spectrogram and the index corresponding to the predicted speech command from raspberry pi to matlab. the supporting function uses the system object to receive the audio captured by your microphone in matlab.
generate executable on raspberry pi
replace the hostipaddress
with your machine's address. your raspberry pi sends auditory spectrograms and the predicted speech command to this ip address.
hostipaddress = coder.constant('172.18.230.30');
create a code generation configuration object to generate an executable program. specify the target language as c .
cfg = coder.config('exe'); cfg.targetlang = 'c ';
create a configuration object for deep learning code generation with the arm compute library that is on your raspberry pi. specify the architecture of the raspberry pi and attach the deep learning configuration object to the code generation configuration object.
dlcfg = coder.deeplearningconfig('arm-compute'); dlcfg.armarchitecture = 'armv7'; dlcfg.armcomputeversion = '20.02.1'; cfg.deeplearningconfig = dlcfg;
use the raspberry pi support package function, raspi
, to create a connection to your raspberry pi. in the following code, replace:
raspiname
with the name of your raspberry pipi with your user name
password
with your password
r = raspi('raspiname','pi','password');
create a (matlab coder) object for raspberry pi and attach it to the code generation configuration object.
hw = coder.hardware('raspberry pi');
cfg.hardware = hw;
specify the build folder on the raspberry pi.
builddir = '~/remotebuilddir';
cfg.hardware.builddir = builddir;
use an auto generated c main file for the generation of a standalone executable.
cfg.generateexamplemain = 'generatecodeandcompile';
call codegen
(matlab coder) to generate c code and the executable on your raspberry pi. by default, the raspberry pi application name is the same as the matlab function.
codegen -config cfg helperspeechcommandrecognitionraspi -args {hostipaddress} -report -v
deploying code. this may take a few minutes. ### compiling function(s) helperspeechcommandrecognitionraspi ... ------------------------------------------------------------------------ location of the generated elf : /home/pi/remotebuilddir/matlab_ws/r2022a/w/ex/examplemanager/sporwal.bdoc22a.j1844576/deeplearning_shared-ex00376115 ### using toolchain: gnu gcc embedded linux ### 'w:\ex\examplemanager\sporwal.bdoc22a.j1844576\deeplearning_shared-ex00376115\codegen\exe\helperspeechcommandrecognitionraspi\helperspeechcommandrecognitionraspi_rtw.mk' is up to date ### building 'helperspeechcommandrecognitionraspi': make -j$(($(nproc) 1)) -otarget -f helperspeechcommandrecognitionraspi_rtw.mk all ------------------------------------------------------------------------ ### generating compilation report ... warning: function 'helperspeechcommandrecognitionraspi' does not terminate due to an infinite loop. warning in ==> helperspeechcommandrecognitionraspi line: 86 column: 1 code generation successful (with warnings): view report
initialize application on raspberry pi
create a command to open the helperspeechcommandraspi
application on raspberry pi
. use to send the command to your raspberry pi.
applicationname = 'helperspeechcommandrecognitionraspi'; applicationdirpaths = raspi.utils.getremotebuilddirectory('applicationname',applicationname); targetdirpath = applicationdirpaths{1}.directory; exename = strcat(applicationname,'.elf'); command = ['cd ' targetdirpath '; ./' exename ' &> 1 &']; system(r,command);
create a system object to send audio captured in matlab to your raspberry pi. update the targetipaddress
for your raspberry pi. raspberry pi receives the captured audio from the same port using the system object.
targetipaddress = '172.18.231.92'; udpsend = dsp.udpsender('remoteipport',26000,'remoteipaddress',targetipaddress);
create a system object to receive auditory features and the predicted speech command index from your raspberry pi. each udp packet received from the raspberry pi consists of auditory features in column-major order followed by the predicted speech command index. the maximum message length for the dsp.udpreceiver
object is 65507 bytes. calculate the buffer size to accommodate the maximum number of udp packets.
sizeoffloatinbytes = 4; maxudpmessagelength = floor(65507/sizeoffloatinbytes); samplesperpacket = 1 numelementsperspectrogram; numpackets = floor(maxudpmessagelength/samplesperpacket); buffersize = numpackets*samplesperpacket*sizeoffloatinbytes; udpreceive = dsp.udpreceiver("localipport",21000, ... "messagedatatype","single", ... "maximummessagelength",samplesperpacket, ... "receivebuffersize",buffersize);
reduce initialization overhead by sending a frame of zeros to the executable running on your raspberry pi.
udpsend(zeros(samplespercapture,1,"single"));
perform speech command recognition using deployed code
detect commands as long as both the time scope and matrix viewer are open or until the time limit is reached. to stop the live detection before the time limit is reached, close the time scope or matrix viewer window.
show(timescope) show(matrixviewer) timelimit = 20; tic while isvisible(timescope) && isvisible(matrixviewer) && toc < timelimit % capture audio and send that to raspi x = adr(); udpsend(x); % receive data packet from raspi udprec = udpreceive(); if ~isempty(udprec) % extract predicted index, the last sample of received udp packet speechcommandidx = udprec(end); % extract auditory spectrogram spec = reshape(udprec(1:numelementsperspectrogram), [numbands, numspectrumperspectrogram]); % display time domain signal and auditory spectrogram timescope(x) matrixviewer(spec) if speechcommandidx == backgroundidx timescope.title = ' '; else timescope.title = char(labels(speechcommandidx)); end drawnow limitrate end end hide(matrixviewer) hide(timescope)
to stop the executable on your raspberry pi, use stopexecutable
. release the udp objects.
stopexecutable(codertarget.raspi.raspberrypi,exename) release(udpsend) release(udpreceive)
profile using pil workflow
you can measure the execution time taken on the raspberry pi using a processor-in-the-loop (pil) workflow of embedded coder®. the supporting function is the equivalent of the function, except that the former returns the speech command index and auditory spectrogram while the latter sends the same parameters using udp. the time taken by the udp calls is less than 1 ms, which is relatively small compared to the overall execution time.
create a pil configuration object.
cfg = coder.config('lib','ecoder',true); cfg.verificationmode = 'pil';
set the arm compute library and architecture.
dlcfg = coder.deeplearningconfig('arm-compute'); cfg.deeplearningconfig = dlcfg ; cfg.deeplearningconfig.armarchitecture = 'armv7'; cfg.deeplearningconfig.armcomputeversion = '19.05';
set up the connection with your target hardware.
if (~exist('r','var')) r = raspi('raspiname','pi','password'); end hw = coder.hardware('raspberry pi'); cfg.hardware = hw;
set the build directory and target language.
builddir = '~/remotebuilddir'; cfg.hardware.builddir = builddir; cfg.targetlang = 'c ';
enable profiling and then generate the pil code. a mex file named profilespeechcommandrecognition_pil
is generated in your current folder.
cfg.codeexecutionprofiling = true; codegen -config cfg profilespeechcommandrecognitionraspi -args {rand(samplespercapture, 1, 'single')} -report -v
deploying code. this may take a few minutes. ### compiling function(s) profilespeechcommandrecognitionraspi ... ### connectivity configuration for function 'profilespeechcommandrecognitionraspi': 'raspberry pi' ### using toolchain: gnu gcc embedded linux ### creating 'w:\ex\examplemanager\sporwal.bdoc22a.j1844576\deeplearning_shared-ex00376115\codegen\lib\profilespeechcommandrecognitionraspi\coderassumptions\lib\profilespeechcommandrecognitionraspi_ca.mk' ... ### building 'profilespeechcommandrecognitionraspi_ca': make -j$(($(nproc) 1)) -otarget -f profilespeechcommandrecognitionraspi_ca.mk all ### using toolchain: gnu gcc embedded linux ### creating 'w:\ex\examplemanager\sporwal.bdoc22a.j1844576\deeplearning_shared-ex00376115\codegen\lib\profilespeechcommandrecognitionraspi\pil\profilespeechcommandrecognitionraspi_rtw.mk' ... ### building 'profilespeechcommandrecognitionraspi': make -j$(($(nproc) 1)) -otarget -f profilespeechcommandrecognitionraspi_rtw.mk all location of the generated elf : /home/pi/remotebuilddir/matlab_ws/r2022a/w/ex/examplemanager/sporwal.bdoc22a.j1844576/deeplearning_shared-ex00376115/codegen/lib/profilespeechcommandrecognitionraspi/pil ------------------------------------------------------------------------ ### using toolchain: gnu gcc embedded linux ### 'w:\ex\examplemanager\sporwal.bdoc22a.j1844576\deeplearning_shared-ex00376115\codegen\lib\profilespeechcommandrecognitionraspi\profilespeechcommandrecognitionraspi_rtw.mk' is up to date ### building 'profilespeechcommandrecognitionraspi': make -j$(($(nproc) 1)) -otarget -f profilespeechcommandrecognitionraspi_rtw.mk all ------------------------------------------------------------------------ ### generating compilation report ... code generation successful: view report
evaluate raspberry pi execution time
call the generated pil function multiple times to get the average execution time.
testdur = 50e-3; numcalls = 100; for k = 1:numcalls x = pinknoise(fs*testdur,'single'); [speechcommandidx, auditoryfeatures] = profilespeechcommandrecognitionraspi_pil(x); end
### starting application: 'codegen\lib\profilespeechcommandrecognitionraspi\pil\profilespeechcommandrecognitionraspi.elf' to terminate execution: clear profilespeechcommandrecognitionraspi_pil ### launching application profilespeechcommandrecognitionraspi.elf... execution profiling data is available for viewing. open simulation data inspector. execution profiling report available after termination.
terminate the pil execution.
clear profilespeechcommandrecognitionraspi_pil
### host application produced the following standard output (stdout) and standard error (stderr) messages: execution profiling report: report(getcoderexecutionprofile('profilespeechcommandrecognitionraspi'))
generate an execution profile report to evaluate execution time.
executionprofile = getcoderexecutionprofile('profilespeechcommandrecognitionraspi'); report(executionprofile, ... 'units','seconds', ... 'scalefactor','1e-03', ... 'numericformat','%0.4f')
ans = 'w:\ex\examplemanager\sporwal.bdoc22a.j1844576\deeplearning_shared-ex00376115\codegen\lib\profilespeechcommandrecognitionraspi\html\orphaned\executionprofiling_d82c7024f87064b9.html'
the maximum execution time taken by the function is nearly twice the average execution time. you can notice that the execution time is maximum for the first call of the pil function and it is due to the initialization happening in the first call. the average execution time is approximately 20 ms, which is below the 50 ms budget (audio capture time). the performance is measured on raspberry pi 4 model b rev 1.1.