Reference · Statistics

stats.linear_regression

signature
stats.linear_regression(list, list, bool=) -> map

What it does

The line y = slope * x + intercept that fits two lists of numbers of the same length best, by least squares, as Python's statistics.linear_regression. The answer is a map { slope, intercept } of floats. With true as the third argument the line is proportional: it goes through the origin, the intercept is 0.0 and only the slope is fitted.

Examples

print(stats.linear_regression([1, 2, 3, 4, 5], [3, 5, 7, 9, 11]))print(stats.linear_regression([1, 2, 3], [2.1, 3.9, 6.2]))let fit = stats.linear_regression([1, 2, 3, 4, 5], [3, 5, 7, 9, 11])print(fit.slope * 6 + fit.intercept)
output
{ slope: 2.0, intercept: 1.0 }{ slope: 2.05, intercept: -0.033333333333333215 }13.0

Edge cases

print(stats.linear_regression([1, 2, 3], [4, 7, 10]), stats.linear_regression([1, 2, 3], [4, 7, 10], true))print(stats.linear_regression([1, 2, 3, 4], [1, 3, 2, 4]))print(stats.linear_regression([1, 2], [1, 2]), stats.linear_regression([1, 2, 3], [3, 6, 9], null))
output
{ slope: 3.0, intercept: 1.0 } { slope: 3.4285714285714284, intercept: 0.0 }{ slope: 0.8, intercept: 0.5 }{ slope: 1.0, intercept: 0.0 } { slope: 3.0, intercept: 0.0 }

Errors

A constant x is a runtime error, not an error value: no slope fits. For a proportional fit the same holds when x is all zeros. Lists of different lengths, fewer than two points, and an item that is not a number are runtime errors too.

this one fails
print(stats.linear_regression([2, 2, 2], [1, 2, 3]))
output
line 1: `stats.linear_regression`: x is constant
this one fails
print(stats.linear_regression([0, 0], [1, 2], true))
output
line 1: `stats.linear_regression`: x is all zeros
this one fails
print(stats.linear_regression([1, 2], [1, 2, 3]))
output
line 1: `stats.linear_regression` needs lists of the same length (2 and 3)

Chaining

In a pipeline x comes first and y is the argument:

let year = [2021, 2022, 2023, 2024]let users = [120, 150, 190, 220]let fit = year | stats.linear_regression(users)print(fit.slope | round(1), year | stats.linear_regression(users) | get("slope") | round(1))print(year | map((y) => fit.slope * y + fit.intercept) | map((v) => round(v, 1)))
output
34.0 34.0[119.0, 153.0, 187.0, 221.0]

See also

stats.correlation, stats.covariance, stats.mean

Thread
8Useful? Like it, or add to its thread below.

Thread 0 posts

On stats.linear_regression(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo