Skip to main content

Least Squares Method: Definition, How It Works, and Examples

The least squares method is a foundational statistical technique used to identify the line (or curve) of best fit for a dataset. By minimizing the total error between observed data points and their predicted values, it enables professionals across fields (e.g., economics, engineering, data science) to model variable relationships, make predictions, and analyze trends. In this guide, we'll explore the least squares method in depth—from its definition and mathematical basis to practical examples and real-world applications.

Tom Roberts

By · Editor, Quantopia

Published · Updated

Table of Contents#

  • What Is the Least Squares Method?
  • How Does the Least Squares Method Work?
  • Mathematical Formula for Linear Regression (Least Squares)
  • Example: Calculating the Line of Best Fit
  • Real-World Example: Predicting Sales from Ad Spend
  • Assumptions of Ordinary Least Squares (OLS)
  • Types of Least Squares Methods
  • Applications of the Least Squares Method
  • Advantages and Disadvantages
  • Frequently Asked Questions (FAQ)
  • Conclusion
  • References

What Is the Least Squares Method?#

The least squares method is a form of regression analysis that finds the trend line (or curve) best representing a dataset. For a set of data points (relating an independent variable xx to a dependent variable yy), the method minimizes the sum of squared residuals—the difference between observed yy-values and values predicted by the line (y^\hat{y}).

First clearly articulated by Adrien-Marie Legendre in 1805 and independently by Carl Friedrich Gauss in 1809, the least squares method quickly became a cornerstone of statistical analysis. Gauss famously used it to predict the orbit of the asteroid Ceres, demonstrating its predictive power early on.

In simpler terms: If you plot data on a graph, the least squares line is the one where the total "distance" (squared to eliminate negative values) between data points and the line is smallest. This line is used to:

  • Model relationships (e.g., "How does income affect spending?").
  • Make predictions (e.g., "Forecast sales based on advertising spend.").

How Does the Least Squares Method Work?#

The core goal of least squares is to minimize the sum of squared residuals:

∑(yi−y^i)2\sum (y_i - \hat{y}_i)^2

Where:

  • yiy_i = observed value of yy for the ii-th data point.
  • y^i\hat{y}_i = predicted value of yy (from the line of best fit) for the ii-th data point.

Why "Squared" Residuals?#

Squaring residuals serves two critical purposes:

  1. Eliminates negative values: Residuals ( yi−y^iy_i - \hat{y}_i ) can be positive (data point above the line) or negative (below the line). Squaring ensures all errors are positive, so they don't cancel out.
  2. Penalizes larger errors: Squaring amplifies the impact of extreme values, ensuring the line prioritizes fitting points with bigger discrepancies (small errors have less influence).

Mathematical Formula for Linear Regression (Least Squares)#

For simple linear regression (where xx and yy have a linear relationship: y=mx+by = mx + b), we derive the slope (mm) and intercept (bb) of the best-fit line using:

m=n∑xy−∑x∑yn∑x2−(∑x)2m = \frac{n\sum xy - \sum x \sum y}{n\sum x^2 - (\sum x)^2} b=∑y−m∑xnb = \frac{\sum y - m \sum x}{n}

Where:

  • nn = number of data points.
  • ∑x\sum x = sum of all xx-values.
  • ∑y\sum y = sum of all yy-values.
  • ∑xy\sum xy = sum of xi×yix_i \times y_i for all data points.
  • ∑x2\sum x^2 = sum of xi2x_i^2 for all data points.

Example: Calculating the Line of Best Fit#

Let's apply the least squares method to a sample dataset. Suppose we have 5 data points:

xx (Independent Variable)yy (Dependent Variable)
12
23
35
44
56

Step 1: Calculate Key Summations#

First, compute ∑x\sum x, ∑y\sum y, ∑xy\sum xy, and ∑x2\sum x^2:

  • ∑x=1+2+3+4+5=15\sum x = 1 + 2 + 3 + 4 + 5 = 15
  • ∑y=2+3+5+4+6=20\sum y = 2 + 3 + 5 + 4 + 6 = 20
  • ∑xy=(1×2)+(2×3)+(3×5)+(4×4)+(5×6)=2+6+15+16+30=69\sum xy = (1 \times 2) + (2 \times 3) + (3 \times 5) + (4 \times 4) + (5 \times 6) = 2 + 6 + 15 + 16 + 30 = 69
  • ∑x2=12+22+32+42+52=1+4+9+16+25=55\sum x^2 = 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 1 + 4 + 9 + 16 + 25 = 55

Step 2: Compute the Slope (mm)#

Using n=5n = 5:

m=5(69)−(15)(20)5(55)−(15)2=345−300275−225=4550=0.9m = \frac{5(69) - (15)(20)}{5(55) - (15)^2} = \frac{345 - 300}{275 - 225} = \frac{45}{50} = 0.9

Step 3: Compute the Intercept (bb)#

b=∑y−m∑xn=20−(0.9)(15)5=20−13.55=6.55=1.3b = \frac{\sum y - m \sum x}{n} = \frac{20 - (0.9)(15)}{5} = \frac{20 - 13.5}{5} = \frac{6.5}{5} = 1.3

Step 4: The Line of Best Fit#

The regression line is:

y^=0.9x+1.3\hat{y} = 0.9x + 1.3

To verify, we calculate predicted values (y^\hat{y}) and residuals (y−y^y - \hat{y}):

xxyyy^=0.9x+1.3\hat{y} = 0.9x + 1.3Residual (y−y^y - \hat{y})Squared Residual ((y−y^)2(y - \hat{y})^2)
122.2-0.20.04
233.1-0.10.01
354.01.01.00
444.9-0.90.81
565.80.20.04

Total squared residuals: 0.04+0.01+1.00+0.81+0.04=1.90.04 + 0.01 + 1.00 + 0.81 + 0.04 = 1.9 (the minimum possible for this dataset).

Real-World Example: Predicting Sales from Ad Spend#

Consider a small business that wants to understand how advertising spending affects monthly sales. Over six months, they record the following data:

MonthAd Spend ($1,000s)Sales ($10,000s)
125
237
3510
449
5613
6714

Using the least squares method, the business calculates:

  • n=6n = 6, ∑x=27\sum x = 27, ∑y=58\sum y = 58
  • ∑xy=2(5)+3(7)+5(10)+4(9)+6(13)+7(14)=293\sum xy = 2(5) + 3(7) + 5(10) + 4(9) + 6(13) + 7(14) = 293
  • ∑x2=4+9+25+16+36+49=139\sum x^2 = 4 + 9 + 25 + 16 + 36 + 49 = 139

Slope:

m=6(293)−(27)(58)6(139)−(27)2=1758−1566834−729=192105≈1.829m = \frac{6(293) - (27)(58)}{6(139) - (27)^2} = \frac{1758 - 1566}{834 - 729} = \frac{192}{105} \approx 1.829

Intercept:

b=58−1.829(27)6=58−49.386≈1.44b = \frac{58 - 1.829(27)}{6} = \frac{58 - 49.38}{6} \approx 1.44

Regression equation: y^=1.829x+1.44\hat{y} = 1.829x + 1.44

Interpretation: For every additional 1,000spentonadvertising,salesincreasebyapproximately1,000 spent on advertising, sales increase by approximately 18,290. If the business spends 8,000onads,predictedsalesare8,000 on ads, predicted sales are 1.829(8) + 1.44 \approx 16.07(or(or160,700).

This example shows how ordinary least squares regression transforms raw data into actionable business insights.

Assumptions of Ordinary Least Squares (OLS)#

The ordinary least squares estimator produces unbiased, efficient estimates only when certain conditions—known as the Gauss-Markov assumptions—are met:

  1. Linearity: The relationship between the independent variable(s) and the dependent variable is linear in the parameters.
  2. Independence: Observations are independent of each other. This assumption is often violated in time-series data, where autocorrelation can bias results.
  3. Homoscedasticity: The variance of residuals is constant across all levels of the independent variable. When this is violated (heteroscedasticity), weighted least squares may be more appropriate.
  4. No perfect multicollinearity (for multiple regression): Independent variables are not perfectly correlated with each other.
  5. Zero conditional mean: The expected value of the error term is zero given any value of the independent variables. This ensures the estimator is unbiased.

When these assumptions hold, the Gauss-Markov theorem guarantees that OLS is the Best Linear Unbiased Estimator (BLUE)—meaning it has the lowest variance among all linear unbiased estimators.

If residuals are normally distributed, OLS also becomes the maximum likelihood estimator, enabling hypothesis testing and confidence intervals.

Types of Least Squares Methods#

While ordinary least squares (OLS) is the most common form, several variants address different data conditions:

MethodWhen to UseKey Feature
Ordinary Least Squares (OLS)Standard linear regression with homoscedastic, uncorrelated errorsMinimizes sum of squared residuals
Weighted Least Squares (WLS)Heteroscedastic data (unequal error variances)Assigns weights to observations inversely proportional to their variance
Generalized Least Squares (GLS)Correlated errors (e.g., time-series data with autocorrelation)Accounts for correlation structure in the error term
Nonlinear Least SquaresModel is nonlinear in parametersUses iterative algorithms (e.g., Gauss-Newton) to find parameter estimates
Total Least SquaresErrors exist in both independent and dependent variablesMinimizes perpendicular distances to the fitted line

For most introductory applications, ordinary least squares is sufficient. However, recognizing when to use weighted or generalized least squares is critical for advanced econometric and scientific analysis.

Applications of the Least Squares Method#

The least squares method is used across diverse fields:

  • Economics: Model relationships like "income vs. spending" or "interest rates vs. inflation" to inform policy decisions. Econometricians use OLS as the foundation for demand estimation and forecasting.
  • Engineering: Analyze experimental data (e.g., "temperature vs. material strength") to optimize designs and calibrate sensors.
  • Finance: Predict stock prices, analyze risk (e.g., CAPM models for "asset returns vs. market returns"), and estimate beta coefficients for portfolio management.
  • Science: Fit curves to experimental data (e.g., "time vs. chemical reaction rate") to derive physical models and test hypotheses.
  • Machine Learning: Linear regression—built on least squares—is a baseline algorithm for predictive modeling, feature selection, and regularization techniques like ridge regression and Lasso.
  • Healthcare: Model dose-response relationships in clinical trials and predict patient outcomes based on biomarkers.

Advantages and Disadvantages#

Advantages:#

  • Intuitive and Simple: Easy to understand, implement, and interpret (e.g., slope = "change in yy per unit xx").
  • Objective Best Fit: Provides a clear, data-driven "best fit" by minimizing squared errors.
  • Optimal Under Assumptions: When Gauss-Markov conditions are met, OLS is the most efficient linear unbiased estimator.
  • Closed-Form Solution: Unlike many optimization problems, OLS has an exact analytical solution—no iterative computation required.
  • Foundation for Advanced Methods: Serves as the basis for ridge regression, Lasso, and other regularized regression techniques.

Disadvantages:#

  • Sensitive to Outliers: Squaring residuals amplifies extreme values, distorting the line of best fit.
  • Assumes Linearity: Only effective if xx and yy have a linear relationship (or can be transformed to linear).
  • Assumes Independent Errors: If residuals (errors) are correlated (e.g., in time-series data), results are biased.
  • Assumes Homoscedasticity: Unequal error variances across observations can lead to inefficient estimates and incorrect standard errors.
  • Multicollinearity Sensitivity: In multiple regression, highly correlated predictors inflate standard errors of coefficient estimates.

Frequently Asked Questions (FAQ)#

What is the difference between least squares and linear regression?
Least squares is the method used to estimate the parameters of a linear regression model. Linear regression is the broader modeling framework; least squares is the most common technique for fitting that model to data.

When should I use weighted least squares instead of ordinary least squares?
Use weighted least squares when the variance of residuals is not constant across observations (heteroscedasticity). For example, if larger values of xx produce larger residuals, WLS assigns smaller weights to those observations to reduce their influence.

Can least squares be used for nonlinear relationships?
Yes. Nonlinear least squares extends the method to models that are nonlinear in parameters (e.g., exponential growth curves). However, nonlinear least squares requires iterative numerical algorithms and does not have a closed-form solution.

What does the R-squared value tell me?
R-squared (the coefficient of determination) measures the proportion of variance in the dependent variable explained by the model. An R-squared of 0.85 means 85% of the variation in yy is accounted for by the regression. While useful, R-squared alone does not validate model assumptions.

Is least squares the same as maximum likelihood estimation?
When the errors are normally distributed, ordinary least squares and maximum likelihood estimation produce identical parameter estimates. In general, however, they are distinct approaches.

Who invented the least squares method?
The method is attributed to both Adrien-Marie Legendre, who published it in 1805, and Carl Friedrich Gauss, who claimed to have developed it in 1795 and published in 1809. Gauss extended the method by connecting it to probability theory and the normal distribution.

Conclusion#

The least squares method is a powerful tool for modeling linear relationships and making predictions. While it has limitations (e.g., sensitivity to outliers), its simplicity and interpretability make it a staple in regression analysis. Understanding the underlying assumptions—linearity, independence, homoscedasticity, and zero conditional mean—ensures that you apply the method appropriately and interpret results correctly. Whether you're analyzing economic trends, engineering data, or scientific experiments, understanding least squares equips you to derive meaningful insights from data.

References#

  1. James, G., Witten, D., Hastie, T., & Tibshirani, R. (2013). An Introduction to Statistical Learning: with Applications in R. Springer. (2nd ed., 2021, available at https://www.statlearning.com/)
  2. Investopedia. "Least Squares Method Explained: Uses, Examples & Key Insights." Retrieved from https://www.investopedia.com/terms/l/least-squares-method.asp
  3. Wikipedia. "Least Squares." Retrieved from https://en.wikipedia.org/wiki/Least_squares
  4. Wikipedia. "Gauss–Markov Theorem." Retrieved from https://en.wikipedia.org/wiki/Gauss%E2%80%93Markov_theorem
  5. GeeksforGeeks. "Least Square Method." Retrieved from https://www.geeksforgeeks.org/maths/least-square-method/