Explain how backpropagation works in a deep neural network, specifically detailing the mathematical derivation of the gradients.