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.

  • Intermédiaire
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • 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

Découvrez Least Squares Line Fit in Python with NumPy avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  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.

Quand l’utiliser ?

  • Solve equations, integrals and differential equations in a few lines.
  • Fit models to measured data and analyse signals in science and engineering classes.
  • Check homework answers numerically and see where a hand calculation went wrong.

Code d’exemple

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}")
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

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

Explication du code

Cet exemple montre Least Squares Line Fit in Python with NumPy en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  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.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

S'entraîner avec un défi

Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.

Tous les défis

Outils pour cette leçon