⚡️ Speed up function gradient_descent
by 20,699%
#36
+6
−11
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.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 20,699% (206.99x) speedup for
gradient_descent
insrc/numpy_pandas/statistical_functions.py
⏱️ Runtime :
11.7 seconds
→56.1 milliseconds
(best of102
runs)📝 Explanation and details
Here's a much faster version of your program. The main optimization is replacing all explicit Python loops over NumPy arrays with fast vectorized NumPy operations. This will drastically reduce runtime and memory overhead. All comments are preserved since the logic of the overall function is unchanged—only the internal implementation is made more efficient.
Key changes for performance.
X.dot(weights)
, which is fully vectorized and uses optimized BLAS routines.X.T.dot(errors)
, then divided by the number of samples.This approach will be orders of magnitude faster for realistic data sizes, as almost all time is now spent in highly optimized NumPy C code rather than slow Python loops. The output will be numerically equivalent to your original function.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-gradient_descent-mc9t89qc
and push.