5.6.2Machine Learning (Aerospace Applications)

Logistic regression — sigmoid, cross-entropy loss

2,824 words13 min readdifficulty · medium6 backlinks

Overview

Logistic regression is the fundamental algorithm for binary classification problems in aerospace ML. Instead of predicting continuous values (like altitude), we predict probabilities (like "will this component fail?" or "is this satellite image cloudy?"). It maps any real-valued input to a probability between 0 and 1 using the sigmoid function, then trains by minimizing cross-entropy loss.

Figure — Logistic regression — sigmoid, cross-entropy loss

Core Components

The sigmoid function does exactly this. Think of it as a "probability translator" — it takes your model's raw confidence score and converts it to a valid probability.


1. The Sigmoid Function

Derivation from First Principles:

Why this specific form? Start with the odds ratio. If probability of class 1 is pp, the odds are: odds=p1p\text{odds} = \frac{p}{1-p}

In logistic regression, we assume the log-odds are linear in features: log(p1p)=z=wTx+b\log\left(\frac{p}{1-p}\right) = z = \mathbf{w}^T \mathbf{x} + b

Why? This is the key assumption — the effect of features is multiplicative on odds, but additive on log-odds. Now solve for pp:

p1p=ez\frac{p}{1-p} = e^z p=ez(1p)p = e^z(1-p) p=ezpezp = e^z - pe^z p(1+ez)=ezp(1 + e^z) = e^z p=ez1+ezp = \frac{e^z}{1 + e^z}

Multiply numerator and denominator by eze^{-z}: p=1ez+1=σ(z)p = \frac{1}{e^{-z} + 1} = \sigma(z)

Key Properties:

  • σ(0)=0.5\sigma(0) = 0.5 (decision boundary)
  • σ(z)1\sigma(z) \to 1 as zz \to \infty
  • σ(z)0\sigma(z) \to 0 as zz \to -\infty
  • Derivative: σ(z)=σ(z)(1σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z)) (convenient for backprop!)

Derivative Derivation: ddzσ(z)=ddz(11+ez)\frac{d}{dz}\sigma(z) = \frac{d}{dz}\left(\frac{1}{1+e^{-z}}\right) Using chain rule with u=1+ezu = 1 + e^{-z}: =1u2(ez)=ez(1+ez)2= -\frac{1}{u^2} \cdot (-e^{-z}) = \frac{e^{-z}}{(1+e^{-z})^2} =11+ezez1+ez=σ(z)ez1+ez= \frac{1}{1+e^{-z}} \cdot \frac{e^{-z}}{1+e^{-z}} = \sigma(z) \cdot \frac{e^{-z}}{1+e^{-z}} =σ(z)(111+ez)=σ(z)(1σ(z))= \sigma(z) \cdot \left(1 - \frac{1}{1+e^{-z}}\right) = \sigma(z)(1-\sigma(z))

Why this step? The derivative form makes gradient calculations elegant — no exponentials in the gradient updates!



2. Cross-Entropy Loss

Cross-entropy from information theory does exactly this.

For NN training examples: J(w,b)=1Ni=1N[y(i)log(y^(i))+(1y(i))log(1y^(i))]J(\mathbf{w}, b) = -\frac{1}{N}\sum_{i=1}^{N} [y^{(i)} \log(\hat{y}^{(i)}) + (1-y^{(i)}) \log(1-\hat{y}^{(i)})]

Derivation from Maximum Likelihood:

Assume each label yiy_i is drawn from Bernoulli distribution with probability y^i\hat{y}_i: P(yiy^i)=y^iyi(1y^i)1yiP(y_i | \hat{y}_i) = \hat{y}_i^{y_i} (1-\hat{y}_i)^{1-y_i}

Why this form? When yi=1y_i=1, this is y^i\hat{y}_i. When yi=0y_i=0, this is 1y^i1-\hat{y}_i. Perfect compact notation.

Likelihood of all data (assuming independence): L=i=1Ny^iyi(1y^i)1yiL = \prod_{i=1}^N \hat{y}_i^{y_i} (1-\hat{y}_i)^{1-y_i}

Take log-likelihood (products become sums, easier to optimize): logL=i=1N[yilogy^i+(1yi)log(1y^i)]\log L = \sum_{i=1}^N [y_i \log \hat{y}_i + (1-y_i) \log(1-\hat{y}_i)]

Maximize log-likelihood = minimize negative log-likelihood: J=1NlogL=1Ni=1N[yilogy^i+(1yi)log(1y^i)]J = -\frac{1}{N} \log L = -\frac{1}{N}\sum_{i=1}^{N} [y_i \log \hat{y}_i + (1-y_i) \log(1-\hat{y}_i)]

Why this step? Maximizing likelihood finds parameters most consistent with observed data. Negative makes it a loss to minimize.

Intuition Check:

  • If y=1y=1 and y^=0.9\hat{y}=0.9: loss = log(0.9)=0.105-\log(0.9) = 0.105 (small)
  • If y=1y=1 and y^=0.1\hat{y}=0.1: loss = log(0.1)=2.303-\log(0.1) = 2.303 (large!)
  • If y=0y=0 and y^=0.9\hat{y}=0.9: loss = log(0.1)=2.303-\log(0.1) = 2.303 (large!)

Jwj=1Ni=1N(y^(i)y(i))xj(i)\frac{\partial J}{\partial w_j} = \frac{1}{N}\sum_{i=1}^{N} (\hat{y}^{(i)} - y^{(i)}) x_j^{(i)}

Derivation:

For single example, chain rule: Lwj=Ly^y^zzwj\frac{\partial L}{\partial w_j} = \frac{\partial L}{\partial \hat{y}} \cdot \frac{\partial \hat{y}}{\partial z} \cdot \frac{\partial z}{\partial w_j}

Step 1: Loss derivative w.r.t. prediction Ly^=yy^+1y1y^\frac{\partial L}{\partial \hat{y}} = -\frac{y}{\hat{y}} + \frac{1-y}{1-\hat{y}}

Why? Derivative of ylogy^-y\log\hat{y} is y/y^-y/\hat{y}, derivative of (1y)log(1y^)-(1-y)\log(1-\hat{y}) is (1y)/(1y^)(1-y)/(1-\hat{y}).

Step 2: Sigmoid derivative (we derived earlier) y^z=y^(1y^)\frac{\partial \hat{y}}{\partial z} = \hat{y}(1-\hat{y})

Step 3: Linear part derivative zwj=xj\frac{\partial z}{\partial w_j} = x_j

Combine: Lwj=[yy^+1y1y^]y^(1y^)xj\frac{\partial L}{\partial w_j} = \left[-\frac{y}{\hat{y}} + \frac{1-y}{1-\hat{y}}\right] \cdot \hat{y}(1-\hat{y}) \cdot x_j =[y(1y^)+(1y)y^]xj= \left[-y(1-\hat{y}) + (1-y)\hat{y}\right] x_j =[y+yy^+y^yy^]xj= [-y + y\hat{y} + \hat{y} - y\hat{y}] x_j =(y^y)xj= (\hat{y} - y) x_j

Why this step? The cross-entropy and sigmoid derivatives perfectly cancel the complex fractions, leaving a beautifully simple gradient!

Average over NN examples: Jwj=1Ni=1N(y^(i)y(i))xj(i)\frac{\partial J}{\partial w_j} = \frac{1}{N}\sum_{i=1}^{N} (\hat{y}^{(i)} - y^{(i)}) x_j^{(i)}

Gradient descent update: wj:=wjαJwjw_j := w_j - \alpha \frac{\partial J}{\partial w_j}


Worked Examples

Problem: Predict if a turbine blade will fail based on operating hours. Dataset:

  • x(1)=1000x^{(1)} = 1000 hours, y(1)=0y^{(1)} = 0 (no failure)
  • x(2)=5000x^{(2)} = 5000 hours, y(2)=1y^{(2)} = 1 (failure)

Initialize: w=0.0001w = 0.0001, b=0.3b = -0.3 (features unnormalized for illustration; small ww chosen so zz stays in a sane range).

Forward Pass (Example 2): z(2)=wx(2)+b=0.000150000.3=0.50.3=0.2z^{(2)} = w \cdot x^{(2)} + b = 0.0001 \cdot 5000 - 0.3 = 0.5 - 0.3 = 0.2 y^(2)=σ(0.2)=11+e0.2=11.2214=0.5498\hat{y}^{(2)} = \sigma(0.2) = \frac{1}{1 + e^{-0.2}} = \frac{1}{1.2214} = 0.5498

Why this step? We compute the linear combination first, then pass through sigmoid to get probability. Note we deliberately use w=0.0001w=0.0001 throughout so that zz does not saturate the sigmoid.

Loss for this example: L(2)=[1log(0.5498)+0log(0.4502)]=log(0.5498)=0.598L^{(2)} = -[1 \cdot \log(0.5498) + 0 \cdot \log(0.4502)] = -\log(0.5498) = 0.598

Gradient: L(2)w=(y^(2)y(2))x(2)=(0.54981)5000=2251\frac{\partial L^{(2)}}{\partial w} = (\hat{y}^{(2)} - y^{(2)}) \cdot x^{(2)} = (0.5498 - 1) \cdot 5000 = -2251

Why negative? Prediction is too low (0.55 vs 1), so we need to increase ww to increase prediction. Negative gradient means descent will add to ww.

Update (α=106\alpha = 10^{-6}): Because the raw feature (x=5000x=5000) is large, the gradient is large, so we pick a tiny learning rate to avoid overshooting: w:=0.0001106(2251)=0.0001+0.002251=0.002351w := 0.0001 - 10^{-6} \cdot (-2251) = 0.0001 + 0.002251 = 0.002351

Why this step? With unnormalized features the gradient magnitude scales with xx, so α\alpha must be small. (In practice we normalize features — see Mistake 2 — which lets us use a larger, more stable α\alpha.) After the update ww increases, making the model predict a higher probability for high operating hours.


Problem: Binary classifier for cloud presence. Features: average pixel brightness (x1x_1), brightness variance (x2x_2).

Training point: x=[180,45]\mathbf{x} = [180, 45], y=1y = 1 (cloudy) Parameters: w=[0.01,0.02]\mathbf{w} = [0.01, -0.02], b=1.5b = -1.5

Prediction: z=0.01(180)+(0.02)(45)1.5=1.80.91.5=0.6z = 0.01(180) + (-0.02)(45) - 1.5 = 1.8 - 0.9 - 1.5 = -0.6 y^=σ(0.6)=11+e0.6=11+1.8221=12.8221=0.3543\hat{y} = \sigma(-0.6) = \frac{1}{1 + e^{0.6}} = \frac{1}{1 + 1.8221} = \frac{1}{2.8221} = 0.3543

Why this step? Negative zz means model thinks "not cloudy" (prob < 0.5), but truth is cloudy (y=1y=1) — error!

Loss: L=[1log(0.3543)]=1.0376L = -[1 \cdot \log(0.3543)] = 1.0376

Gradients: Lw1=(y^y)x1=(0.35431)(180)=116.23\frac{\partial L}{\partial w_1} = (\hat{y} - y) x_1 = (0.3543 - 1)(180) = -116.23 Lw2=(0.35431)(45)=29.06\frac{\partial L}{\partial w_2} = (0.3543 - 1)(45) = -29.06

Why this step? Both gradients are negative because prediction is too low. Updates will increase both weights to make the model more "pro-cloudy" for these feature values.


Common Mistakes

Wrong Thinking: "Sigmoid gives 0.7, so output is 0.7?"

Why It Feels Right: Sigmoid outputs a number, so use it directly.

The Fix: y^\hat{y} is a probability, not the final class. Apply threshold:

prediction_class = 1 if y_hat >= 0.5 else 0

For aerospace safety applications, you might use threshold 0.3 (prefer false alarms over missed failures).

Why This Works: Probabilities inform decisions based on cost/benefit. A 0.7 probability doesn't mean "70% of the answer is class 1" — it means "70% confidence in class 1."


Wrong Code:

# x1 in [0, 1000] hours, x2 in [0, 1] boolean
z = w1 * x1 + w2 * x2 + b

Why It Fails: w1w_1 will dominate because x1x_1 scale is huge. Gradient updates become unstable and force you to use a tiny learning rate (as we saw in Example 1).

The Fix: Standardize features: xjnorm=xjμjσjx_j^{\text{norm}} = \frac{x_j - \mu_j}{\sigma_j}

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

Why This Works: All features contribute equally. Gradients have similar magnitudes, making optimization converge faster and letting you use a larger, stable learning rate.


Wrong Math: Computing L=[ylogy]L = -[y \log y] instead of L=[ylogy^]L = -[y \log \hat{y}]

Why It Happens: Confusing true label yy with predicted probability y^\hat{y}.

The Fix: Cross-entropy measures divergence between:

  • True distribution: yy (either 0 or 1)
  • Predicted distribution: y^\hat{y} (probability from sigmoid)

Always: L=[ylogy^+(1y)log(1y^)]L = -[y \log \hat{y} + (1-y)\log(1-\hat{y})]


Study Aids

Cross-Entropy: "Punish Confident Wrongs" log-\log grows huge as probability → 0. If model is confident (high y^\hat{y}) but wrong (y=0y=0), loss explodes.


Recall

Feynman Explanation (Explain to a 12-Year-Old) Imagine you're guessing if a coin is heads or tails based on how shiny it is. You can't just say "yes" or "no" — you need to say HOW SURE you are, like "70% sure it's heads."

The sigmoid function is like a special ruler that turns any measurement (shine level) into a percentage between 0% and 100%. If shine is really high, sigmoid says "almost 100% heads." If shine is really low, sigmoid says "almost 0% heads" (so tails!). If shine is medium, sigmoid says "50% — could be either."

Now, how do we learn what "high" and "low" shine mean? We show the computer lots of coins with their true answers. Cross-entropy is the "wrongness score" — if you said "90% heads" but it was tails, you get a HUGE penalty. If you said "51% heads" and it was heads, tiny penalty. The computer adjusts its ruler to make the wrongness score as small as possible.

In aerospace, instead of coins, we might be guessing "will this engine part break?" based on temperature and vibration. Same math!


Connections

  • Linear Regression: Logistic regression uses linear combination z=wTx+bz = \mathbf{w}^T\mathbf{x} + b, but adds sigmoid for classification
  • Gradient Descent: Weight updates use J\nabla J derived here; same optimization algorithm
  • Softmax Regression: Multi-class generalization — sigmoid becomes softmax for K>2K > 2 classes
  • Neural Networks: Sigmoid is an activation function; cross-entropy is the standard classification loss
  • Maximum Likelihood Estimation: Cross-entropy loss is negative log-likelihood of Bernoulli model
  • ROC Curves and AUC: Evaluate logistic regression by varying the decision threshold
  • Regularization (L1, L2): Prevent overfitting by adding λw\lambda \|\mathbf{w}\| to loss function
  • Bayesian Interpretation: Logistic regression approximates P(y=1x)P(y=1|\mathbf{x}) directly

Flashcards

#flashcards/coding

What is the sigmoid function and why is it used in logistic regression?
σ(z)=11+ez\sigma(z) = \frac{1}{1+e^{-z}}. It maps any real-valued linear combination to a probability in (0,1)(0,1), is differentiable everywhere, and its derivative has a simple form σ(z)(1σ(z))\sigma(z)(1-\sigma(z)) that makes gradient calculations efficient.
Derive the sigmoid function from the log-odds assumption
Assume log(p1p)=z\log\left(\frac{p}{1-p}\right) = z. Then p1p=ez\frac{p}{1-p} = e^z, so p=ez(1p)p = e^z(1-p), giving p(1+ez)=ezp(1+e^z) = e^z, thus p=ez1+ez=11+ezp = \frac{e^z}{1+e^z} = \frac{1}{1+e^{-z}}.
What is binary cross-entropy loss for a single example?
L(y,y^)=[ylog(y^)+(1y)log(1y^)]L(y, \hat{y}) = -[y \log(\hat{y}) + (1-y) \log(1-\hat{y})] where y{0,1}y \in \{0,1\} is true label and y^(0,1)\hat{y} \in (0,1) is predicted probability.
Why is cross-entropy loss used instead of MSE for logistic regression?
MSE is non-convex with sigmoid (multiple local minima) and has vanishing gradients when predictions saturate. Cross-entropy is convex, derived from maximum likelihood, and maintains strong gradients even for confident wrong predictions.
Derive the gradient of cross-entropy loss w.r.t. weight wjw_j
Using chain rule: Lwj=Ly^y^zzwj=[yy^+1y1y^]y^(1y^)xj=(y^y)xj\frac{\partial L}{\partial w_j} = \frac{\partial L}{\partial \hat{y}} \cdot \frac{\partial \hat{y}}{\partial z} \cdot \frac{\partial z}{\partial w_j} = \left[-\frac{y}{\hat{y}} + \frac{1-y}{1-\hat{y}}\right] \cdot \hat{y}(1-\hat{y}) \cdot x_j = (\hat{y} - y)x_j.
What is the decision boundary in logistic regression?
The hyperplane where wTx+b=0\mathbf{w}^T\mathbf{x} + b = 0, corresponding to y^=σ(0)=0.5\hat{y} = \sigma(0) = 0.5. Points one side are classified as 1, the other as 0.
What is the derivative of the sigmoid function?
σ(z)=σ(z)(1σ(z))\sigma'(z) = \sigma(z)(1-\sigma(z)). This is derived using the quotient/chain rule and makes backpropagation efficient since it only requires the sigmoid output, not recomputing the exponential.
Why must features be normalized in logistic regression?
Features with vastly different scales cause some weights to dominate and force tiny learning rates. Standardization (zero mean, unit variance) ensures all features contribute equally and gradients have similar magnitudes, accelerating convergence.
How is logistic regression related to maximum likelihood estimation?
The cross-entropy loss is the negative log-likelihood of a Bernoulli distribution. Minimizing loss = maximizing likelihood of observed labels given model parameters.
What threshold should be used for aerospace safety-critical classification?
Not always 0.5. For failure prediction, use lower threshold (e.g., 0.3) to prefer false alarms over missed failures. Threshold depends on cost asymmetry: cost(miss)cost(false alarm)\text{cost}(\text{miss}) \gg \text{cost}(\text{false alarm}).

Concept Map

solves

predicts

assumes

solve for p

maps z to

input to

derivative

enables

threshold 0.5

trained by minimizing

convex unlike

optimized via

Logistic Regression

Binary Classification

Probabilities in 0 to 1

Log-odds linear in features

Sigmoid Function

Logit z = wTx + b

sigma times 1 minus sigma

Gradient Descent

Decision Boundary

Cross-Entropy Loss

Mean Squared Error

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, yaha basic idea ye hai ki jab humein classification karna hota hai — jaise "ye component fail hoga ya nahi", ya "satellite image me cloud hai ya nahi" — tab humein continuous number nahi, balki ek probability chahiye jo 0 aur 1 ke beech ho. Ab problem ye hai ki normal linear regression (y=wx+by = wx + b) toh koi bhi value de sakta hai, jaise -10 ya 5, jo probability ke liye galat hai. Isiliye hum sigmoid function use karte hai, jo kisi bhi real number ko squash karke (0,1)(0,1) ke beech le aata hai. Simple bhaasha me sigmoid ek "probability translator" hai — model ka raw confidence score leta hai aur usko valid probability me convert kar deta hai.

Ab sigmoid kaha se aaya? Iska core intuition hai odds ratio. Hum maante hai ki log-odds features ke saath linear relation rakhte hai, matlab features ka effect odds pe multiplicative hota hai lekin log-odds pe additive. Jab isko solve karte hai toh automatically sigmoid formula nikal aata hai — ye koi random function nahi hai, ye ek natural derivation hai. Aur ek bada plus point ye hai ki sigmoid ka derivative bahut clean hai: σ(z)=σ(z)(1σ(z))\sigma'(z) = \sigma(z)(1-\sigma(z)), jisse gradient descent ke calculations easy ho jaate hai, koi extra exponentials ka jhanjhat nahi.

Loss function ke liye hum MSE nahi, balki cross-entropy loss use karte hai, aur iska reason important hai. MSE sigmoid ke saath non-convex ho jaata hai (matlab multiple local minima, training atak sakti hai) aur jab prediction galat hoti hai tab bhi gradient kamzor ho jaata hai. Cross-entropy convex hoti hai (ek hi global minimum), strong gradients deti hai, aur confident galat predictions ko heavily penalize karti hai — yani model "over-confident galti" karne pe zyada seekhta hai. Ye poori cheez maximum likelihood se derive hoti hai, jo mathematically prove karta hai ki ye loss sahi choice hai. Yahi combination — sigmoid plus cross-entropy — logistic regression ko aerospace ML me binary classification ka reliable foundation banata hai.

Go deeper — visual, from zero

Test yourself — Machine Learning (Aerospace Applications)

Connections