%% Weighted Cross-Entropy Loss
% Create an array of prediction scores for 12 observations over 10 classes.

numClasses = 10;
numObservations = 12;

Y = rand(numClasses,numObservations);
dlY = dlarray(Y,'CB');
dlY = softmax(dlY);

% View the size and format of the prediction scores.

size(dlY)
dims(dlY)

% Create an array of targets encoded as one-hot vectors.

labels = randi(numClasses,[1 numObservations]);
targets = onehotencode(labels,1,'ClassNames',1:numClasses);

% View the size of the targets.

size(targets)

% Compute the weighted cross-entropy loss between the predictions and the targets using a vector class weights. Specify a weights format of 'UC' (unspecified, channel) using the 'WeightsFormat' option.

weights = rand(1,numClasses);
loss = crossentropy(dlY,targets,weights,'WeightsFormat','UC')

% Copyright 2021 The MathWorks, Inc.