acoustic scene recognition using late fusion -凯发k8网页登录
this example shows how to create a multi-model late fusion system for acoustic scene recognition. the example trains a convolutional neural network (cnn) using mel spectrograms and an ensemble classifier using wavelet scattering. the example uses the tut dataset for training and evaluation .
introduction
acoustic scene classification (asc) is the task of classifying environments from the sounds they produce. asc is a generic classification problem that is foundational for context awareness in devices, robots, and many other applications . early attempts at asc used mel-frequency cepstral coefficients () and gaussian mixture models (gmms) to describe their statistical distribution. other popular features used for asc include zero crossing rate, spectral centroid (), spectral rolloff (), spectral flux ( ), and linear prediction coefficients () . hidden markov models (hmms) were trained to describe the temporal evolution of the gmms. more recently, the best performing systems have used deep learning, usually cnns, and a fusion of multiple models. the most popular feature for top-ranked systems in the dcase 2017 contest was the mel spectrogram (). the top-ranked systems in the challenge used late fusion and data augmentation to help their systems generalize.
to illustrate a simple approach that produces reasonable results, this example trains a cnn using mel spectrograms and an ensemble classifier using wavelet scattering. the cnn and ensemble classifier produce roughly equivalent overall accuracy, but perform better at distinguishing different acoustic scenes. to increase overall accuracy, you merge the cnn and ensemble classifier results using late fusion.
load acoustic scene recognition data set
to run the example, you must first download the data set . the full data set is approximately 15.5 gb. depending on your machine and internet connection, downloading the data can take about 4 hours.
downloadfolder = tempdir; dataset = fullfile(downloadfolder,"tut-acoustic-scenes-2017"); if ~datasetexists(dataset) disp("downloading tut-acoustic-scenes-2017 (15.5 gb) ...") helperdownload_tut_acoustic_scenes_2017(dataset); end
read in the development set metadata as a table. name the table variables filename
, acousticscene
, and specificlocation
.
trainmetadata = readtable(fullfile(dataset,"tut-acoustic-scenes-2017-development","meta"), ... delimiter={'\t'}, ... readvariablenames=false); trainmetadata.properties.variablenames = ["filename","acousticscene","specificlocation"]; head(trainmetadata)
ans=8×3 table
filename acousticscene specificlocation
__________________________ _____________ ________________
{'audio/b020_90_100.wav' } {'beach'} {'b020'}
{'audio/b020_110_120.wav'} {'beach'} {'b020'}
{'audio/b020_100_110.wav'} {'beach'} {'b020'}
{'audio/b020_40_50.wav' } {'beach'} {'b020'}
{'audio/b020_50_60.wav' } {'beach'} {'b020'}
{'audio/b020_30_40.wav' } {'beach'} {'b020'}
{'audio/b020_160_170.wav'} {'beach'} {'b020'}
{'audio/b020_170_180.wav'} {'beach'} {'b020'}
testmetadata = readtable(fullfile(dataset,"tut-acoustic-scenes-2017-evaluation","meta"), ... delimiter={'\t'}, ... readvariablenames=false); testmetadata.properties.variablenames = ["filename","acousticscene","specificlocation"]; head(testmetadata)
ans=8×3 table
filename acousticscene specificlocation
__________________ _____________ ________________
{'audio/1245.wav'} {'beach'} {'b174'}
{'audio/1456.wav'} {'beach'} {'b174'}
{'audio/1318.wav'} {'beach'} {'b174'}
{'audio/967.wav' } {'beach'} {'b174'}
{'audio/203.wav' } {'beach'} {'b174'}
{'audio/777.wav' } {'beach'} {'b174'}
{'audio/231.wav' } {'beach'} {'b174'}
{'audio/768.wav' } {'beach'} {'b174'}
note that the specific recording locations in the test set do not intersect with the specific recording locations in the development set. this makes it easier to validate that the trained models can generalize to real-world scenarios.
sharedrecordinglocations = intersect(testmetadata.specificlocation,trainmetadata.specificlocation);
disp("number of specific recording locations in both train and test sets = " numel(sharedrecordinglocations))
number of specific recording locations in both train and test sets = 0
the first variable of the metadata tables contains the file names. concatenate the file names with the file paths.
trainfilepaths = fullfile(dataset,"tut-acoustic-scenes-2017-development",trainmetadata.filename); testfilepaths = fullfile(dataset,"tut-acoustic-scenes-2017-evaluation",testmetadata.filename);
there may be files listed in the metadata that are not present in the data set. remove the filepaths and acoustic scene labels that correspond to the missing files.
ads = audiodatastore(dataset,includesubfolders=true); allfiles = ads.files; trainidxtoremove = ~ismember(trainfilepaths,allfiles); trainfilepaths(trainidxtoremove) = []; trainlabels = categorical(trainmetadata.acousticscene); trainlabels(trainidxtoremove) = []; testidxtoremove = ~ismember(testfilepaths,allfiles); testfilepaths(testidxtoremove) = []; testlabels = categorical(testmetadata.acousticscene); testlabels(testidxtoremove) = [];
create audio datastores for the train and test sets. set the labels
property of the audiodatastore
to the acoustic scene. call to verify an even distribution of labels in both the train and test sets.
adstrain = audiodatastore(trainfilepaths, ... labels=trainlabels, ... includesubfolders=true); display(counteachlabel(adstrain))
15×2 table label count ________________ _____ beach 312 bus 312 cafe/restaurant 312 car 312 city_center 312 forest_path 312 grocery_store 312 home 312 library 312 metro_station 312 office 312 park 312 residential_area 312 train 312 tram 312
adstest = audiodatastore(testfilepaths, ... labels=categorical(testmetadata.acousticscene), ... includesubfolders=true); display(counteachlabel(adstest))
15×2 table label count ________________ _____ beach 108 bus 108 cafe/restaurant 108 car 108 city_center 108 forest_path 108 grocery_store 108 home 108 library 108 metro_station 108 office 108 park 108 residential_area 108 train 108 tram 108
you can reduce the data set used in this example to speed up the run time at the cost of performance. in general, reducing the data set is a good practice for development and debugging. set speedupexample
to true
to reduce the data set.
speedupexample = false; if speedupexample adstrain = spliteachlabel(adstrain,20); adstest = spliteachlabel(adstest,10); end
call to get the data and sample rate of a file from the train set. audio in the database has consistent sample rate and duration. normalize the audio and listen to it. display the corresponding label.
[data,adsinfo] = read(adstrain); data = data./max(data,[],"all"); fs = adsinfo.samplerate; sound(data,fs) disp("acoustic scene = " string(adstrain.labels(1)))
acoustic scene = beach
call to return the datastore to its initial condition.
reset(adstrain)
feature extraction for cnn
each audio clip in the dataset consists of 10 seconds of stereo (left-right) audio. the feature extraction pipeline and the cnn architecture in this example are based on . hyperparameters for the feature extraction, the cnn architecture, and the training options were modified from the original paper using a systematic hyperparameter optimization workflow.
first, convert the audio to mid-side encoding. suggests that mid-side encoded data provides better spatial information that the cnn can use to identify moving sources (such as a train moving across an acoustic scene).
datamidside = [sum(data,2),data(:,1)-data(:,2)];
divide the signal into one-second segments with overlap. the final system uses a probability-weighted average on the one-second segments to predict the scene for each 10-second audio clip in the test set. dividing the audio clips into one-second segments makes the network easier to train and helps prevent overfitting to specific acoustic events in the training set. the overlap helps to ensure all combinations of features relative to one another are captured by the training data. it also provides the system with additional data that can be mixed uniquely during augmentation.
segmentlength = 1; segmentoverlap = 0.5; [databufferedmid,~] = buffer(datamidside(:,1),round(segmentlength*fs),round(segmentoverlap*fs),"nodelay"); [databufferedside,~] = buffer(datamidside(:,2),round(segmentlength*fs),round(segmentoverlap*fs),"nodelay"); databuffered = zeros(size(databufferedmid,1),size(databufferedmid,2) size(databufferedside,2)); databuffered(:,1:2:end) = databufferedmid; databuffered(:,2:2:end) = databufferedside;
use to transform the data into a compact frequency-domain representation. define parameters for the mel spectrogram as suggested by .
windowlength = 2048; samplesperhop = 1024; samplesoverlap = windowlength - samplesperhop; fftlength = 2*windowlength; numbands = 128;
melspectrogram
operates along channels independently. to optimize processing time, call melspectrogram
with the entire buffered signal.
spec = melspectrogram(databuffered,fs, ... window=hamming(windowlength,"periodic"), ... overlaplength=samplesoverlap, ... fftlength=fftlength, ... numbands=numbands);
convert the mel spectrogram into the logarithmic scale.
spec = log10(spec eps);
reshape the array to dimensions (number of bands)-by-(number of hops)-by-(number of channels)-by-(number of segments). when you feed an image into a neural network, the first two dimensions are the height and width of the image, the third dimension is the channels, and the fourth dimension separates the individual images.
x = reshape(spec,size(spec,1),size(spec,2),size(data,2),[]);
call melspectrogram
without output arguments to plot the mel spectrogram of the mid channel for the first six of the one-second increments.
tiledlayout(3,2) for channel = 1:2:11 nexttile melspectrogram(databuffered(:,channel),fs, ... window=hamming(windowlength,"periodic"), ... overlaplength=samplesoverlap, ... fftlength=fftlength, ... numbands=numbands); title("segment " ceil(channel/2)) end
the helper function performs the feature extraction steps outlined above.
to speed up processing, extract mel spectrograms of all audio files in the datastores using arrays. unlike in-memory arrays, tall arrays remain unevaluated until you request that the calculations be performed using the function. this deferred evaluation enables you to work quickly with large data sets. when you eventually request the output using gather
, matlab combines the queued calculations where possible and takes the minimum number of passes through the data. if you have parallel computing toolbox™, you can use tall arrays in your local matlab session, or on a local parallel pool. you can also run tall array calculations on a cluster if you have matlab® parallel server™ installed.
if you do not have parallel computing toolbox™, the code in this example still runs.
train_set_tall = tall(adstrain); xtrain = cellfun(@(x)helpersegmentedmelspectrograms(x,fs, ... segmentlength=segmentlength, ... segmentoverlap=segmentoverlap, ... windowlength=windowlength, ... hoplength=samplesperhop, ... numbands=numbands, ... fftlength=fftlength), ... train_set_tall, ... uniformoutput=false); xtrain = gather(xtrain);
evaluating tall expression using the parallel pool 'local': - pass 1 of 1: 0% complete evaluation 0% complete - pass 1 of 1: completed in 3 min 56 sec evaluation completed in 3 min 56 sec
xtrain = cat(4,xtrain{:}); test_set_tall = tall(adstest); xtest = cellfun(@(x)helpersegmentedmelspectrograms(x,fs, ... segmentlength=segmentlength, ... segmentoverlap=segmentoverlap, ... windowlength=windowlength, ... hoplength=samplesperhop, ... numbands=numbands, ... fftlength=fftlength), ... test_set_tall, ... uniformoutput=false); xtest = gather(xtest);
evaluating tall expression using the parallel pool 'local': - pass 1 of 1: completed in 1 min 26 sec evaluation completed in 1 min 26 sec
xtest = cat(4,xtest{:});
replicate the labels of the training and test sets so that they are in one-to-one correspondence with the segments.
numsegmentsper10seconds = size(databuffered,2)/2; ytrain = repmat(adstrain.labels,1,numsegmentsper10seconds)'; ytrain = ytrain(:); ytest = repmat(adstest.labels,1,numsegmentsper10seconds)'; ytest = ytest(:);
data augmentation for cnn
the dcase 2017 dataset contains a relatively small number of acoustic recordings for the task, and the development set and evaluation set were recorded at different specific locations. as a result, it is easy to overfit to the data during training. one popular method to reduce overfitting is mixup. in mixup, you augment your dataset by mixing the features of two different classes. when you mix the features, you mix the labels in equal proportion. that is:
mixup was reformulated by as labels drawn from a probability distribution instead of mixed labels. the implementation of mixup in this example is a simplified version of mixup: each spectrogram is mixed with a spectrogram of a different label with lambda set to 0.5. the original and mixed datasets are combined for training.
xtrainextra = xtrain; ytrainextra = ytrain; lambda = 0.5; for ii = 1:size(xtrain,4) % find all available spectrograms with different labels. availablespectrograms = find(ytrain~=ytrain(ii)); % randomly choose one of the available spectrograms with a different label. numavailablespectrograms = numel(availablespectrograms); idx = randi([1,numavailablespectrograms]); % mix. xtrainextra(:,:,:,ii) = lambda*xtrain(:,:,:,ii) (1-lambda)*xtrain(:,:,:,availablespectrograms(idx)); % specify the label as randomly set by lambda. if rand > lambda ytrainextra(ii) = ytrain(availablespectrograms(idx)); end end xtrain = cat(4,xtrain,xtrainextra); ytrain = [ytrain;ytrainextra];
call summary
to display the distribution of labels for the augmented training set.
summary(ytrain)
beach 11769 bus 11904 cafe/restaurant 11873 car 11820 city_center 11886 forest_path 11936 grocery_store 11914 home 11923 library 11817 metro_station 11804 office 11922 park 11871 residential_area 11704 train 11773 tram 11924
define and train cnn
define the cnn architecture. this architecture is based on and modified through trial and error. see (deep learning toolbox) to learn more about deep learning layers available in matlab®.
imgsize = [size(xtrain,1),size(xtrain,2),size(xtrain,3)]; numf = 32; layers = [ ... imageinputlayer(imgsize) batchnormalizationlayer convolution2dlayer(3,numf,padding="same") batchnormalizationlayer relulayer convolution2dlayer(3,numf,padding="same") batchnormalizationlayer relulayer maxpooling2dlayer(3,stride=2,padding="same") convolution2dlayer(3,2*numf,padding="same") batchnormalizationlayer relulayer convolution2dlayer(3,2*numf,padding="same") batchnormalizationlayer relulayer maxpooling2dlayer(3,stride=2,padding="same") convolution2dlayer(3,4*numf,padding="same") batchnormalizationlayer relulayer convolution2dlayer(3,4*numf,padding="same") batchnormalizationlayer relulayer maxpooling2dlayer(3,stride=2,padding="same") convolution2dlayer(3,8*numf,padding="same") batchnormalizationlayer relulayer convolution2dlayer(3,8*numf,padding="same") batchnormalizationlayer relulayer globalaveragepooling2dlayer dropoutlayer(0.5) fullyconnectedlayer(15) softmaxlayer classificationlayer];
define (deep learning toolbox) for the cnn. these options are based on and modified through a systematic hyperparameter optimization workflow.
minibatchsize = 128; tuneme = 128; lr = 0.05*minibatchsize/tuneme; options = trainingoptions( ... "sgdm", ... momentum=0.9, ... l2regularization=0.005, ... ... minibatchsize=minibatchsize, ... maxepochs=8, ... shuffle="every-epoch", ... ... plots="training-progress", ... verbose=false, ... ... initiallearnrate=lr, ... learnrateschedule="piecewise", ... learnratedropperiod=2, ... learnratedropfactor=0.2, ... ... validationdata={xtest,ytest}, ... validationfrequency=floor(size(xtrain,4)/minibatchsize));
call (deep learning toolbox) to train the network.
trainednet = trainnetwork(xtrain,ytrain,layers,options);
evaluate cnn
call (deep learning toolbox) to predict responses from the trained network using the held-out test set.
cnnresponsespersegment = predict(trainednet,xtest);
average the responses over each 10-second audio clip.
classes = trainednet.layers(end).classes; numfiles = numel(adstest.files); counter = 1; cnnresponses = zeros(numfiles,numel(classes)); for channel = 1:numfiles cnnresponses(channel,:) = sum(cnnresponsespersegment(counter:counter numsegmentsper10seconds-1,:),1)/numsegmentsper10seconds; counter = counter numsegmentsper10seconds; end
for each 10-second audio clip, choose the maximum of the predictions, then map it to the corresponding predicted location.
[~,classidx] = max(cnnresponses,[],2); cnnpredictedlabels = classes(classidx);
call (deep learning toolbox) to visualize the accuracy on the test set.
figure(units="normalized",position=[0.2 0.2 0.5 0.5]) confusionchart(adstest.labels,cnnpredictedlabels, ... title=["test accuracy - cnn","average accuracy = " mean(adstest.labels==cnnpredictedlabels)*100], ... columnsummary="column-normalized",rowsummary="row-normalized");
feature extraction for ensemble classifier
wavelet scattering has been shown in to provide a good representation of acoustic scenes. define a waveletscattering
(wavelet toolbox) object. the invariance scale and quality factors were determined through trial and error.
sf = waveletscattering(signallength=size(data,1), ... samplingfrequency=fs, ... invariancescale=0.75, ... qualityfactors=[4 1]);
convert the audio signal to mono, and then call (wavelet toolbox) to return the scattering coefficients for the scattering decomposition framework, sf
.
datamono = mean(data,2);
scatteringcoeffients = featurematrix(sf,datamono,transform="log");
average the scattering coefficients over the 10-second audio clip.
featurevector = mean(scatteringcoeffients,2);
disp("number of wavelet features per 10-second clip = " numel(featurevector));
number of wavelet features per 10-second clip = 286
the helper function performs the above steps. use a array with and helperwaveletfeaturevector
to parallelize the feature extraction. extract wavelet feature vectors for the train and test sets.
scatteringtrain = cellfun(@(x)helperwaveletfeaturevector(x,sf),train_set_tall,uniformoutput=false); xtrain = gather(scatteringtrain); xtrain = cell2mat(xtrain')';
scatteringtest = cellfun(@(x)helperwaveletfeaturevector(x,sf),test_set_tall,uniformoutput=false); xtest = gather(scatteringtest); xtest = cell2mat(xtest')';
define and train ensemble classifier
use fitcensemble
to create a trained classification ensemble model (classificationensemble
).
subspacedimension = min(150,size(xtrain,2) - 1); numlearningcycles = 30; classificationensemble = fitcensemble(xtrain,adstrain.labels, ... method="subspace", ... numlearningcycles=numlearningcycles, ... learners="discriminant", ... npredtosample=subspacedimension, ... classnames=removecats(unique(adstrain.labels)));
evaluate ensemble classifier
for each 10-second audio clip, call predict
to return the labels and the weights, then map it to the corresponding predicted location. call (deep learning toolbox) to visualize the accuracy on the test set.
[waveletpredictedlabels,waveletresponses] = predict(classificationensemble,xtest); figure(units="normalized",position=[0.2 0.2 0.5 0.5]) confusionchart(adstest.labels,waveletpredictedlabels, ... title=["test accuracy - wavelet scattering","average accuracy = " mean(adstest.labels==waveletpredictedlabels)*100], ... columnsummary="column-normalized",rowsummary="row-normalized");
fprintf('average accuracy of classifier = %0.2f\n',mean(adstest.labels==waveletpredictedlabels)*100)
average accuracy of classifier = 75.74
apply late fusion
for each 10-second clip, calling predict
on the wavelet classifier and the cnn returns a vector indicating the relative confidence in their decision. multiply the waveletresponses
with the cnnresponses
to create a late fusion system.
fused = waveletresponses.*cnnresponses; [~,classidx] = max(fused,[],2); predictedlabels = classes(classidx);
evaluate late fusion
call confusionchart
to visualize the fused classification accuracy.
figure(units="normalized",position=[0.2 0.2 0.5 0.5]) confusionchart(adstest.labels,predictedlabels, ... title=["test accuracy - fusion","average accuracy = " mean(adstest.labels==predictedlabels)*100], ... columnsummary="column-normalized",rowsummary="row-normalized");
supporting functions
helpersegmentedmelspectrograms
function x = helpersegmentedmelspectrograms(x,fs,varargin) % 凯发官网入口首页 copyright 2019-2021 the mathworks, inc. p = inputparser; addparameter(p,windowlength=1024); addparameter(p,hoplength=512); addparameter(p,numbands=128); addparameter(p,segmentlength=1); addparameter(p,segmentoverlap=0); addparameter(p,fftlength=1024); parse(p,varargin{:}) params = p.results; x = [sum(x,2),x(:,1)-x(:,2)]; x = x./max(max(x)); [xb_m,~] = buffer(x(:,1),round(params.segmentlength*fs),round(params.segmentoverlap*fs),"nodelay"); [xb_s,~] = buffer(x(:,2),round(params.segmentlength*fs),round(params.segmentoverlap*fs),"nodelay"); xb = zeros(size(xb_m,1),size(xb_m,2) size(xb_s,2)); xb(:,1:2:end) = xb_m; xb(:,2:2:end) = xb_s; spec = melspectrogram(xb,fs, ... window=hamming(params.windowlength,"periodic"), ... overlaplength=params.windowlength - params.hoplength, ... fftlength=params.fftlength, ... numbands=params.numbands, ... frequencyrange=[0,floor(fs/2)]); spec = log10(spec eps); x = reshape(spec,size(spec,1),size(spec,2),size(x,2),[]); end
helperwaveletfeatureextractor
function features = helperwaveletfeaturevector(x,sf) % 凯发官网入口首页 copyright 2019-2021 the mathworks, inc. x = mean(x,2); features = featurematrix(sf,x,transform="log"); features = mean(features,2); end
references
[1] a. mesaros, t. heittola, and t. virtanen. acoustic scene classification: an overview of dcase 2017 challenge entries. in proc. international workshop on acoustic signal enhancement, 2018.
[2] huszar, ferenc. "mixup: data-dependent data augmentation." inference. november 03, 2017. accessed january 15, 2019. .
[3] han, yoonchang, jeongsoo park, and kyogu lee. "convolutional neural networks with binaural representations and background subtraction for acoustic scene classification." the detection and classification of acoustic scenes and events (dcase) (2017): 1-5.
[4] lostanlen, vincent, and joakim anden. binaural scene classification with wavelet scattering. technical report, dcase2016 challenge, 2016.
[5] a. j. eronen, v. t. peltonen, j. t. tuomi, a. p. klapuri, s. fagerlund, t. sorsa, g. lorho, and j. huopaniemi, "audio-based context recognition," ieee trans. on audio, speech, and language processing, vol 14, no. 1, pp. 321-329, jan 2006.
[6]
[7]