In scikit-learn, the penalty and C parameters modify the standard cost function (loss function) of the LogisticRegression class during the optimization process. They do not change the core predictive sigmoid formula itself, but they directly dictate how the model weights (w) are calculated during training.
The core math breaks down as follows:
Without any penalty (penalty=None), a binary logistic regression model optimizes the standard log-loss (binary cross-entropy) cost function, denoted as L(w):
Where:
- yi is the true label (0 or 1).
- ŷi is the predicted probability generated by the sigmoid function:
penalty Alters the Formula
The penalty parameter adds a regularization term to the cost function to restrict the size of the coefficients and prevent overfitting. It determines the shape of this constraint:
Adds the squared magnitude of coefficients (L2 norm).
Adds the absolute magnitude of coefficients (L1 norm), which drives unimportant weights to exactly zero to create a sparse model.
C Alters the Formula
In traditional statistics, regularization strength is controlled by a parameter named λ (lambda), where a larger λ means more aggressive penalty enforcement:
Instead of λ, scikit-learn uses C, which is defined as the inverse of regularization strength:
Crucially, scikit-learn multiplies C by the loss term rather than the penalty term. The objective function that scikit-learn minimizes looks like this:
C
| Value of C | Regularization Strength | Effect on the Objective Function | Model Behavior |
|---|---|---|---|
| Small C (e.g., 0.01) | High | The penalty term dominates; the data loss L(w) is largely ignored. | Coefficients shrink heavily toward zero; protects against overfitting. |
| Large C (e.g., 1000) | Low | The data loss L(w) dominates; the penalty term is ignored. | Model prioritizes fitting the training data exactly; risks overfitting. |
Although C is defined as the inverse of the regularization strength (C = 1 / λ), scikit-learn's optimization objective is implemented as:
As a result:
- A smaller C places relatively less emphasis on fitting the training data and therefore results in stronger regularization.
- A larger C places greater emphasis on minimizing the data loss, resulting in weaker regularization.
No comments:
Post a Comment