Eliminate duplicated calculations and unnecessary work for linear regression #25922
+7
−2
Conversation
Update to 15 March
LGTM! |
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)) |
rhettinger
May 6, 2021
Author
Contributor
That was an existing line take from covariance(). I think it is the fastest way the run this computation.
55b78ce
into
python:main
10 of 11 checks passed
10 of 11 checks passed
Thanks @rhettinger for the PR |
Sorry @rhettinger, I had trouble checking out the |
Thanks @rhettinger for the PR |
GH-25945 is a backport of this pull request to the 3.10 branch. |
miss-islington
added a commit
to miss-islington/cpython
that referenced
this pull request
May 6, 2021
…ression (pythonGH-25922) (cherry picked from commit 55b78ce) Co-authored-by: Raymond Hettinger <rhettinger@users.noreply.github.com>
rhettinger
pushed a commit
that referenced
this pull request
May 6, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
The current code, while pretty, does repeated calculations and unnecessary work:
covariance() and variance() both divide by
n - 1
which is thrown away in the slope calculation. This also causes two unnecessary roundings.covariance(x,y) and variance(x) both compute fmean(x). This doesn't need to be done twice.
variance(x) uses the extremely slow internal _ss(), _sum(), and _convert() functions whose purpose is to preserve type information. However, that type information is thrown away by linear_regression(x, y) which always returns a pair of floats:
the intercept calculation makes two more redundant fmean() calls that are unnecessary.
The inlined code makes the actual calculation more clear. It matches this typical presentation: slope = s_{x,y} / s^2_x