The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← AI 301 — Machine Learning, Neural Networks and Language

Weeks 3–5

Linear and logistic models, regularization and calibration

Learning objectives

  • Explain and trace the mechanisms in linear and logistic models, regularization and calibration.
  • Apply the method to the worked example and changed-condition exercise.
  • Identify assumptions, failure cases and the evidence needed to justify a result.

Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.

A linear regression model forms a weighted sum of features plus an intercept. Least-squares fitting minimizes squared residuals, emphasizing large errors. The coefficient is conditional on the model's other features and data construction; it is not automatically a causal effect. Outliers, correlated features and omitted nonlinear structure can make naive interpretation misleading.

Logistic regression maps a linear score through a sigmoid to a number between zero and one for a binary target. A probability-like output still needs calibration evaluation. Thresholding at 0.5 is a policy choice, not a mathematical obligation. When false negatives and false positives have different consequences, threshold selection should reflect development evidence and the decision context.

Regularization penalizes some forms of model complexity. L2 discourages large weights; L1 can promote sparse solutions. Feature scale affects penalty interpretation, so scaling belongs within the training pipeline when needed. Regularization strength is chosen without consulting the reserved test set. A simpler model can generalize better, but excessive regularization can underfit. Inspect residual patterns or calibration curves rather than relying on one average score.

Worked reasoning The two branches evaluate the same sigmoid identity while avoiding exp(1000) overflow for very negative input. A score of zero maps to 0.5, but does not prove that half of such cases are truly positive. Calibration is an empirical property under a defined population. Numerical stability and statistical validity are separate requirements.

Extended teaching and laboratory

A logistic model computes a score z, transforms it with a sigmoid and applies a chosen threshold for a decision. These are three distinct objects. A sigmoid maps numbers into (0,1), but that range alone does not establish calibration. A set of predictions near .8 is calibrated only if the relevant outcome occurs about 80% of the time in the defined setting, subject to sampling uncertainty.

Changing the threshold changes sensitivity and false alerts without changing the fitted probability model. Regularization constrains fitting; it does not select a universally correct operational threshold. Use numerically stable sigmoid evaluation and assess calibration on data independent of fitting.

Worked problem Four predicted probabilities are [.2,.4,.7,.9] and outcomes are [0,1,1,0]. Compare confusion matrices at thresholds .5 and .8, defining positive as probability≥threshold.

Step-by-step reasoning 1. At .5, the last two are predicted positive: TP=1, FP=1, FN=1, TN=1.

  1. At .8, only .9 is positive: TP=0, FP=1, FN=2, TN=1. Precision becomes 0/1=0 and recall 0/2=0.
  1. This small example shows that a higher threshold does not guarantee an improved empirical precision on every finite dataset.
  1. The .9 error does not alone prove global miscalibration. Assess calibration across enough cases and relevant subgroups rather than interpreting a single probability as certainty.

Fit an objective whose scaling you can explain

The preserved logistic performance study already derives mean binary cross-entropy gradients and implements stable loss. Here extend that calculation to regularization and multiclass fitting. A fitted model is the minimizer of an explicit objective, or the result of a specified approximate optimization procedure. A model-family name alone does not identify either. State whether loss is summed or averaged, which coefficients are penalized and how the intercept is treated.

For rows xᵢ and numerical targets yᵢ, define rᵢ=b+w·xᵢ−yᵢ and J=(1/(2n))Σrᵢ²+(λ/2)Σwⱼ². The intercept is unpenalized in this definition. Differentiation gives ∂J/∂b=Σrᵢ/n and ∂J/∂wⱼ=Σrᵢxᵢⱼ/n+λwⱼ. A simultaneous gradient step subtracts a chosen rate times these derivatives, all evaluated at the same old parameters. Dividing the data loss by n while retaining an unchanged penalty changes their relative importance; a library's alpha is not automatically this λ.

Take centered fictional observations x=[−1,1], y=[−2,2], with intercept fixed at zero. Mean half-squared loss becomes (w−2)²/2. With λ=1, J=(w−2)²/2+w²/2. Its derivative is 2w−2 and second derivative is 2, so the unique minimizer is w=1. Without the penalty it is w=2. The penalty deliberately trades a larger training residual for a smaller coefficient; it does not prove that w=1 predicts a new population better. Development evaluation must decide whether that tradeoff helps the actual task.

Why an absolute penalty can create an exact zero

Replace the squared penalty with λ|w|. Away from zero, the derivative is w−2+λ for w>0 and w−2−λ for w<0. At zero, |w| has subgradients in [−1,1]. Zero minimizes the convex objective when the negative smooth-loss gradient can be balanced by λ times that interval. With λ=.5, the positive solution is w=1.5. With λ=3, zero satisfies the subgradient condition and is the optimum. More generally, if the smooth term is (w−a)²/2, the solution is sign(a)max(|a|−λ,0), the soft-threshold rule. This derivation uses the explicit one-coordinate normalization; other loss scalings require corresponding thresholds.

Feature units alter the penalty. Expressing x in minutes instead of hours divides its corresponding coefficient by sixty to preserve predictions, while an unchanged coefficient penalty then changes its numerical contribution. Fit scaling within each training fold when appropriate. Correlated inputs can distribute a predictive relationship across different coefficients; sparse selection is not a causal discovery method. An elastic-net objective combines stated absolute and squared penalties. Its mixture and strength remain development choices, not permission to inspect final test outcomes repeatedly.

Binary and multiclass probabilities

For binary y, a logistic score z=b+w·x gives p=1/(1+exp(−z)). Negative log-likelihood is −y ln p−(1−y)ln(1−p). Using dp/dz=p(1−p) and the chain rule simplifies its score derivative to p−y. Thus L2-penalized mean loss has coefficient derivative Σ(pᵢ−yᵢ)xᵢⱼ/n+λwⱼ, with the intercept derivative lacking the penalty. Compare this with the already preserved stable implementation. Numerical clipping may change extreme calculations; it is not a proof that every mathematical derivative remains exact at a clipping boundary.

For K mutually exclusive classes, give each class a score zₖ=bₖ+wₖ·x. Softmax probabilities are exp(zₖ−M)/Σexp(zⱼ−M), where M is the largest finite score. For target class t, loss is −ln pₜ, and its derivative with respect to score k is pₖ−1[k=t]. With one feature x=2, scores [0,ln 2,0] and target class 0, probabilities are [1/4,1/2,1/4]. Loss is ln 4, score gradients [−3/4,1/2,1/4], and coefficient gradients [−3/2,1,1/2] before regularization. Their score-gradient sum is zero because adding the same constant to every score leaves probabilities unchanged. Parameter identification and regularization conventions therefore deserve attention even when predicted probabilities are well defined.

A probability vector and an action are separate outputs. The retained threshold and expected-value exercises show why .5 is not a universal operating rule. Calibration can be fitted using a separate development partition or a suitable cross-validation procedure; evaluating a calibrator on the same labels used to fit it gives optimistic evidence. Brier loss averages (p−y)², while log loss heavily penalizes confident wrong forecasts. Reliability bins need their case counts and empty-bin policy; a bin with no cases supplies no observed rate. Neither calibration nor a smaller loss identifies an intervention's causal benefit.

Optional changed objective and complete reasoning

Change the centered numerical targets to [−1,1], keeping x=[−1,1]. For the squared penalty λ=1, the derivative is (w−1)+w, so w=1/2. For the absolute penalty λ=.5, soft thresholding also gives w=1/2; agreement in this record does not make the penalties identical. At λ=2, the squared-penalty solution is 1/3, while the absolute-penalty solution is zero. Change the multiclass target to class 2 without changing scores: loss remains ln 4, but score gradients become [1/4,1/2,−3/4] and coefficient gradients [1/2,1,−3/2]. Identical loss values need not have identical gradients. If a learner sums rather than averages a two-row data loss, retaining the original λ changes the optimum. Multiply the entire objective by two, including its penalty, to preserve its minimizer.

Optional criteria, one point each: define normalization and penalized parameters; derive and solve both one-coordinate objectives; reconcile multiclass shapes, probabilities and gradients; preserve fitting/calibration/final-evaluation boundaries. Explain all four for four points. These synthetic calculations do not establish observed learner competence.

Apply the idea

Four predicted probabilities are [.2,.4,.7,.9] and outcomes are [0,1,1,0]. Compare confusion matrices at thresholds .5 and .8, defining positive as probability≥threshold.

A stakeholder demands that every .9 prediction be correct. Explain the probability misconception and propose an evaluation.

Read the worked reasoning

A calibrated .9 forecast permits about 10% negatives in the corresponding population; it is not a deterministic guarantee. Evaluate reliability across probability bins with counts and uncertainty, inspect subgroup differences, and assess whether the deployment distribution matches evaluation. If errors have severe consequences, add review or abstention rather than promising certainty from a threshold.

Check understanding

What does regularization address?

  1. A guarantee that every coefficient is causal
    Feedback

    Predictive fitting does not establish causal identification.

  2. Automatic correction of leaked features
    Feedback

    Leakage requires correcting the data and evaluation design.

  3. A tradeoff between fitting data and constraining model complexity
    Feedback

    Penalty strength can reduce variance while introducing bias.

Further reading

Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.

Use the preserved original investigation and connected Academy preparation/application below. Compare your reasoning with its optional complete model. Historical source directions remain in immutable edition4.

My learning →