Natural Language Processing/Logistic Regression
15 / 67

02/2024Natural Language Processing

Logistic Regression

A from-scratch logistic-regression text classifier: features to a sigmoid, a linear decision boundary, trained by gradient descent on the cross-entropy loss.

╌╌╌╌

A text classifier built on logistic regression, implemented from scratch. Where naive Bayes is generative — it models how documents are produced — logistic regression is discriminative: it learns a decision boundary directly, weighting features by how much each one moves the answer.

The model runs a linear score through a sigmoid. Each document becomes a feature vector (word counts and indicators). The model scores it with a weight vector and bias , then squashes the score to a probability with the logistic function:

The output lies in and is read as the probability of the positive class.

The logistic function maps the linear score to a probability. Thresholding at (dashed) splits the prediction, and since exactly when , the boundary sits at (dot).

The decision rule thresholds that probability at to get the label. Because exactly when , the boundary is the hyperplane : the classifier is linear even though the probability it reports is not.

Training uses cross-entropy as its loss, maximizing the likelihood of the training labels, equivalently minimizing the average negative log-likelihood. For a single example the loss is

This penalizes a confident wrong prediction sharply and a correct one lightly. It is convex in , so gradient descent reaches the global optimum.

Squared error would also measure the miss, but paired with a sigmoid it is non-convex in , and its gradient carries a factor of . That factor collapses toward zero whenever the model is saturated — confidently near or — so a confidently wrong prediction produces almost no gradient and learning stalls exactly where it should correct hardest. Cross-entropy is designed to cancel that factor.

The reward is a clean gradient: with cross-entropy the term cancels, and the gradient with respect to the weights is just the prediction error times the features:

Descent repeats over the training set until the loss stops falling. An penalty on the weights adds a term to the gradient, keeping weights from blowing up on rare features that appear in only one class. Multi-class problems use the softmax generalization, one weight vector per class.

You can read the full report.

References

  1. Project repository
  2. Reference notes: Logistic Regression
  3. Reference notes: Evaluating Classifiers
  4. Reference notes: Numerical Optimization and Gradient Descent

╌╌ END ╌╌