statistics Fits A Line With linear_regression

linear_regression returns slope and intercept in one call and correlation rates the fit, so predictions and linearity checks need no external packages.

PythonData Integrity

Code

pythonsnippet
16 lines
from statistics import linear_regression, correlation

# Weekly ad spend (x) versus signups (y): a textbook linear relationship.
spend = [10, 20, 30, 40, 50]
signups = [12, 21, 32, 38, 51]

slope, intercept = linear_regression(spend, signups)
print(f"slope={slope:.3f} intercept={intercept:.3f}")
print(f"predict at 35 -> {intercept + slope * 35:.1f}")

# correlation quantifies how linear the relationship is, from -1 to 1.
r = correlation(spend, signups)
print(f"correlation={r:.4f}")
print(f"r squared={r ** 2:.4f}")

# xs and ys must have equal length; xs need not be sorted.

Output

Captured from a sandboxed run of this snippet in the build pipeline.

slope=0.950 intercept=2.300
predict at 35 -> 35.5
correlation=0.9954
r squared=0.9909

Inside the snippet

The file’s state is a handful of top-level bindings: spend, signups.

What to watch for

  • Built-in APIs only, so there is no supply chain to vet.

Putting it to use

The demo output is labeled (slope=, predict at 35 ->, correlation=), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `statistics`. Its state lives in module-level bindings: `spend`, `signups`.