Machine Learning • Machine Learning Algorithms • 15 min read

Linear and Logistic Regression

Two questions, two kinds of predictions

A housing website might ask, “What price should we estimate for this property?” A spam filter asks, “Is this message spam?” Both systems examine input features and produce predictions, but the outputs are fundamentally different.

Linear regression commonly predicts a numeric quantity. A simple example is estimating rent from apartment size: a larger apartment may tend to have a higher expected rent, although real prices depend on many other factors. A linear model represents this relationship as a weighted sum of features.

Logistic regression, despite its name, is commonly used for classification. It combines features into a score and transforms the score using a logistic function to produce a value between zero and one. For binary tasks that value can be interpreted as an estimated probability when the model and calibration are suitable. The application still needs a decision threshold to choose a class.

The key distinction is not whether the training procedure contains “regression” in its name. It is the prediction objective, the output interpretation, and the loss function used to learn the parameters.

In this article, follow the same progression for both methods: start with the prediction, see the mathematical function, understand how parameters are learned, then test the model on unseen data.

Linear regression and logistic regression are foundational supervised-learning models. Both use a weighted combination of input features, but they solve different prediction problems. Linear regression predicts a numerical quantity, while binary logistic regression estimates the probability of a class.

Their relative simplicity makes them useful starting points. They also introduce ideas that reappear in more complex machine-learning systems: features, learned parameters, objective functions, optimization, regularization, decision thresholds, and generalization.

1. Supervised learning and regression models

In supervised learning, a model learns from examples containing input features and corresponding target values. A training example can be written as (x,y)(\mathbf{x}, y), where x\mathbf{x} represents the input features and yy is the target.

Consider two problems involving the same inputs:

  • House-price prediction: Given floor area, location-related features, and building age, predict a numerical price. This is a regression task.
  • Loan-default prediction: Given suitable applicant and loan characteristics, estimate whether a loan will default. This is a classification task.

Despite its name, logistic regression is primarily a classification algorithm, not a method for predicting unrestricted numerical targets. Its name comes from modeling the log-odds of an event as a linear function of features.

PropertyLinear regressionBinary logistic regression
Primary taskPredict a continuous numerical targetEstimate the probability of a binary outcome
Model outputAny real-valued predictionA probability between 0 and 1
Core transformationWeighted sumSigmoid applied to a weighted sum
Common training objectiveSquared-error lossLog loss (binary cross-entropy)
Typical evaluationMAE, RMSE, R2R^2Precision, recall, F1, ROC-AUC, log loss
ExamplePredict energy consumptionPredict equipment failure: yes or no

Both models can be extended or adapted, but this article concentrates on ordinary linear regression and binary logistic regression.

2. Linear regression

Linear regression models the expected numerical target as a linear combination of input features and a constant term.

For one feature, the prediction equation is:

y^=wx+b\hat{y} = wx + b

Here:

  • xx is the input feature.
  • ww is the weight or coefficient learned from data.
  • bb is the intercept or bias term.
  • y^\hat{y} (pronounced “y-hat”) is the predicted value.

For several features, linear regression becomes:

y^=w1x1+w2x2+⋯+wdxd+b\hat{y} = w_1x_1 + w_2x_2 + \cdots + w_dx_d + b

In vector notation:

y^=wTx+b\hat{y} = \mathbf{w}^{\mathsf T}\mathbf{x} + b

The model is linear in its coefficients. The original inputs do not necessarily have to be raw quantities: an engineered feature such as x2x^2 can be included while retaining a model that is linear in its learned coefficients.

Worked example: estimating a numerical value

Suppose a simple fitted model predicts monthly energy consumption from a machine’s daily operating hours:

consumption^=12x+40\widehat{\text{consumption}} = 12x + 40

For x=5x = 5 hours per day:

y^=12(5)+40=100\hat{y} = 12(5) + 40 = 100

The predicted consumption is 100 units in the target’s chosen measurement scale. The coefficient of 12 means that, within this model, increasing operating time by one hour per day changes the prediction by 12 units, holding any other included features constant.

This relationship is predictive, not automatically causal. A learned coefficient does not by itself prove that changing a feature causes the target to change.

How the model is fitted

Given nn labeled examples, the model needs coefficients that produce useful predictions. A common objective is mean squared error (MSE):

MSE⁡(w,b)=1n∑i=1n(yi−y^i)2\operatorname{MSE}(\mathbf{w},b)=\frac{1}{n}\sum_{i=1}^{n}(y_i-\hat{y}_i)^2

Squaring errors makes large mistakes more costly and prevents positive and negative errors from canceling one another.

Ordinary least squares can be solved with suitable numerical linear-algebra methods. Alternatively, the coefficients can be optimized iteratively, for example with gradient descent. In practice, stable numerical solvers are preferred to manually computing a matrix inverse.

Residuals

A residual is the difference between the observed target and its prediction:

ei=yi−y^ie_i = y_i - \hat{y}_i

Residuals help reveal systematic prediction errors. For example, if residual magnitude grows at larger predictions, the errors may have nonconstant variance. A curved residual pattern can indicate that the current model misses an important relationship.

3. Logistic regression

Binary logistic regression models the probability that the target belongs to one of two classes. It first forms a linear score:

z=wTx+bz = \mathbf{w}^{\mathsf T}\mathbf{x} + b

It then applies the sigmoid function:

σ(z)=11+e−z\sigma(z)=\frac{1}{1+e^{-z}}

The predicted probability of class 1 is:

P(y=1∣x)=σ(wTx+b)P(y=1\mid\mathbf{x})=\sigma(\mathbf{w}^{\mathsf T}\mathbf{x}+b)

This maps every real-valued score to a number strictly between 0 and 1. A larger score corresponds to a larger probability for class 1.

Comparison of linear regression's unbounded output and logistic regression's sigmoid probability curve
Linear regression returns a numerical prediction directly; logistic regression converts a linear score into a probability.

Worked example: predicting a class probability

Suppose a fitted logistic model has one feature and produces:

z=0.8x−2z = 0.8x - 2

For x=4x=4:

z=0.8(4)−2=1.2z=0.8(4)-2=1.2

The estimated class-1 probability is:

P(y=1∣x=4)=11+e−1.2≈0.769P(y=1\mid x=4)=\frac{1}{1+e^{-1.2}}\approx 0.769

The model estimates a probability of approximately 76.9% for class 1. This is a model estimate, not a guarantee that the event will happen, and its reliability depends in part on probability calibration and the data used for training.

From probability to a class label

To turn a probability into a binary prediction, choose a decision threshold. With a threshold of 0.5:

y^={1if P(y=1∣x)≥0.50otherwise\hat{y}=\begin{cases} 1 & \text{if } P(y=1\mid\mathbf{x})\geq 0.5 \\ 0 & \text{otherwise} \end{cases}

The threshold can be changed. For example, if missing a potentially dangerous equipment failure is costly, a lower threshold might increase recall but also produce more false alarms. The appropriate threshold depends on the application and the consequences of errors.

Log-odds interpretation

Logistic regression is linear in the log-odds of the event:

log⁡(p1−p)=wTx+b\log\left(\frac{p}{1-p}\right)=\mathbf{w}^{\mathsf T}\mathbf{x}+b

where p=P(y=1∣x)p=P(y=1\mid\mathbf{x}).

For one feature, increasing that feature by one unit while keeping other features fixed multiplies the modeled odds by ewe^w. Odds are not the same as probability, so the coefficient should not be interpreted as a constant percentage-point change in probability.

4. Why the training objectives differ

Ordinary linear regression commonly minimizes squared prediction errors. Binary logistic regression commonly minimizes binary cross-entropy, also called log loss:

L=−1n∑i=1n[yilog⁡(pi)+(1−yi)log⁡(1−pi)]L=-\frac{1}{n}\sum_{i=1}^{n}\left[y_i\log(p_i)+(1-y_i)\log(1-p_i)\right]

Here, yi∈{0,1}y_i\in\{0,1\} and pip_i is the predicted probability of class 1. The loss strongly penalizes confident, incorrect probability predictions.

Prediction caseActual targetPredicted probability of class 1Interpretation
A10.95Confident and correct
B10.55Correct but uncertain at a 0.5 threshold
C10.05Confident and incorrect
D00.10Correct low class-1 probability

For standard unregularized logistic regression, minimizing log loss corresponds to maximum likelihood estimation under a Bernoulli outcome model. This provides a probabilistic basis for its objective.

5. Training models with scikit-learn

The following examples show a basic, reproducible workflow: split the data, fit the model only on the training data, make predictions for the test set, and evaluate the result.

Example A: linear regression

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split

# Synthetic relationship: y = 12x + 40
X = np.array([[1], [2], [3], [4], [5], [6], [7], [8]], dtype=float)
y = np.array([52, 64, 76, 88, 100, 112, 124, 136], dtype=float)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42
)

model = LinearRegression()
model.fit(X_train, y_train)

predictions = model.predict(X_test)
print("Coefficient:", model.coef_[0])
print("Intercept:", model.intercept_)
print("MAE:", mean_absolute_error(y_test, predictions))
print("RMSE:", np.sqrt(mean_squared_error(y_test, predictions)))
print("R2:", r2_score(y_test, predictions))
print("Prediction at x=5:", model.predict([[5]])[0])

Because these synthetic observations lie on an exact straight line, the fitted model can recover the underlying relationship almost perfectly. Real datasets are noisier; a successful synthetic example is not evidence of real-world accuracy.

For regression, common evaluation measures include:

  • MAE: Mean absolute error, expressed in the target’s units.
  • RMSE: Root mean squared error, which penalizes large errors more heavily.
  • R2R^2: The proportion of sample target variance accounted for by the model under the standard definition; its value can be negative on test data.

Example B: logistic regression

from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
    accuracy_score, classification_report, confusion_matrix,
    roc_auc_score
)
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# A standard educational dataset. Not a clinical decision system.
X, y = load_breast_cancer(return_X_y=True)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# The scaler is fitted inside the pipeline on training data only.
model = make_pipeline(
    StandardScaler(),
    LogisticRegression(max_iter=2000, random_state=42)
)
model.fit(X_train, y_train)

probabilities = model.predict_proba(X_test)[:, 1]
predictions = (probabilities >= 0.5).astype(int)

print("Accuracy:", accuracy_score(y_test, predictions))
print("ROC-AUC:", roc_auc_score(y_test, probabilities))
print("Confusion matrix:\n", confusion_matrix(y_test, predictions))
print(classification_report(y_test, predictions))

This example illustrates a standard classification workflow, not a validated medical application. The StandardScaler transforms features using statistics learned from the training set. Putting preprocessing inside a pipeline helps prevent data leakage, a common cause of misleading evaluation results.

Notice that predict_proba returns estimated probabilities, while applying a threshold converts them into labels. These are different outputs and should be evaluated differently.

6. Interpreting evaluation results

For linear regression, examine prediction errors on held-out data, compare against a simple baseline, and inspect residual patterns. The most useful metric depends on whether the application cares about typical absolute error or especially large mistakes.

For logistic regression, accuracy alone is often inadequate. If 99% of cases belong to one class, predicting that class every time can produce high accuracy while failing to identify the minority class.

Key classification metrics include:

  • Precision: Among positive predictions, the proportion that are correct.
  • Recall: Among actual positive cases, the proportion found by the model.
  • F1-score: A harmonic mean of precision and recall.
  • ROC-AUC: How well model scores rank positive cases above negative cases across thresholds.
  • Log loss: How well predicted probabilities align with observed labels under logarithmic scoring.

A confusion matrix separates true positives, false positives, true negatives, and false negatives. It helps connect numerical metrics to actual consequences.

Probabilities also need attention. A model that predicts 0.8 for many examples should, if it is well calibrated on comparable data, observe positive outcomes around 80% of the time in that group. Good classification accuracy does not guarantee good calibration.

7. Assumptions and limitations

These models are useful baselines, but their simplicity comes with constraints.

Linear regression considerations

  • Functional form: A simple linear model may miss nonlinear interactions or curved relationships unless appropriate features are added.
  • Correlated features: Strong multicollinearity can make individual coefficients unstable.
  • Outliers: Squared-error fitting can be heavily influenced by extreme observations.
  • Error assumptions: For classical confidence intervals and hypothesis tests, additional assumptions about the error process matter. Normal residuals are not a universal requirement for making predictions.
  • Extrapolation: Predictions well beyond the observed feature range may be unreliable.

Logistic regression considerations

  • Logit functional form: The model assumes that the log-odds are linear in the specified features, not that the probability is linear.
  • Complex boundaries: Without suitable feature engineering, nonlinear patterns may be missed.
  • Class imbalance: Thresholds, metrics, weighting, and sampling strategy require care.
  • Separation: Perfect or near-perfect class separation can make unregularized coefficient estimates unstable.
  • Probability quality: Estimates may be poorly calibrated when assumptions or data conditions are unfavorable.

Shared limitations

Both models can be affected by biased data, missing variables, dataset shift, leakage, and inappropriate evaluation. Neither model automatically establishes causation, fairness, or suitability for high-stakes decisions.

8. Regularization and feature scaling

Regularization discourages excessively large coefficients, which may help reduce overfitting and stabilize models with correlated inputs.

Two common approaches are:

TechniquePenaltyTypical effect
L1 (lasso-style)λ∑j∣wj∣\lambda\sum_j\lvert w_j\rvertCan drive some coefficients to zero
L2 (ridge-style)λ∑jwj2\lambda\sum_j w_j^2Shrinks coefficients toward zero

The intercept is often excluded from the penalty. Different libraries use different objective normalizations and regularization conventions, so parameter values such as alpha and C are not always interchangeable.

Feature scaling can make optimization behave better and makes penalties treat features with different units more comparably. Scaling is particularly useful for regularized linear models and logistic regression. Standardization parameters must be learned from training data, not from the entire dataset before splitting.

9. Choosing between the models

Start with the type of target:

  1. If the desired result is a numerical amount, linear regression is a reasonable initial baseline.
  2. If the desired result is the probability of a binary event, logistic regression is a reasonable initial baseline.
  3. If the relationship is too complex for either model, consider feature transformations, regularization, decision trees, ensembles, or neural networks as appropriate.
  4. Always evaluate against a simple baseline on data that represents the intended use.

For more than two classes, multinomial logistic regression is a common extension. There are also specialized regression models for counts, rates, and other outcome types, but these require their own modeling assumptions.

10. How these ideas connect to AI

Linear and logistic regression are not merely introductory algorithms. They expose a general machine-learning workflow:

Features → Parameterized model → Prediction → Loss → Parameter optimization → Evaluation

Neural networks build on related foundations, combining learned weighted transformations with nonlinear activation functions. Logistic regression’s sigmoid and cross-entropy also appear in neural-network classification. Linear transformations are central to layers, embeddings, and many other AI computations.

Studying these models gives you a concrete basis for understanding why a loss function matters, what training changes, how predictions are evaluated, and why reliable performance on unseen data is the actual goal.

11. Check your understanding

  1. Why is logistic regression used for classification despite having “regression” in its name?
  2. What does the coefficient ww represent in the equation y^=wx+b\hat{y}=wx+b?
  3. Why should training-set statistics, rather than full-dataset statistics, determine feature scaling?
  4. How does changing the decision threshold affect the precision-recall trade-off?
  5. Why does a model with high training accuracy still need evaluation on unseen examples?
Show suggested answers
  1. It models class probabilities through a sigmoid applied to a linear score, and models log-odds linearly.
  2. It describes the change in predicted target per one-unit increase in the feature, with other features fixed.
  3. Full-dataset statistics reveal information about evaluation examples and can create leakage.
  4. Lowering the threshold generally identifies more positives, often increasing recall while reducing precision; actual effects depend on the data.
  5. Training performance does not establish generalization and may reflect memorization or overfitting.

References and further reading

Related articles in

  • Clustering and K-Means — Learn how unsupervised clustering discovers groups in data, how K-Means optimizes cluster centroids, and how to evaluate and use its results responsibly.
  • Data, Model, and Experiment Versioning — Learn to trace ML results to exact datasets, code revisions, configurations, and artifacts.
  • Decision Trees, Random Forests, and Boosting — Learn how decision trees partition data, how random forests reduce variance through bagging, and how boosting combines sequential learners to improve predictions.

Image preview

Fit