%% Masked Huber Loss for Padded Sequences
% Create arrays of predictions and targets for 12 sequences of varying lengths over 10 responses.

numResponses = 10;
numObservations = 12;
maxSequenceLength = 15;

sequenceLengths = randi(maxSequenceLength,[1 numObservations]);

Y = cell(numObservations,1);
targets = cell(numObservations,1);

for i = 1:numObservations
    Y{i} = rand(numResponses,sequenceLengths(i));
    targets{i} = rand(numResponses,sequenceLengths(i));
end

% View the cell arrays of predictions and targets.

Y
targets

% Pad the prediction and target sequences in the second dimension using the padsequences function and also return the corresponding mask.

[Y,mask] = padsequences(Y,2);
targets = padsequences(targets,2);

% Convert the padded sequences to dlarray with format 'CTB' (channel, time, batch). Because formatted dlarray objects automatically sort the dimensions, keep the dimensions of the targets and mask consistent by also converting them to a formatted dlarray objects with the same formats.

dlY = dlarray(Y,'CTB');
targets = dlarray(targets,'CTB');
mask = dlarray(mask,'CTB');

% View the sizes of the prediction scores, targets, and the mask.

size(dlY)
size(targets)
size(mask)

% Compute the Huber loss between the predictions and the targets. To prevent the loss values calculated from padding from contributing to the loss, set the 'Mask' option to the mask returned by the padsequences function.

loss = huber(dlY,targets,'Mask',mask)

% Copyright 2021 The MathWorks, Inc.