l2loss
L2loss for regression tasks
Syntax
Description
The L2loss operation computes the L2loss (based on the squared L2norm) given network predictions and target values. When theReduction
option is"sum"
and theNormalizationFactor
option is"batch-size"
, the computed value is known as the mean squared error (MSE).
Thel2loss
function calculates the L2loss usingdlarray
data.Usingdlarray
objects makes working with high dimensional data easier by allowing you to label the dimensions. For example, you can label which dimensions correspond to spatial, time, channel, and batch dimensions using the"S"
,"T"
,"C"
, and"B"
labels, respectively. For unspecified and other dimensions, use the"U"
label. Fordlarray
object functions that operate over particular dimensions, you can specify the dimension labels by formatting thedlarray
object directly, or by using theDataFormat
option.
specifies additional options using one or more name-value arguments. For example,loss
= l2loss(___,Name=Value
)l2loss(Y,targets,Reduction="none")
computes the L2loss without reducing the output to a scalar.
Examples
Mean Squared Error Loss
Create an array of predictions for 12 observations over 10 responses.
numResponses = 10; numObservations = 12; Y = rand(numResponses,numObservations); dlY = dlarray(Y,'CB');
View the size and format of the predictions.
size(dlY)
ans =1×210 12
dims(dlY)
ans = 'CB'
Create an array of random targets.
targets = rand(numResponses,numObservations);
View the size of the targets.
size(targets)
ans =1×210 12
Compute the mean squared error (MSE) loss between the predictions and the targets using thel2loss
function.
loss = l2loss(dlY,targets)
loss = 1x1 dlarray 1.4748
Masked Mean Squared Error 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);fori = 1:numObservations Y{i} = rand(numResponses,sequenceLengths(i)); targets{i} = rand(numResponses,sequenceLengths(i));end
View the cell arrays of predictions and targets.
Y
Y=12×1 cell array{10x13 double} {10x14 double} {10x2 double} {10x14 double} {10x10 double} {10x2 double} {10x5 double} {10x9 double} {10x15 double} {10x15 double} {10x3 double} {10x15 double}
targets
targets=12×1 cell array{10x13 double} {10x14 double} {10x2 double} {10x14 double} {10x10 double} {10x2 double} {10x5 double} {10x9 double} {10x15 double} {10x15 double} {10x3 double} {10x15 double}
Pad the prediction and target sequences in the second dimension using thepadsequences
function and also return the corresponding mask.
[Y,mask] = padsequences(Y,2); targets = padsequences(targets,2);
Convert the padded sequences todlarray
with the format"CTB"
(channel, time, batch). Because formatteddlarray
objects automatically permute the dimensions of the underlying data, keep the order consistent by also converting the targets and mask to formatteddlarray
objects with the format"CTB"
(channel, batch, time).
dlY = dlarray(Y,"CTB"); targets = dlarray(targets,"CTB"); mask = dlarray(mask,"CTB");
View the sizes of the prediction scores, targets, and mask.
size(dlY)
ans =1×310 12 15
size(targets)
ans =1×310 12 15
size(mask)
ans =1×310 12 15
Compute the mean squared error (MSE) between the predictions and the targets. To prevent the loss values calculated from padding from contributing to the loss, set theMask
option to the mask returned by thepadsequences
function.
loss = l2loss(dlY,targets,Mask=mask)
loss = 1x1 dlarray 16.3668
Input Arguments
Y
—Predictions
dlarray
|numeric array
Predictions, specified as a formatteddlarray
, an unformatteddlarray
或数字数组。WhenY
is not a formatteddlarray
, you must specify the dimension format using theDataFormat
option.
IfY
is a numeric array,targets
must be adlarray
.
targets
—Target responses
dlarray
|numeric array
Target responses, specified as a formatted or unformatteddlarray
or a numeric array.
的大小each dimension oftargets
must match the size of the corresponding dimension ofY
.
Iftargets
is a formatteddlarray
, then its format must be the same as the format ofY
, or the same asDataFormat
ifY
is unformatted.
Iftargets
is an unformatteddlarray
or a numeric array, then the function applies the format ofY
or the value ofDataFormat
totargets
.
Tip
Formatteddlarray
objects automatically permute the dimensions of the underlying data to have order"S"
(spatial),"C"
(channel),"B"
(batch),"T"
(time), then"U"
(unspecified). To ensure that the dimensions ofY
andtargets
are consistent, whenY
is a formatteddlarray
, also specifytargets
as a formatteddlarray
.
weights
—Weights
dlarray
|numeric array
Weights, specified as a formatted or unformatteddlarray
or a numeric array.
Ifweights
is a vector andY
has two or more nonsingleton dimensions, thenweights
must be a formatteddlarray
, where the dimension label of the nonsingleton dimension is either"C"
(channel) or"B"
(batch) and has a size that matches the size of the corresponding dimension inY
.
Ifweights
is a formatteddlarray
with two or more nonsingleton dimensions, then its format must match the format ofY
.
Ifweights
is not a formatteddlarray
and has two or more nonsingleton dimensions, then its size must match the size ofY
and the function uses the same format asY
. Alternatively, to specify the weights format, use theWeightsFormat
option.
Name-Value Arguments
Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN
, whereName
is the argument name andValue
is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.
Example:loss = l2loss(Y,targets,Reduction="none")
specifies to compute the L2loss without reducing the output to a scalar
Mask
—Mask indicating which elements to include for loss computation
dlarray
|逻辑阵列|numeric array
Mask indicating which elements to include for loss computation, specified as adlarray
object, a logical array, or a numeric array with the same size asY
.
The function includes and excludes elements of the input data for loss computation when the corresponding value in the mask is 1 and 0, respectively.
IfMask
is a formatteddlarray
object, then its format must match that ofY
. IfMask
is not a formatteddlarray
object, then the function uses the same format asY
.
If you specify theDataFormat
option, then the function also uses the specified format for the mask.
的大小each dimension ofMask
must match the size of the corresponding dimension inY
. The default value is a logical array of ones.
Tip
Formatteddlarray
objects automatically permute the dimensions of the underlying data to have this order:"S"
(spatial),"C"
(channel),"B"
(batch),"T"
(time), and"U"
(unspecified). For example,dlarray
objects automatically permute the dimensions of data with format"TSCSBS"
to have format"SSSCBT"
.
To ensure that the dimensions ofY
and the mask are consistent, whenY
is a formatteddlarray
, also specify the mask as a formatteddlarray
.
Reduction
—Mode for reducing array of loss values
"sum"
(default) |"none"
Mode for reducing the array of loss values, specified as one of the following:
NormalizationFactor
—Divisor for normalizing reduced loss
"batch-size"
(default) |"all-elements"
|"mask-included"
|"none"
Divisor for normalizing the reduced loss whenReduction
is"sum"
, specified as one of the following:
"batch-size"
— Normalize the loss by dividing it by the number of observations inX
."all-elements"
— Normalize the loss by dividing it by the number of elements ofX
."mask-included"
——正常损失损失值除以by the number of included elements specified by the mask for each observation independently. To use this option, you must specify a mask using theMask
option."none"
— Do not normalize the loss.
DataFormat
—Dimension order of unformatted data
character vector|string scalar
Dimension order of unformatted input data, specified as a character vector or string scalarFMT
that provides a label for each dimension of the data.
When you specify the format of adlarray
object, each character provides a label for each dimension of the data and must be one of the following:
"S"
— Spatial"C"
— Channel"B"
— Batch (for example, samples and observations)"T"
— Time (for example, time steps of sequences)"U"
— Unspecified
You can specify multiple dimensions labeled"S"
or"U"
. You can use the labels"C"
,"B"
, and"T"
at most once.
You must specifyDataFormat
when the input data is not a formatteddlarray
.
Data Types:char
|string
WeightsFormat
—Dimension order of weights
character vector|string scalar
Dimension order of the weights, specified as a character vector or string scalar that provides a label for each dimension of the weights.
When you specify the format of adlarray
object, each character provides a label for each dimension of the data and must be one of the following:
"S"
— Spatial"C"
— Channel"B"
— Batch (for example, samples and observations)"T"
— Time (for example, time steps of sequences)"U"
— Unspecified
You can specify multiple dimensions labeled"S"
or"U"
. You can use the labels"C"
,"B"
, and"T"
at most once.
You must specifyWeightsFormat
whenweights
is a numeric vector andY
has two or more nonsingleton dimensions.
Ifweights
is not a vector, or bothweights
andY
are vectors, then default value ofWeightsFormat
is the same as the format ofY
.
Data Types:char
|string
Output Arguments
loss
— L2loss
dlarray
L2loss, returned as an unformatteddlarray
. The outputloss
is an unformatteddlarray
with the same underlying data type as the inputY
.
的大小loss
depends on theReduction
option.
Algorithms
L2 Loss
The L2loss operation computes the L2loss (based on the squared L2norm) given network predictions and target values. When theReduction
option is"sum"
and theNormalizationFactor
option is"batch-size"
, the computed value is known as the mean squared error (MSE).
For each elementYjof the input, thel2loss
function computes the corresponding element-wise loss values using
whereYjis a predicted value andTjis the corresponding target value.
减少loss values to a scalar, the function then reduces the element-wise loss using the formula
whereNis the normalization factor,mjis the mask value for elementj, andwjis the weight value for elementj.
If you do not opt to reduce the loss, then the function applies the mask and the weights to the loss values directly:
Extended Capabilities
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
Usage notes and limitations:
When at least one of the following input arguments is a
gpuArray
or adlarray
with underlying data of typegpuArray
, this function runs on the GPU:Y
targets
weights
Mask
For more information, seeRun MATLAB Functions on a GPU(Parallel Computing Toolbox).
Version History
Introduced in R2021b
Open Example
You have a modified version of this example. Do you want to open this example with your edits?
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select:.
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina(Español)
- Canada(English)
- United States(English)
Europe
- Belgium(English)
- Denmark(English)
- Deutschland(Deutsch)
- España(Español)
- Finland(English)
- France(Français)
- Ireland(English)
- Italia(Italiano)
- Luxembourg(English)
- Netherlands(English)
- Norway(English)
- Österreich(Deutsch)
- Portugal(English)
- Sweden(English)
- Switzerland
- United Kingdom(English)