| 3 | |
| 4 | |
| 5 | class LogisticRegression: |
| 6 | def __init__(self, penalty="l2", gamma=0, fit_intercept=True): |
| 7 | r""" |
| 8 | A simple binary logistic regression model fit via gradient descent on |
| 9 | the penalized negative log likelihood. |
| 10 | |
| 11 | Notes |
| 12 | ----- |
| 13 | In simple binary logistic regression, the entries in a binary target |
| 14 | vector :math:`\mathbf{y} = (y_1, \ldots, y_N)` are assumed to have been |
| 15 | drawn from a series of independent Bernoulli random variables with |
| 16 | expected values :math:`p_1, \ldots, p_N`. The binary logistic regession |
| 17 | model models the logit of these unknown mean parameters as a linear |
| 18 | function of the model coefficients, :math:`\mathbf{b}`, and the |
| 19 | covariates for the corresponding example, :math:`\mathbf{x}_i`: |
| 20 | |
| 21 | .. math:: |
| 22 | |
| 23 | \text{Logit}(p_i) = |
| 24 | \log \left( \frac{p_i}{1 - p_i} \right) = \mathbf{b}^\top\mathbf{x}_i |
| 25 | |
| 26 | The model predictions :math:`\hat{\mathbf{y}}` are the expected values |
| 27 | of the Bernoulli parameters for each example: |
| 28 | |
| 29 | .. math:: |
| 30 | |
| 31 | \hat{y}_i = |
| 32 | \mathbb{E}[y_i \mid \mathbf{x}_i] = \sigma(\mathbf{b}^\top \mathbf{x}_i) |
| 33 | |
| 34 | where :math:`\sigma` is the logistic sigmoid function :math:`\sigma(x) |
| 35 | = \frac{1}{1 + e^{-x}}`. Under this model, the (penalized) negative log |
| 36 | likelihood of the targets **y** is |
| 37 | |
| 38 | .. math:: |
| 39 | |
| 40 | - \log \mathcal{L}(\mathbf{b}, \mathbf{y}) = -\frac{1}{N} \left[ |
| 41 | \left( |
| 42 | \sum_{i=0}^N y_i \log(\hat{y}_i) + |
| 43 | (1-y_i) \log(1-\hat{y}_i) |
| 44 | \right) - R(\mathbf{b}, \gamma) |
| 45 | \right] |
| 46 | |
| 47 | where |
| 48 | |
| 49 | .. math:: |
| 50 | |
| 51 | R(\mathbf{b}, \gamma) = \left\{ |
| 52 | \begin{array}{lr} |
| 53 | \frac{\gamma}{2} ||\mathbf{b}||_2^2 & :\texttt{ penalty = 'l2'}\\ |
| 54 | \gamma ||\mathbf{b}||_1 & :\texttt{ penalty = 'l1'} |
| 55 | \end{array} |
| 56 | \right. |
| 57 | |
| 58 | is a regularization penalty, :math:`\gamma` is a regularization weight, |
| 59 | `N` is the number of examples in **y**, :math:`\hat{y}_i` is the model |
| 60 | prediction on example *i*, and **b** is the vector of model |
| 61 | coefficients. |
| 62 | |