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.
- np.polyfit for a line
- The same fit with np.linalg.lstsq
- R squared from residuals
slope4.381 points per hourintercept47.036R^20.9885The 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.
hours, score📍 The pointsnp.polyfit(hours, score, 1)📏 Hang the stick where the springs balancescore - predicted🌀 The stretch of each springR^2 = 0.9885✅ How much of the pattern the line explainsA 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
np.polyfit(hours, score, 1)returns[slope, intercept], here 4.381 and 47.036.np.linalg.lstsqsolves the same problem with the matrix[hours, 1].- R squared is
1 - ss_res / ss_tot: 1 is a perfect fit. - 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.linregressor statsmodels.
Example code
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}")
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.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Swapping x and y
polyfit takes x first; swapping fits a different line.
np.polyfit(score, hours, 1)
np.polyfit(hours, score, 1)
Forgetting the column of ones in lstsq
Without it the line is forced through the origin.
np.linalg.lstsq(hours[:, None], score, rcond=None)
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.
- Simple Linear Regression (Least Squares) Fit the best straight line through data points with the least squares formulas. Medium
- Linear Regression with Gradient Descent Learn the slope and intercept of a line by repeatedly stepping down the mean squared error. Medium
Tools for this lesson
- Linear Regression in Python with scikit-learnFit a straight line with sklearn LinearRegression, read the slope and intercept, measure R^2 and MAE, and predict new values.
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.