modulation classification with deep learning -凯发k8网页登录
this example shows how to use a convolutional neural network (cnn) for modulation classification. you generate synthetic, channel-impaired waveforms. using the generated waveforms as training data, you train a cnn for modulation classification. you then test the cnn with software-defined radio (sdr) hardware and over-the-air signals.
predict modulation type using cnn
the trained cnn in this example recognizes these eight digital and three analog modulation types:
binary phase shift keying (bpsk)
quadrature phase shift keying (qpsk)
8-ary phase shift keying (8-psk)
16-ary quadrature amplitude modulation (16-qam)
64-ary quadrature amplitude modulation (64-qam)
4-ary pulse amplitude modulation (pam4)
gaussian frequency shift keying (gfsk)
continuous phase frequency shift keying (cpfsk)
broadcast fm (b-fm)
double sideband amplitude modulation (dsb-am)
single sideband amplitude modulation (ssb-am)
modulationtypes = categorical(["bpsk", "qpsk", "8psk", ... "16qam", "64qam", "pam4", "gfsk", "cpfsk", ... "b-fm", "dsb-am", "ssb-am"]);
first, load the trained network. for details on network training, see the training a cnn section.
load trainedmodulationclassificationnetwork
trainednet
trainednet = seriesnetwork with properties: layers: [28×1 nnet.cnn.layer.layer] inputnames: {'input layer'} outputnames: {'output'}
the trained cnn takes 1024 channel-impaired samples and predicts the modulation type of each frame. generate several pam4 frames that are impaired with rician multipath fading, center frequency and sampling time drift, and awgn. use following function to generate synthetic signals to test the cnn. then use the cnn to predict the modulation type of the frames.
: generate random bits
pam4-modulate the bits
: design a square-root raised cosine pulse shaping filter
: pulse shape the symbols
: apply rician multipath channel
: apply phase and/or frequency shift due to clock offset
: apply timing drift due to clock offset
: add awgn
% set the random number generator to a known state to be able to regenerate % the same frames every time the simulation is run rng(123456) % random bits d = randi([0 3], 1024, 1); % pam4 modulation syms = pammod(d,4); % square-root raised cosine filter filtercoeffs = rcosdesign(0.35,4,8); tx = filter(filtercoeffs,1,upsample(syms,8)); % channel snr = 30; maxoffset = 5; fc = 902e6; fs = 200e3; multipathchannel = comm.ricianchannel(... 'samplerate', fs, ... 'pathdelays', [0 1.8 3.4] / 200e3, ... 'averagepathgains', [0 -2 -10], ... 'kfactor', 4, ... 'maximumdopplershift', 4); frequencyshifter = comm.phasefrequencyoffset(... 'samplerate', fs); % apply an independent multipath channel reset(multipathchannel) outmultipathchan = multipathchannel(tx); % determine clock offset factor clockoffset = (rand() * 2*maxoffset) - maxoffset; c = 1 clockoffset / 1e6; % add frequency offset frequencyshifter.frequencyoffset = -(c-1)*fc; outfreqshifter = frequencyshifter(outmultipathchan); % add sampling time drift t = (0:length(tx)-1)' / fs; newfs = fs * c; tp = (0:length(tx)-1)' / newfs; outtimedrift = interp1(t, outfreqshifter, tp); % add noise rx = awgn(outtimedrift,snr,0); % frame generation for classification unknownframes = helpermodclassgetnnframes(rx); % classification [prediction1,score1] = classify(trainednet,unknownframes);
return the classifier predictions, which are analogous to hard decisions. the network correctly identifies the frames as pam4 frames. for details on the generation of the modulated signals, see function.
prediction1
prediction1 = 7×1 categorical
pam4
pam4
pam4
pam4
pam4
pam4
pam4
the classifier also returns a vector of scores for each frame. the score corresponds to the probability that each frame has the predicted modulation type. plot the scores.
helpermodclassplotscores(score1,modulationtypes)
before we can use a cnn for modulation classification, or any other task, we first need to train the network with known (or labeled) data. the first part of this example shows how to use communications toolbox™ features, such as modulators, filters, and channel impairments, to generate synthetic training data. the second part focuses on defining, training, and testing the cnn for the task of modulation classification. the third part tests the network performance with over-the-air signals using software defined radio (sdr) platforms.
waveform generation for training
generate 10,000 frames for each modulation type, where 80% is used for training, 10% is used for validation and 10% is used for testing. we use training and validation frames during the network training phase. final classification accuracy is obtained using test frames. each frame is 1024 samples long and has a sample rate of 200 khz. for digital modulation types, eight samples represent a symbol. the network makes each decision based on single frames rather than on multiple consecutive frames (as in video). assume a center frequency of 902 mhz and 100 mhz for the digital and analog modulation types, respectively.
to run this example quickly, use the trained network and generate a small number of training frames. to train the network on your computer, choose the "train network now" option (i.e. set trainnow to true).
trainnow = false; if trainnow == true numframespermodtype = 10000; else numframespermodtype = 200; end percenttrainingsamples = 80; percentvalidationsamples = 10; percenttestsamples = 10; sps = 8; % samples per symbol spf = 1024; % samples per frame symbolsperframe = spf / sps; fs = 200e3; % sample rate fc = [902e6 100e6]; % center frequencies
create channel impairments
pass each frame through a channel with
awgn
rician multipath fading
clock offset, resulting in center frequency offset and sampling time drift
because the network in this example makes decisions based on single frames, each frame must pass through an independent channel.
awgn
the channel adds awgn with an snr of 30 db. implement the channel using function.
rician multipath
the channel passes the signals through a rician multipath fading channel using the system object™. assume a delay profile of [0 1.8 3.4] samples with corresponding average path gains of [0 -2 -10] db. the k-factor is 4 and the maximum doppler shift is 4 hz, which is equivalent to a walking speed at 902 mhz. implement the channel with the following settings.
clock offset
clock offset occurs because of the inaccuracies of internal clock sources of transmitters and receivers. clock offset causes the center frequency, which is used to downconvert the signal to baseband, and the digital-to-analog converter sampling rate to differ from the ideal values. the channel simulator uses the clock offset factor , expressed as , where is the clock offset. for each frame, the channel generates a random value from a uniformly distributed set of values in the range [ ], where is the maximum clock offset. clock offset is measured in parts per million (ppm). for this example, assume a maximum clock offset of 5 ppm.
maxdeltaoff = 5; deltaoff = (rand()*2*maxdeltaoff) - maxdeltaoff; c = 1 (deltaoff/1e6);
frequency offset
subject each frame to a frequency offset based on clock offset factor and the center frequency. implement the channel using .
sampling rate offset
subject each frame to a sampling rate offset based on clock offset factor . implement the channel using the function to resample the frame at the new rate of .
combined channel
use the object to apply all three channel impairments to the frames.
channel = helpermodclasstestchannel(... 'samplerate', fs, ... 'snr', snr, ... 'pathdelays', [0 1.8 3.4] / fs, ... 'averagepathgains', [0 -2 -10], ... 'kfactor', 4, ... 'maximumdopplershift', 4, ... 'maximumclockoffset', 5, ... 'centerfrequency', 902e6)
channel = helpermodclasstestchannel with properties: snr: 30 centerfrequency: 902000000 samplerate: 200000 pathdelays: [0 9.0000e-06 1.7000e-05] averagepathgains: [0 -2 -10] kfactor: 4 maximumdopplershift: 4 maximumclockoffset: 5
you can view basic information about the channel using the info object function.
chinfo = info(channel)
chinfo = struct with fields:
channeldelay: 6
maximumfrequencyoffset: 4510
maximumsamplerateoffset: 1
waveform generation
create a loop that generates channel-impaired frames for each modulation type and stores the frames with their corresponding labels in mat files. by saving the data into files, you eliminate the need to generate the data every time you run this example. you can also share the data more effectively.
remove a random number of samples from the beginning of each frame to remove transients and to make sure that the frames have a random starting point with respect to the symbol boundaries.
% set the random number generator to a known state to be able to regenerate % the same frames every time the simulation is run rng(1235) tic nummodulationtypes = length(modulationtypes); channelinfo = info(channel); transdelay = 50; pool = getpoolsafe(); if ~isa(pool,"parallel.clusterpool") datadirectory = fullfile(tempdir,"modclassdatafiles"); else datadirectory = uigetdir("","select network location to save data files"); end disp("data file directory is " datadirectory)
data file directory is c:\temp\modclassdatafiles
filenameroot = "frame"; % check if data files exist datafilesexist = false; if exist(datadirectory,'dir') files = dir(fullfile(datadirectory,sprintf("%s*",filenameroot))); if length(files) == nummodulationtypes*numframespermodtype datafilesexist = true; end end if ~datafilesexist disp("generating data and saving in data files...") [success,msg,msgid] = mkdir(datadirectory); if ~success error(msgid,msg) end for modtype = 1:nummodulationtypes elapsedtime = seconds(toc); elapsedtime.format = 'hh:mm:ss'; fprintf('%s - generating %s frames\n', ... elapsedtime, modulationtypes(modtype)) label = modulationtypes(modtype); numsymbols = (numframespermodtype / sps); datasrc = helpermodclassgetsource(modulationtypes(modtype), sps, 2*spf, fs); modulator = helpermodclassgetmodulator(modulationtypes(modtype), sps, fs); if contains(char(modulationtypes(modtype)), {'b-fm','dsb-am','ssb-am'}) % analog modulation types use a center frequency of 100 mhz channel.centerfrequency = 100e6; else % digital modulation types use a center frequency of 902 mhz channel.centerfrequency = 902e6; end for p=1:numframespermodtype % generate random data x = datasrc(); % modulate y = modulator(x); % pass through independent channels rxsamples = channel(y); % remove transients from the beginning, trim to size, and normalize frame = helpermodclassframegenerator(rxsamples, spf, spf, transdelay, sps); % save data file filename = fullfile(datadirectory,... sprintf("%s%sd",filenameroot,modulationtypes(modtype),p)); save(filename,"frame","label") end end else disp("data files exist. skip data generation.") end
generating data and saving in data files...
00:00:00 - generating bpsk frames 00:00:02 - generating qpsk frames 00:00:03 - generating 8psk frames 00:00:05 - generating 16qam frames 00:00:06 - generating 64qam frames 00:00:08 - generating pam4 frames 00:00:10 - generating gfsk frames 00:00:11 - generating cpfsk frames 00:00:13 - generating b-fm frames 00:00:24 - generating dsb-am frames 00:00:26 - generating ssb-am frames
% plot the amplitude of the real and imaginary parts of the example frames % against the sample number helpermodclassplottimedomain(datadirectory,modulationtypes,fs)
% plot the spectrogram of the example frames
helpermodclassplotspectrogram(datadirectory,modulationtypes,fs,sps)
create a datastore
use a signaldatastore
object to manage the files that contain the generated complex waveforms. datastores are especially useful when each individual file fits in memory, but the entire collection does not necessarily fit.
frameds = signaldatastore(datadirectory,'signalvariablenames',["frame","label"]);
transform complex signals to real arrays
the deep learning network in this example expects real inputs while the received signal has complex baseband samples. transform the complex signals into real valued 4-d arrays. the output frames have size 1-by-spf-by-2-by-n, where the first page (3rd dimension) is in-phase samples and the second page is quadrature samples. when the convolutional filters are of size 1-by-spf, this approach ensures that the information in the i and q gets mixed even in the convolutional layers and makes better use of the phase information. see for details.
framedstrans = transform(frameds,@helpermodclassiqaspages);
split into training, validation, and test
next divide the frames into training, validation, and test data. see for details.
splitpercentages = [percenttrainingsamples,percentvalidationsamples,percenttestsamples]; [traindstrans,validdstrans,testdstrans] = helpermodclasssplitdata(framedstrans,splitpercentages);
import data into memory
neural network training is iterative. at every iteration, the datastore reads data from files and transforms the data before updating the network coefficients. if the data fits into the memory of your computer, importing the data from the files into the memory enables faster training by eliminating this repeated read from file and transform process. instead, the data is read from the files and transformed once. training this network using data files on disk takes about 110 minutes while training using in-memory data takes about 50 min.
import all the data in the files into memory. the files have two variables: frame
and label
and each call to the datastore returns a cell array, where the first element is the frame
and the second element is the label
. use the functions and to read frames and labels. use with "useparallel"
option set to true
to enable parallel processing of the transform functions, in case you have ™ license. since readall
function, by default, concatenates the output of the read
function over the first dimension, return the frames in a cell array and manually concatenate over the 4th dimension.
% read the training and validation frames into the memory pctexists = parallelcomputinglicenseexists(); trainframes = transform(traindstrans, @helpermodclassreadframe); rxtrainframes = readall(trainframes,"useparallel",pctexists); rxtrainframes = cat(4, rxtrainframes{:}); validframes = transform(validdstrans, @helpermodclassreadframe); rxvalidframes = readall(validframes,"useparallel",pctexists); rxvalidframes = cat(4, rxvalidframes{:}); % read the training and validation labels into the memory trainlabels = transform(traindstrans, @helpermodclassreadlabel); rxtrainlabels = readall(trainlabels,"useparallel",pctexists); validlabels = transform(validdstrans, @helpermodclassreadlabel); rxvalidlabels = readall(validlabels,"useparallel",pctexists);
train the cnn
this example uses a cnn that consists of six convolution layers and one fully connected layer. each convolution layer except the last is followed by a batch normalization layer, rectified linear unit (relu) activation layer, and max pooling layer. in the last convolution layer, the max pooling layer is replaced with an average pooling layer. the output layer has softmax activation. for network design guidance, see (deep learning toolbox).
modclassnet = helpermodclasscnn(modulationtypes,sps,spf);
next configure (deep learning toolbox) to use an sgdm solver with a mini-batch size of 1024. set the maximum number of epochs to 20, since a larger number of epochs provides no further training advantage. by default, the 'executionenvironment'
property is set to 'auto'
, where the trainnetwork
function uses a gpu if one is available or uses the cpu, if not. to use the gpu, you must have a license. set the initial learning rate to . reduce the learning rate by a factor of 1.25 every 7 epochs. set 'plots'
to 'training-progress'
to plot the training progress. on an nvidia® geforce rtx 3080 gpu, the network takes approximately 3 minutes to train.
maxepochs = 20;
minibatchsize = 1024;
options = helpermodclasstrainingoptions(maxepochs,minibatchsize,...
numel(rxtrainlabels),rxvalidframes,rxvalidlabels);
either train the network or use the already trained network. by default, this example uses the trained network.
if trainnow == true elapsedtime = seconds(toc); elapsedtime.format = 'hh:mm:ss'; fprintf('%s - training the network\n', elapsedtime) trainednet = trainnetwork(rxtrainframes,rxtrainlabels,modclassnet,options); else load trainedmodulationclassificationnetwork end
as the plot of the training progress shows, the network converges in about 20 epochs to more than 97% accuracy.
evaluate the trained network by obtaining the classification accuracy for the test frames. the results show that the network achieves about 97% accuracy for this group of waveforms.
elapsedtime = seconds(toc); elapsedtime.format = 'hh:mm:ss'; fprintf('%s - classifying test frames\n', elapsedtime)
00:00:50 - classifying test frames
% read the test frames into the memory testframes = transform(testdstrans, @helpermodclassreadframe); rxtestframes = readall(testframes,"useparallel",pctexists); rxtestframes = cat(4, rxtestframes{:}); % read the test labels into the memory testlabels = transform(testdstrans, @helpermodclassreadlabel); rxtestlabels = readall(testlabels,"useparallel",pctexists); rxtestpred = classify(trainednet,rxtestframes); testaccuracy = mean(rxtestpred == rxtestlabels); disp("test accuracy: " testaccuracy*100 "%")
test accuracy: 97.7273%
plot the confusion matrix for the test frames. as the matrix shows, the network confuses 16-qam and 64-qam frames. this problem is expected since each frame carries only 128 symbols and 16-qam is a subset of 64-qam. the network also confuses qpsk and 8-psk frames, since the constellations of these modulation types look similar once phase-rotated due to the fading channel and frequency offset.
figure cm = confusionchart(rxtestlabels, rxtestpred); cm.title = 'confusion matrix for test data'; cm.rowsummary = 'row-normalized'; cm.parent.position = [cm.parent.position(1:2) 950 550];
test with sdr
test the performance of the trained network with over-the-air signals using the function. to perform this test, you must have dedicated sdrs for transmission and reception. you can use two adalm-pluto radios, or one adalm-pluto radio for transmission and one usrp® radio for reception. you must (communications toolbox support package for analog devices adalm-pluto radio). if you are using a usrp® radio, you must also (communications toolbox support package for usrp radio). the helpermodclasssdrtest
function uses the same modulation functions as used for generating the training signals, and then transmits them using an adalm-pluto radio. instead of simulating the channel, capture the channel-impaired signals using the sdr that is configured for signal reception (adalm-pluto or usrp® radio). use the trained network with the same classify
function used previously to predict the modulation type. running the next code segment produces a confusion matrix and prints out the test accuracy.
radioplatform = "adalm-pluto"; switch radioplatform case "adalm-pluto" if helperisplutosdrinstalled() == true radios = findplutoradio(); if length(radios) >= 2 helpermodclasssdrtest(radios); else disp('selected radios not found. skipping over-the-air test.') end end case {"usrp b2xx","usrp x3xx","usrp n2xx"} if (helperisusrpinstalled() == true) && (helperisplutosdrinstalled() == true) txradio = findplutoradio(); rxradio = findsdru(); switch radioplatform case "usrp b2xx" idx = contains({rxradio.platform}, {'b200','b210'}); case "usrp x3xx" idx = contains({rxradio.platform}, {'x300','x310'}); case "usrp n2xx" idx = contains({rxradio.platform}, 'n200/n210/usrp2'); end rxradio = rxradio(idx); if (length(txradio) >= 1) && (length(rxradio) >= 1) helpermodclasssdrtest(rxradio); else disp('selected radios not found. skipping over-the-air test.') end end end
when using two stationary adalm-pluto radios separated by about 2 feet, the network achieves 99% overall accuracy with the following confusion matrix. results will vary based on experimental setup.
further exploration
it is possible to optimize the hyperparameters parameters, such as number of filters, filter size, or optimize the network structure, such as adding more layers, using different activation layers, etc. to improve the accuracy.
communication toolbox provides many more modulation types and channel impairments. for more information see and propagation and channel models sections. you can also add standard specific signals with , , and . you can also add radar signals with .
function provides the matlab® functions used to generate modulated signals. you can also explore the following functions and system objects for more details:
helper files
function pool = getpoolsafe() if exist("gcp","file") && license('test','distrib_computing_toolbox') pool = gcp; if isempty(pool) pool = parpool; end else pool = []; end end
references
o'shea, t. j., j. corgan, and t. c. clancy. "convolutional radio modulation recognition networks." preprint, submitted june 10, 2016.
o'shea, t. j., t. roy, and t. c. clancy. "over-the-air deep learning based radio signal classification." ieee journal of selected topics in signal processing. vol. 12, number 1, 2018, pp. 168–179.
liu, x., d. yang, and a. e. gamal. "deep neural network architectures for modulation classification." preprint, submitted january 5, 2018.
related topics
- deep learning in matlab (deep learning toolbox)