Math and Science with Python

Least Squares Line Fit in Python with NumPy

Fit the best straight line through data with np.polyfit or np.linalg.lstsq, and measure how good it is with R squared.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • np.polyfit for a line
  • The same fit with np.linalg.lstsq
  • R squared from residuals
score = 4.381 * hours + 47.036
slope4.381 points per hour
intercept47.036
R^20.9885

The line with the smallest squared errors

The problem

Does studying longer raise test scores, and by how much? Points on a scatter plot never sit on one line, so you need a rule for the best line and a number that says how well it fits.

Think of it like this

Least squares is like hanging a rigid stick among the points with a spring from each point to the stick. The springs pull harder the further away a point is, and the stick settles where the total pull is smallest.

From springs to code
hours, score📍 The points
np.polyfit(hours, score, 1)📏 Hang the stick where the springs balance
score - predicted🌀 The stretch of each spring
R^2 = 0.9885✅ How much of the pattern the line explains
The line settles where the squared distances are smallest.
In one sentence

A least squares fit chooses the line that makes the sum of squared vertical distances from the points as small as possible. np.polyfit(x, y, 1) returns its slope and intercept.

Key points

  1. np.polyfit(hours, score, 1) returns [slope, intercept], here 4.381 and 47.036.
  2. np.linalg.lstsq solves the same problem with the matrix [hours, 1].
  3. R squared is 1 - ss_res / ss_tot: 1 is a perfect fit.
  4. Prediction is slope * x + intercept.

When should you use it?

  • Trend lines for experiments and reports.
  • Simple linear regression in statistics classes.
  • Calibration lines in the lab.

When not to use it

  • The data curves: fit a higher degree or use scipy.optimize.curve_fit.
  • You need p-values and confidence intervals: use scipy.stats.linregress or statsmodels.

Example code

Open in editor →
main.py
import numpy as np

# Hours studied and test scores
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=float)
score = np.array([52, 55, 61, 64, 70, 71, 78, 83], dtype=float)

# polyfit with degree 1 fits a straight line: score = slope * hours + intercept
slope, intercept = np.polyfit(hours, score, 1)
print(f"polyfit: score = {slope:.3f} * hours + {intercept:.3f}")

# The same fit with lstsq: columns [hours, 1]
A = np.column_stack([hours, np.ones_like(hours)])
(m, c), residuals, rank, _ = np.linalg.lstsq(A, score, rcond=None)
print(f"lstsq:   score = {m:.3f} * hours + {c:.3f}")

# R squared: how much of the variation the line explains
predicted = slope * hours + intercept
ss_res = np.sum((score - predicted) ** 2)
ss_tot = np.sum((score - score.mean()) ** 2)
print(f"R^2 = {1 - ss_res / ss_tot:.4f}")
print(f"Predicted score for 10 hours: {slope * 10 + intercept:.1f}")
Get a Run button for this example

Result of running the code

polyfit: score = 4.381 * hours + 47.036
lstsq:   score = 4.381 * hours + 47.036
R^2 = 0.9885
Predicted score for 10 hours: 90.8

Code explanation

np.polyfit(hours, score, 1) fits a polynomial of degree 1, a straight line, and returns its slope 4.381 and intercept 47.036. lstsq solves the same problem written as a matrix: column_stack builds a column of hours and a column of ones, so the two results are m and c, and they match. R squared compares the leftover error ss_res with the total variation ss_tot; 0.9885 means the line explains almost all the variation in score.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the function or the data and predict the result before running.
  2. Compare the numerical answer with the exact one from SymPy or a hand calculation.
  3. Plot the result with Matplotlib to see what the numbers mean.
Run in the Python compiler →

Common mistakes

Swapping x and y

polyfit takes x first; swapping fits a different line.

Problem
np.polyfit(score, hours, 1)
Fix
np.polyfit(hours, score, 1)

Forgetting the column of ones in lstsq

Without it the line is forced through the origin.

Problem
np.linalg.lstsq(hours[:, None], score, rcond=None)
Fix
A = np.column_stack([hours, np.ones_like(hours)])

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges

Tools for this lesson