function [dZ, dT] = internal_crossentropyBackward(dZ, X, T, observationDim, hasIndependentTargetCategories)
% This function is undocumented and will change in a future release.

%   Copyright 2019 The MathWorks, Inc.

N = size(X, observationDim);
P = nnet.internal.cnn.util.boundAwayFromZero(X);
dX = -dZ.*T./(P.*N); % categorical cross-entropy backward

if nargout > 1
    dT = -dZ.*log(P)./N;
end

if hasIndependentTargetCategories
    OneMinusX = nnet.internal.cnn.util.boundAwayFromZero(1 - X);
    dX = dX + dZ.*(1-T)./(OneMinusX.*N); % binary cross-entropy backward
    if nargout > 1
        dT = dT + dZ.*log(OneMinusX)./N;
    end
end
 
dZ = dX;

end

