Python Glossary Русский

Python 3.10+statisticsfunction

statistics.linear_regression

relationships

Linear regression: the slope and intercept of the least-squares line (Python 3.10+).

Syntax

statistics.linear_regression(x, y)

The fit is not symmetric: x is the independent variable and y the dependent one, so swapping the arguments yields a different line. The result says nothing about how well the line describes the data — use statistics.correlation for the strength of the relationship. You need at least two points and non-constant x, otherwise StatisticsError.

Examples

# Python 3.11+
import statistics
r = statistics.linear_regression([1, 2, 3], [2, 4, 6])
print(round(r.slope, 1), round(r.intercept, 1))   # → 2.0 0.0
slope, intercept = statistics.linear_regression([1, 2, 3, 4], [3, 5, 6, 9])
print(round(slope, 2), round(intercept, 2))   # → 1.9 1.0
print(round(slope * 5 + intercept, 2))   # → 10.5
print(round(statistics.linear_regression([1, 2], [3, 5], proportional=True).slope, 2))   # → 2.6
print(statistics.linear_regression([1, 1, 1], [2, 4, 6]))   # → StatisticsError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy