Walk me through the mathematical formulation of logistic regression and explain how the loss function is optimized.