An error occurred while Defining Custom Classification Output Layer:Error using 'backwardLoss' in Layer sseClassificationLayer. The function threw an error and could not be executed.

3 Ansichten (letzte 30 Tage)
Here is my code:
classdef sseClassificationLayer < nnet.layer.ClassificationLayer
% Example custom classification layer with sum of squares error loss.
methods
function layer = sseClassificationLayer(name)
% layer = sseClassificationLayer(name) creates a sum of squares
% error classification layer and specifies the layer name.
% Set layer name.
layer.Name = name;
% Set layer description.
layer.Description = 'Sum of squares error';
end
function loss = forwardLoss(~, Y, T)
% loss = forwardLoss(layer, Y, T) returns the SSE loss between
% the predictions Y and the training targets T.
% Calculate sum of squares.
sumSquares = sum((Y-T).^2);
% Take mean over mini-batch.
N = size(Y,4);
loss = sum(sumSquares)/N;
end
function dLdY = backwardLoss(~, ~, ~)
% (Optional) Backward propagate the derivative of the loss
% function.
%
% Inputs:
% layer - Output layer
% Y – Predictions made by network
% T – Training targets
%
% Output:
% dLdY - Derivative of the loss with respect to the
% predictions Y
% Layer backward loss function goes here.
N = size(Y,4);
dLdY = 2*(Y-T)/N;
end
end
end

Antworten (1)

Ayush Aniket
Ayush Aniket am 15 Mai 2024
Hi 文 王 ,
The error occurs due to missing input parameters of the 'backwardLoss' method in your custom classification layer. The 'backwardLoss' method should accept the same input arguments as 'forwardLoss', specifically the layer itself, the predictions 'Y', and the training targets 'T'. However, in your definition of backwardLoss, you've omitted 'Y' and 'T' from the parameter list.
The correct definition would be as shown below:
function dLdY = backwardLoss(~, Y, T)
% Backward propagate the derivative of the loss function.
%
% Inputs:
% Y – Predictions made by network
% T – Training targets
%
% Output:
% dLdY - Derivative of the loss with respect to the
% predictions Y
% Calculate the number of observations (assuming the last dimension of Y is the batch size)
N = size(Y, 4);
% Compute the gradient of the loss function
dLdY = 2 * (Y - T) / N;
end

Kategorien

Mehr zu Image Data Workflows finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by