Fun with Learning Technology
LearnCoursesQuestionsTracksToolsNewsExplorePractice
Fun with Learning Technology

A new problem, explained clearly, every day.

Subscribe
Learn
  • Lessons
  • Topics
  • News
  • Tools
  • Courses
  • Career tracks
  • Everything
Site
  • About
  • Contact
  • Support
  • Privacy
  • Terms
Get the daily one

One email per new problem. No spam.

Request a tutorial

Requests shape what gets made next.

© 2026 Fun with Learning TechnologyRSS
Home›Courses›Machine Learning›Logistic Regression

Supervised Learning

Logistic Regression

Logistic Regression is a fundamental supervised learning algorithm used for binary classification by modeling the probability that a given input belongs to a specific class. It matters because it provides interpretable probabilistic outputs and serves as the foundational building block for complex neural network architectures. You reach for it when you need a simple, fast, and explainable baseline model for predicting categorical outcomes where the decision boundary is linear.

The Mathematical Foundation of the Sigmoid

To understand Logistic Regression, we must first address why simple linear regression fails at classification. Linear regression predicts continuous values across the entire real number line, whereas classification requires bounded outputs representing probabilities between zero and one. We solve this by applying the logistic function, also known as the sigmoid function, which maps any real-valued number into the (0, 1) range. The formula is 1 / (1 + exp(-z)). By wrapping our linear combination of input features, z = w*x + b, inside this function, we transform unbounded linear predictions into a smooth 'S' curve. This probabilistic interpretation allows us to treat the output as the likelihood of a positive class, providing a robust mathematical basis for decision-making. We use this function because it is differentiable, which is essential for optimization techniques that adjust model weights to minimize errors efficiently.

import numpy as np

def sigmoid(z):
    # The sigmoid function forces outputs into the range (0, 1)
    return 1 / (1 + np.exp(-z))

# Example usage with linear combination z
z = np.array([-10, 0, 10])
print(sigmoid(z))  # Returns array close to [0, 0.5, 1]

The Log Loss Cost Function

Optimization in classification requires a cost function that penalizes predictions based on how far they deviate from the ground truth. We cannot use Mean Squared Error here because the sigmoid function creates a non-convex surface, leading to many local minima. Instead, we use Log Loss, or Binary Cross-Entropy. The logic is rooted in Maximum Likelihood Estimation: we want to maximize the probability of the observed labels given our parameters. When the actual label is 1, the cost is -log(predicted_probability); when the label is 0, it is -log(1 - predicted_probability). This mechanism heavily penalizes 'confident but wrong' predictions, forcing the model to adjust weights aggressively when it misclassifies an example. By minimizing this loss, we ensure the model converges on the parameters that best explain the training data, ultimately creating a reliable decision boundary for future unseen samples.

def log_loss(y_true, y_pred):
    # Penalize predictions heavily if they are wrong
    # Clip values to avoid log(0) errors
    y_pred = np.clip(y_pred, 1e-15, 1 - 1e-15)
    return -np.mean(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))

# Example with perfect and imperfect predictions
print(log_loss(np.array([1, 0]), np.array([0.9, 0.1]))) # Low loss

Gradient Descent for Optimization

Once the loss function is defined, we must find the optimal weights that minimize it. Because the log loss is a convex function, gradient descent is guaranteed to find the global minimum if the learning rate is chosen appropriately. We calculate the gradient of the cost function with respect to each weight, which essentially tells us the direction of steepest ascent. We then move in the opposite direction by a step size defined by our learning rate. The update rule involves taking the difference between the prediction and the actual target, then multiplying it by the feature input. This process is iterative; we perform these updates over multiple passes, known as epochs, across the entire dataset. Through this refinement, the linear boundary slowly rotates and translates until it provides the best possible separation between the two classes based on the available training inputs.

def update_weights(X, y, weights, lr):
    # Calculate predictions
    predictions = sigmoid(np.dot(X, weights))
    # Gradient is (X^T * (pred - y)) / n
    gradient = np.dot(X.T, (predictions - y)) / len(y)
    # Move against the gradient
    return weights - lr * gradient

# Weights represent the slope/intercept for features
weights = np.zeros(3) # e.g., bias + 2 features

Implementing a Classifier

Combining the sigmoid function, the log loss calculation, and the gradient descent loop results in a functional logistic regression classifier. We structure our data into a matrix where rows are samples and columns are features, typically adding a column of ones to handle the intercept term. During the training phase, we initialize weights randomly or to zero, then iterate through the update rule for a set number of cycles. After training, the 'decision' is made by checking if the probability is greater than a specific threshold, typically 0.5. This thresholding converts a continuous probability into a discrete label. Because the model relies on a linear combination of features, it is crucial that the input data is relatively well-scaled. If features have vastly different ranges, the gradient descent process may become unstable or converge extremely slowly due to the nature of the weight updates.

class LogisticRegression:
    def fit(self, X, y, iterations=1000, lr=0.1):
        self.w = np.zeros(X.shape[1])
        for _ in range(iterations):
            self.w = update_weights(X, y, self.w, lr)
    
    def predict(self, X):
        return (sigmoid(np.dot(X, self.w)) >= 0.5).astype(int)

Practical Limitations and Interpretation

While powerful, Logistic Regression assumes a linear relationship between input features and the log-odds of the outcome. If the decision boundary is non-linear—for instance, if the classes are nested like circles—this model will perform poorly without manual feature engineering. You can overcome this by creating interaction terms or polynomial features to capture non-linear patterns. Furthermore, the model is susceptible to outliers, as they can disproportionately influence the weights during the gradient calculation. Despite these constraints, the primary advantage is interpretability: the weight coefficients indicate exactly how much each feature influences the outcome probability. By examining these weights, you can understand the relative importance of different features in the decision-making process. This transparency makes Logistic Regression an ideal candidate for regulated industries where model explainability is a legal or operational requirement for stakeholders.

# Visualize feature importance by inspecting learned weights
model = LogisticRegression()
model.fit(X_train, y_train)
for i, val in enumerate(model.w):
    print(f"Feature {i} impact: {val}")
# Higher absolute value indicates higher influence on prediction

Key points

  • Logistic Regression applies the sigmoid function to map linear combinations of inputs to probabilities.
  • The model uses binary cross-entropy as its objective function to penalize confident misclassifications.
  • Optimization is performed via gradient descent to find weights that minimize the total log loss.
  • The decision boundary is defined by the set of points where the probability equals 0.5.
  • Scaling input features is essential for the stability and convergence speed of the gradient descent process.
  • Logistic Regression provides an interpretable model where weights directly represent feature contribution to log-odds.
  • Non-linear decision boundaries require feature engineering or transformation since the base model is strictly linear.
  • The algorithm is sensitive to outliers, which can skew the learned decision boundary significantly during training.

Common mistakes

  • Mistake: Treating Logistic Regression as a linear regression model. Why it's wrong: Logistic regression predicts probabilities via the sigmoid function, not continuous values. Fix: Use it for classification tasks by applying a threshold to the output probability.
  • Mistake: Assuming the relationship between independent variables and the log-odds is non-linear. Why it's wrong: Logistic regression assumes a linear relationship between the predictors and the logit of the outcome. Fix: Perform feature engineering to include polynomial terms if the relationship is non-linear.
  • Mistake: Failing to scale input features. Why it's wrong: Like many gradient-based optimization algorithms, logistic regression converges faster and more reliably with scaled features. Fix: Apply standard scaling or normalization to all input features before training.
  • Mistake: Neglecting to check for multicollinearity. Why it's wrong: High correlation between independent variables makes the model coefficients unstable and difficult to interpret. Fix: Remove redundant features or use regularization techniques like Lasso.
  • Mistake: Using it on datasets with high class imbalance without adjustments. Why it's wrong: The model may default to predicting the majority class to minimize loss. Fix: Use class weights or sampling techniques to balance the impact of minority class samples.

Interview questions

What is Logistic Regression and when is it typically used in machine learning?

Logistic Regression is a fundamental classification algorithm used to predict the probability of a categorical outcome, typically binary, based on one or more independent variables. Unlike linear regression, which predicts continuous values, logistic regression applies the sigmoid function to map predicted values into a range between zero and one. We use it when the target variable is categorical, such as determining if an email is spam or not, because it provides a clear threshold for classification decisions based on input features.

What role does the sigmoid function play in Logistic Regression?

The sigmoid function, defined as 1 / (1 + e^-z), is the core mechanism that transforms the output of a linear combination of inputs into a probability score between zero and one. Without this function, our linear model could output values ranging from negative to positive infinity, which makes no sense for probabilities. By squashing these outputs, it allows us to set a decision boundary, usually at 0.5, to classify inputs into distinct groups effectively.

Why do we use the Log Loss (Binary Cross-Entropy) function instead of Mean Squared Error in Logistic Regression?

We avoid Mean Squared Error because, when paired with the non-linear sigmoid function, it creates a non-convex cost function with many local minima, making gradient descent unreliable. Log Loss, or binary cross-entropy, is mathematically derived from maximum likelihood estimation and results in a convex cost surface. This convexity ensures that gradient descent will consistently find the global optimum, which is crucial for training a stable and efficient machine learning classifier.

How does the 'decision boundary' work in Logistic Regression and can it represent non-linear relationships?

The decision boundary is the hypersurface that partitions the feature space into two classes; for a simple linear case, it is a straight line where the probability equals exactly 0.5. By default, Logistic Regression is a linear classifier, meaning it cannot model non-linear boundaries directly. However, we can represent non-linear relationships by creating polynomial features or interaction terms before feeding them into the model, effectively transforming the feature space so that a linear boundary in higher dimensions corresponds to a curved boundary in the original space.

Compare Logistic Regression with Support Vector Machines (SVM). In what scenarios would you choose one over the other?

Logistic Regression and SVMs are both linear classifiers, but they optimize differently. Logistic Regression is probabilistic, modeling the likelihood of class membership via the sigmoid function, which is useful when you need an actual probability score. SVMs aim to maximize the 'margin' between classes, focusing only on support vectors near the decision boundary. If the data is linearly separable, SVMs often provide better generalization by maximizing the margin. However, Logistic Regression is generally easier to interpret and less computationally expensive on very large datasets.

Explain the impact of regularization (L1 vs L2) on Logistic Regression coefficients.

Regularization is used to prevent overfitting by penalizing large coefficients. L2 regularization (Ridge) adds the squared magnitude of coefficients to the loss function, forcing them to be small but rarely zero, which helps handle multicollinearity. L1 regularization (Lasso) adds the absolute value of coefficients, which can force less important feature coefficients exactly to zero. In practice, you might write code like `model = LogisticRegression(penalty='l1', solver='liblinear')` to perform automated feature selection by discarding irrelevant variables entirely through sparsity induced by L1.

All Machine Learning interview questions →

Check yourself

1. What is the primary purpose of the sigmoid function in logistic regression?

  • A.To transform the linear combination of inputs into a probability range between 0 and 1
  • B.To normalize the input feature values to a standard normal distribution
  • C.To ensure that the output is always a non-negative integer
  • D.To replace the need for gradient descent in weight optimization
Show answer

A. To transform the linear combination of inputs into a probability range between 0 and 1
The sigmoid function maps any real-valued number into the (0, 1) interval, which represents the probability of a binary outcome. Option 1 is incorrect as normalization is a preprocessing step, not the model's function. Option 2 is wrong because the output must be a probability, not an integer. Option 4 is false as optimization is still required.

2. Why is the Mean Squared Error (MSE) generally not used as a loss function for logistic regression?

  • A.It is computationally more expensive than Log Loss
  • B.It leads to a non-convex optimization surface which makes finding the global minimum difficult
  • C.It prevents the model from ever outputting 0 or 1
  • D.It is strictly reserved for models with more than two classes
Show answer

B. It leads to a non-convex optimization surface which makes finding the global minimum difficult
With the sigmoid function, MSE leads to a non-convex cost function with many local minima, making gradient descent unreliable. Log Loss is convex, ensuring a unique global minimum. The other options are incorrect as they do not address the mathematical properties of the cost surface.

3. When interpreting the coefficients of a logistic regression model, what does a positive coefficient indicate?

  • A.The feature increases the target value linearly
  • B.The probability of the positive class increases as the feature value increases
  • C.The feature has no impact on the classification boundary
  • D.The model is overfitting to that specific feature
Show answer

B. The probability of the positive class increases as the feature value increases
In logistic regression, a positive coefficient indicates that the log-odds of the positive class increase as the feature value increases, thus increasing the probability. Option 0 is wrong because the relationship is probabilistic, not linear. Option 2 is false by definition of a coefficient's purpose. Option 3 is unrelated to the sign of the coefficient.

4. How does adding L2 regularization (Ridge) affect the weights of a logistic regression model?

  • A.It sets the least important weights exactly to zero
  • B.It forces all weights to be negative to prevent overfitting
  • C.It penalizes large weights to keep them small and reduce model complexity
  • D.It increases the learning rate to reach convergence faster
Show answer

C. It penalizes large weights to keep them small and reduce model complexity
L2 regularization adds a penalty proportional to the square of the weights, which prevents them from becoming too large and helps generalize better. Option 0 describes L1 (Lasso) regularization. Option 1 is incorrect as weights can be positive. Option 3 is wrong because regularization does not directly affect the learning rate.

5. In a binary classification task, if the logistic regression output for a data point is 0.8, what does this signify?

  • A.The model is 80% confident the observation belongs to the positive class
  • B.The observation is definitely classified as the positive class without further processing
  • C.The error rate of the model for this specific data point is 20%
  • D.The model has failed to converge for this particular input
Show answer

A. The model is 80% confident the observation belongs to the positive class
The output of logistic regression is the predicted probability of the positive class. 0.8 means the model predicts an 80% chance of the positive class. Option 1 is imprecise because a classification decision usually requires a specific threshold (e.g., 0.5). Option 2 is a misinterpretation of probability. Option 3 is logically unrelated.

Take the full Machine Learning quiz →

← PreviousLinear RegressionNext →Decision Trees

Machine Learning

35 lessons, free to read.

All lessons →

Track your progress

Sign in to mark lessons done, score quizzes and keep notes.

Open in the app