Beyond the Sigmoid: The Mathematical Soul of Logistic Regression
From the publisher’s feed, collected in the ZeroLabs newsroom.
In the world of Machine Learning, most beginners treat model.fit() as a magic wand. You feed in data, and out comes a prediction. But if you are building algorithms from scratch—with nothing but Numpy and Math—you quickly realize that a classifier is not just a "binary switcher." It is a probability engine.Linear Regression fails at classification because lines are infinite, but probabilities are not. To understand Logistic Regression, we must first understand why its predecessor, the Perceptron, wasn’t enough, and how we use Maximum Likelihood to find the “best” line in a world of curves.1. The Evolution: From Perceptron to ProbabilityIn 1958, a young psychologist named Frank Rosenblatt at the Cornell Aeronautical Laboratory unveiled a machine that would change the course of technology: the Perceptron. It wasn’t just code; it was a physical machine (the Mark I) housed in a cabinet filled with wires and motors.The New York Times famously hailed it as the embryo of a computer that would one day “be able to walk, talk, see, write, reproduce itself and be conscious of its existence”. While the hype was premature, the Perceptron introduced the world to the Connectionist approach — the idea that machines could learn by adjusting the strength of their internal “neural” connections rather than being explicitly programmed.Mathematical FoundationThe Perceptron is a Binary Classifier inspired by the biological neuron. It computes a weighted sum of inputs and applies a “Hard Step” activation function.The Linear Model (z):w_i: Weights (the “importance” of each feature).b: Bias (the threshold for the neuron to “fire”).The Activation Function (Unit Step):The Learning Rule:If the model makes a mistake, we update the weights using the error (target) — (prediction):Where alpha is the Learning Rate.Code Implementation (From Scratch)import numpy as npclass Perceptron: def __init__(self, learning_rate=0.01, epochs=1000): self.lr = learning_rate self.epochs = epochs self.weights = None self.bias = None def fit(self, X, y): n_samples, n_features = X.shape # Initialize weights to zeros (or small random values) self.weights = np.zeros(n_features) self.bias = 0 # Ensure labels are binary (0, 1) y_binary = np.where(y > 0, 1, 0) for _ in range(self.epochs): for idx, x_i in enumerate(X): # 1. Linear combination linear_output = np.dot(x_i, self.weights) + self.bias # 2. Step Activation y_pred = 1 if linear_output >= 0 else 0 # 3. Perceptron Learning Rule update = self.lr * (y_binary[idx] - y_pred) self.weights += update * x_i self.bias += update def predict(self, X): linear_output = np.dot(X, self.weights) + self.bias return np.where(linear_output >= 0, 1, 0)The Problem: The Step Function is “brittle.” It is non-differentiable at zero and has a gradient of zero everywhere else. This means we cannot use Gradient Descent effectively to “nudge” the weights. More importantly, it gives you a hard “Yes” or “No” with no measure of confidence.This structural limitation — the inability to transform inputs into a new space — is exactly why we had to evolve toward Logistic Regression and Multi-Layer Perceptrons (MLPs), which use hidden layers to “bend” the space until it becomes separable.2. The Bridge: The Sigmoid FunctionIn Linear Regression, the output is a continuous value that can range from +∞ to — ∞ . However, for classification, we need a way to restrict this output to a probability range between 0 and 1. This is where the Sigmoid (Logistic) Function acts as our mathematical “squasher.”We start with our standard linear equation (z):We then transform this linear output by passing it through the Sigmoid function:Key Behavioral Characteristics:The Probability Map: No matter how extreme the value of z, it will always return a value between 0 and 1, which we interpret as the probability of the data point belonging to the “positive” class (P(y=1)).Asymptotic Behavior:The Decision Pivot: Exactly at z=0, sigma(z) = 0.5. This point is critical because it defines our Decision Boundary; anything above 0.5 is classified as 1, and anything below as 0.3. Visualizing the Probability Distribition on a Scatter PlotTo truly understand how Logistic Regression differs from Linear Regression, we must visualize how the “True Line” evolves into a “Probability Curve.”The Linear FailureImagine a scatter plot where the x-axis is “Hours Studied” and the y-axis is binary: “Pass (1)” or “Fail (0).” If we fit a standard Linear Regression line, it will cut straight through the data.The Problem: For a student who studies 100 hours, the line might predict a value of 1.5.The Logic: You cannot have a 150% chance of passing. Linear lines are infinite and cannot respect the boundaries of binary classes.The Logistic Transformation (The S-Curve)Logistic Regression replaces that straight line with a flexible S-curve. Instead of trying to hit the points exactly, it models the density and likelihood of the points.Design on the Plot: *Where the data points are mostly “0s,” the curve hugs the bottom of the graph (probability near 0.0).As we move toward the “1s,” the curve begins to rise.Where the two classes overlap or transition, the curve passes through the middle.The “True Line” vs. The Curve: The “True Line” (z = b0 + b1) actually exists behind the scenes. It determines the Log-Odds. When you apply the Sigmoid function to that hidden line, it “bends” into the S-shape we see on the scatter plot.Curve Steepness: The weight (b1) dictates how “aggressive” the transition is. A high b1 creates a very sharp, almost step-like S-curve, meaning the model is very certain. A low b1 creates a shallow, gradual curve, indicating higher uncertainty over a wider range x.4. Maximum Likelihood Estimation (MLE)In a binary classification setup like the one in the image, we typically model the probability of the “positive” class (let’s say the blue dots, or Class 1). Because there are only two possibilities, the probability of the “negative” class (red crosses, or Class 0) is naturally 1 — P(blue).The core idea of MLE is simple: We want to find the specific decision boundary that makes our observed data the most likely outcome.Imagine you have a line. If that line puts a blue dot in a “0.1 probability” zone, the model is saying, “I think there’s only a 10% chance this is blue.” That’s a bad model because the dot is blue.MLE seeks the parameters (the slope and intercept of that boundary line) that maximize the total probability of all observed points. Mathematically, we want to maximize:From Likelihood to Log LossWhile we want to maximize likelihood, computers are much better at minimizing a cost function. We also prefer adding numbers rather than multiplying them (since multiplying many small probabilities leads to tiny numbers that computers can’t handle well).To fix this, we take the Negative Log of the likelihood. This transforms the “Maximum Likelihood” problem into a “Minimum Loss” problem, known as Binary Cross-Entropy or Log Loss.How Log Loss Punishes the Model:The formula for a single point is:If the true class is Blue (y=1): The second half of the formula becomes zero. The loss is simply -log(p)If p=0.99 (High certainty), the loss is nearly 0.If p=0.01 (Confident but wrong), the loss is massive.If the true class is Red (y=0): The first half becomes zero. The loss is L = -log(1-p).If the model predicts a high probability for blue (p=0.9), the loss is high because 1-p (the red probability) is very low.Why the “Smooth Gradient” MattersLooking back at the image, those grid lines (0.6, 0.7, 0.8) represent the model’s confidence.Near the boundary (P=0.5): The Log Loss is moderate. Even if the model gets it wrong, it wasn’t “sure,” so the penalty isn’t catastrophic.Far from the boundary (P to 1 or P to 0): This is the high-stakes zone. If a red cross somehow ends up deep in the blue “0.9” territory, the Log Loss will spike aggressively. This forces the model to tilt or shift the decision boundary during training to avoid such “costly” mistakes.5. Python Implementation (From Scratch)import numpy as npclass LogisticRegressionFromScratch: def __init__(self, learning_rate=0.01, epochs=1000): self.lr = learning_rate self.epochs = epochs self.weights = None self.bias = None self.loss_history = [] def _sigmoid(self, z): return 1 / (1 + np.exp(-z)) def fit(self, X, y): n_samples, n_features = X.shape self.weights = np.zeros(n_features) self.bias = 0 for _ in range(self.epochs): # 1. Forward Pass: Linear Model + Sigmoid model_linear = np.dot(X, self.weights) + self.bias predictions = self._sigmoid(model_linear) # 2. Compute Log-Loss (Binary Cross Entropy) epsilon = 1e-15 # To avoid log(0) loss = -np.mean(y * np.log(predictions + epsilon) + (1 - y) * np.log(1 - predictions + epsilon)) self.loss_history.append(loss) # 3. Gradient Descent (Partial Derivatives) dw = (1 / n_samples) * np.dot(X.T, (predictions - y)) db = (1 / n_samples) * np.sum(predictions - y) # 4. Update Parameters self.weights -= self.lr * dw self.bias -= self.lr * db def predict_prob(self, X): model_linear = np.dot(X, self.weights) + self.bias return self._sigmoid(model_linear) def predict(self, X, threshold=0.5): return [1 if i > threshold else 0 for i in self.predict_prob(X)]6. Expanding Horizons: Multi-Class ClassificationWhat happens when you have more than two categories (e.g., classifying Iris flowers into 3 species)? Logistic Regression handles this through two main strategies:A. One-vs-All (OvA / One-vs-Rest)This is the most intuitive approach. If you have 3 classes (A, B, C), you train three separate binary classifiers:Classifier 1: Class A vs. (Class B + Class C)Classifier 2: Class B vs. (Class A + Class C)Classifier 3: Class C vs. (Class A + Class B)When predicting, you run all three and pick the one with the highest probability.B. The Multinomial Approach: Softmax FunctionFor true multi-class logic in a single model, we replace the Sigmoid with the Softmax Function. While Sigmoid squashes a single value between 0 and 1, Softmax squashes a vector of values so they all sum up to 1.The Formula:This ensures that the output is a valid probability distribution across all K classes.7. The Need for Regularization: Preventing “Over-Confidence”In our “From Scratch” journey, we’ve seen that Gradient Descent tries to minimize loss at all costs. However, if we have a small dataset or too many features, the model might become overfit — it learns the “noise” of the training data so perfectly that it fails on new, unseen data.Why do we need it?Regularization acts as a penalty on the complexity of the model. It prevents the coefficients (b) from exploding to massive values just to classify a single outlier correctly.We have two primary tools for this in our repository:1. L2 Regularization (Ridge Regression)The Math: We add the squared magnitude of the coefficients to the loss function:The Effect: It shrinks all coefficients evenly. It’s great for handling multicollinearity (when features are highly correlated).2. L1 Regularization (Lasso Regression)The Math: We add the absolute magnitude of the coefficients:The Effect: It encourages sparsity. It can drive less important feature coefficients exactly to zero, effectively performing automatic feature selection.The Hyperparameter: lambda (Lambda)This is the “Control Knob” for regularization:High lambda: High penalty, simpler model, prevents overfitting but might lead to underfitting.Low lambda: Low penalty, the model behaves more like standard Logistic Regression.Let’s Connect!LinkedIn: pruthil-prajapatiEmail: GmailGitHub: Pruthil-2910Keep exploring the math behind the models!#BuildInPublic #ArtificialIntelligence #DataEngineering #SoftwareEngineering #Mathematics #ProgrammingTips #100DaysOfCode #UnderTheHood #MathForML #FromScratch #CodeNewbie #Vectorization #Optimization #AlgorithmDesign #NumPy #PythonBeyond the Sigmoid: The Mathematical Soul of Logistic Regression was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.