From 8e3cb61da9981847d5ac846f32f817c8dbfbeef3 Mon Sep 17 00:00:00 2001 From: "Miss Islington (bot)" <31488909+miss-islington@users.noreply.github.com> Date: Thu, 6 May 2021 08:26:55 -0700 Subject: Eliminate duplicated calculations and unnecessary work for linear regression (GH-25922) (GH-25945) --- Lib/statistics.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Lib/statistics.py b/Lib/statistics.py index edb11c8..db8c581 100644 --- a/Lib/statistics.py +++ b/Lib/statistics.py @@ -952,11 +952,16 @@ def linear_regression(regressor, dependent_variable, /): raise StatisticsError('linear regression requires that both inputs have same number of data points') if n < 2: raise StatisticsError('linear regression requires at least two data points') + x, y = regressor, dependent_variable + xbar = fsum(x) / n + ybar = fsum(y) / n + sxy = fsum((xi - xbar) * (yi - ybar) for xi, yi in zip(x, y)) + s2x = fsum((xi - xbar) ** 2.0 for xi in x) try: - slope = covariance(regressor, dependent_variable) / variance(regressor) + slope = sxy / s2x except ZeroDivisionError: raise StatisticsError('regressor is constant') - intercept = fmean(dependent_variable) - slope * fmean(regressor) + intercept = ybar - slope * xbar return LinearRegression(intercept=intercept, slope=slope) -- cgit v0.12