Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for instance weights in dagnn.Loss #1112

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions matlab/+dagnn/Loss.m
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,44 @@

methods
function outputs = forward(obj, inputs, params)
outputs{1} = vl_nnloss(inputs{1}, inputs{2}, [], 'loss', obj.loss, obj.opts{:}) ;

% If there are 3 inputs, the third input should contain sample
% specific weights
weights = ones(size(inputs{2}));
i = find(strcmpi(obj.opts,'instanceWeights'));
if numel(inputs)==3
weights = inputs{3};
elseif ~isempty(i)
weights = obj.opts{i+1};
end

outputs{1} = vl_nnloss(inputs{1}, inputs{2}, [], 'loss', obj.loss, 'InstanceWeights', weights, obj.opts{:}) ;
obj.accumulateAverage(inputs, outputs);
end

function accumulateAverage(obj, inputs, outputs)
if obj.ignoreAverage, return; end;
if obj.ignoreAverage, return; end
n = obj.numAveraged ;
m = n + size(inputs{1}, 1) * size(inputs{1}, 2) * size(inputs{1}, 4);
obj.average = bsxfun(@plus, n * obj.average, gather(outputs{1})) / m ;
obj.numAveraged = m ;
end

function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)
derInputs{1} = vl_nnloss(inputs{1}, inputs{2}, derOutputs{1}, 'loss', obj.loss, obj.opts{:}) ;

% If there are 3 inputs, the third input should contain sample
% specific weights
weights = ones(size(inputs{2}));
i = find(strcmpi(obj.opts,'instanceWeights'));
if numel(inputs)==3
weights = inputs{3};
derInputs{3} = [];
elseif ~isempty(i)
weights = obj.opts{i+1};
derInputs{3} = [];
end

derInputs{1} = vl_nnloss(inputs{1}, inputs{2}, derOutputs{1}, 'loss', obj.loss, 'InstanceWeights', weights, obj.opts{:}) ;
derInputs{2} = [] ;
derParams = {} ;
end
Expand Down