blackBoxRC.m 1.7 KB
Newer Older
hazrmard's avatar
hazrmard committed
1
2
3
4
5
6
7
8
9
10
% Estimates a LSTM model of a RC circuit.
% 
% See:
% - https://www.mathworks.com/help/deeplearning/ug/long-short-term-memory-networks.html
% - https://www.mathworks.com/help/deeplearning/examples/sequence-to-sequence-regression-using-deep-learning.html
% - https://www.mathworks.com/help/deeplearning/examples/time-series-forecasting-using-deep-learning.html

close all;

% Load training data
11
rcdat = load('RC_comb_250.mat');
hazrmard's avatar
hazrmard committed
12
13
14
15
t = rcdat.data(:,1);    % timestamps
u = rcdat.data(:,2);    % input
y = rcdat.data(:,3) * 1000;    % output

16
% Normalizing input signal
hazrmard's avatar
hazrmard committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
mu = mean(u);
sig = std(u);
stdU = (u - mu) / sig;

% Split into sub-sequences
seqLength = 500;
seqU = reshape(stdU, [], seqLength);
seqY = reshape(y, [], seqLength);


XTrain = mat2cell(seqU, ones(1, size(seqU,1)));
YTrain = mat2cell(seqY, ones(1, size(seqY,1)));

% creating LSTM architecture
numFeatures = 1;
numHiddenUnits = 16;
numResponses = 1;

layers = [ ...
    sequenceInputLayer(numFeatures)
    lstmLayer(numHiddenUnits,'OutputMode','sequence')
    lstmLayer(numHiddenUnits,'OutputMode','sequence')
    lstmLayer(numHiddenUnits,'OutputMode','sequence')
    lstmLayer(numHiddenUnits,'OutputMode','sequence')
    fullyConnectedLayer(numResponses)
    regressionLayer];

options = trainingOptions('adam', ...
    'MaxEpochs',40, ...
    'MiniBatchSize', 5, ...
    'GradientThreshold',1, ...
    'InitialLearnRate',0.1, ...
    'LearnRateSchedule','piecewise', ...
    'LearnRateDropPeriod',5, ...
    'LearnRateDropFactor',0.7, ...
    'Verbose',0, ...
    'Plots','training-progress');

net = trainNetwork(XTrain, YTrain, layers, options);

57
% Plot predicted and actual output
hazrmard's avatar
hazrmard committed
58
59
60
YPred = cell2mat(predict(net, {u'}));
plot(t, y, t, YPred);
legend('Actual', 'Prediction');