Gradient descent calculator for linear regression

Gradient descent fits a line by stepping the weights against the gradient of the loss, w ← w − η ∂L/∂w. It converges only when the learning rate η is below 2/λmax, where λmax is the largest eigenvalue of the loss's Hessian. For the demo data below (x from 20 to 80) that limit is 0.000301 on raw x, and 1 once x is standardised.

Paste your own x, y data to get the limit, the fit with MSE, MAE, Huber or log-cosh, lasso and ridge paths, R² and adjusted R², and a Python script. Free, runs in your browser.

Goodfellow, Bengio and Courville (Deep Learning 4.3, 5.1.4, 7.1) · Goh (Distill) · scikit-learn 1.9 and Keras docs · Duke (Nau) · synthetic seeded demo data, not course data · checked against an independent solution (2,093 checks at build) · Updated 24 Nov 2026

n = 30, p = 1

Used by every tab. Demo A: x uniform in [20, 80], y = 12 + 0.8x + 2z (z standard normal), from the seeded generator mulberry32 (seed 2026). Demo B: five features on different scales, y = 3 + 2x1 − 0.1x2 + 0.5x3 + 1.5z; x4 and x5 do not enter y (seed 11). Synthetic, not course data.

Fit y = w·x + b by full-batch gradient descent from w = 0, b = 0. Where does it land, and how close is that to the exact answer?

Weightsw = 0.823367b = 10.9203
Final loss3.65465after 200 iterations
Exact answerw = 0.823367b = 10.9203 (normal equations)
  • Converged: the weights agree with the normal equations to 14 digits. η = 0.1 is 0.1 of the limit for standardised x.
1234050100150200least-squares minimumgradient descentiterationlog₁₀ (mean loss)
30405060703040506070gradient descentnormal equationsxy

How does gradient descent work for linear regression?

Gradient descent starts from a guess and repeatedly steps the weights downhill. Goodfellow, Bengio and Courville describe it as moving "in small steps with the opposite sign of the derivative", where ε (η here) "is the learning rate, a positive scalar determining the size of the step". For a straight line and the mean squared error:

Least squares also has an exact answer, the normal equations of Deep Learning eq. 5.12. Gradient descent should land on it:

On demo A, with x standardised, η = 0.1 and 200 iterations give w = 0.82336694 and b = 10.920258. The normal equations give w = 0.82336694 and b = 10.920258, so the two agree to 14 digits. The weights are converted back to raw x units: w = ws/σx and b = bs − wsμx/σx. The final MSE is 3.65465, close to the noise variance of 4 used to make the data.

Why does a high learning rate make gradient descent diverge?

Each step's curvature term can outweigh its slope term. Goodfellow 4.3.1: "When this last term is too large, the gradient descent step can actually move uphill", and "the eigenvalues of the Hessian thus determine the scale of the learning rate". The MSE of a linear model is a quadratic, so the condition is exact. Goh (Distill, 2017) writes: "All workable step-sizes, therefore, fall in the interval 0 < αλi < 2."

For demo A:

So η = 0.001, used by 10 of the 35 reports with readable code, is 3.32 times the limit on raw x. The loss passes 10200 after 131 iterations. Even at the best fixed rate, raw x needs about 2,27,506 iterations to cut the error a million times, because the condition number is 32,935. Goodfellow: "When the Hessian has a poor condition number, gradient descent performs poorly". After standardising, the Hessian of one feature is exactly 2I, η = 0.5 lands on the answer in one step, and η = 0.1 cuts the error a million times in 62 steps. For demo B the condition number falls from 71,446 (raw) to 1.63 (standardised).

The tiny data in many reports behaves differently. For x = 1 to 5 (y = 2x + 3) the raw limit is 0.0845, so a report's η = 0.08 runs at 95 % of it. The weights zig-zag but still reach w = 2, b = 3. Larger numbers shrink the limit fast. One report fits house prices against areas of 800 to 5,000 sq ft with η = 0.001 on raw x. For those seven areas the limit is 1.32e-7, so η is 7,577 times too large: run as written, the loss passes 10200 after 23 iterations.

What is the difference between L1 and L2 gradient descent?

There is no separate "L1 gradient descent". The question mixes two things that share the names. As losses, L1 is the mean absolute error and L2 the mean squared error: scikit-learn calls MAE the "l1-norm loss". As regularisation, a penalty on the weights is added to the loss. Goodfellow 7.1.1: "L2 regularization is also known as ridge regression or Tikhonov regularization". On 7.1.2: "L1 regularization results in a solution that is more sparse. Sparsity in this context refers to the fact that some parameters have an optimal value of zero." In scikit-learn's scaling:

The penalty |w| has no gradient at zero, so lasso is solved by coordinate descent with soft thresholding (scikit-learn: "The implementation in the class Lasso uses coordinate descent"), not by plain gradient descent. On demo B (standardised), every lasso coefficient is zero from α = 6.077 up. As α falls, the features enter in the order x1, x2, x3, x5, x4. At α = 0.608 the zeros are x4, x5. Ridge never gives an exact zero; at α = 60 its coefficients are 2.96, -1.55, 0.792, -0.0812, 0.194.

What loss functions are used for regression?

Four losses cover most regression work, all written with the residual r = ŷ − y and averaged over the rows. Huber and log-cosh follow the Keras definitions:

The derivative decides how hard a point pulls. With the three rightmost points of demo A raised by 25, the least-squares slope moves from 0.8234 to 1.0025. Huber (δ = 1) moves from 0.8233 to 0.8292 and log-cosh from 0.8236 to 0.8320. MAE stays at 0.8222, because its best line still passes through the same two points. RMSE is not a separate fit: it is the square root of MSE, so it has the same minimum. The tool leaves out quantile, MAPE and MSLE.

How do you evaluate a linear regression model?

Report the error in the units of y (RMSE, MAE) and the share of variance explained (R²), and do it on rows the model did not see. scikit-learn says RMSE gives "a measure in the same units as the target variable". For R²: "Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse)". On demo B with 25 % held out (seed 42), training R² is 0.9608 and test R² is 0.9624. RMSE is 1.384 on the test rows, against the noise standard deviation of 1.5 used to make the data. Then plot the residuals against the fitted values. A pattern there means the straight line is the wrong model, whatever R² says.

What is the difference between R² and adjusted R²?

Multiple R² is the plain R² of a model with several predictors. Adjusted R² charges for each predictor. Duke's regression notes put the degrees of freedom at "n-(k+1)" for k predictors plus an intercept, and say adjusted R² "can go down (even go negative) if irrelevant variables are added":

Here p counts the predictors, not the intercept. Demo B, with n = 60 and p = 5, then the same data with a column of random numbers added:

R² goes up a little: an added column can never lower it. Adjusted R² falls, because the column explains less than one predictor's worth. On demo A the same test gives R² 0.9841 → 0.9842 and adjusted R² 0.9836 → 0.9831.

How do you write gradient descent in Python from scratch?

Compute the residuals, take the mean loss and its gradient, step, and repeat. Store the loss at every step so you can plot it. Standardise x first and convert the weights back at the end. The script in tab 6 does this for all four losses in about 40 lines of NumPy. Its first two printed numbers are tab 1's to 10 digits. One slip shows up in report code: a loop that declares 1,000 iterations but runs once per data row (3 reports). Another is easy to make: summing the gradient without the 1/n makes it n times larger, so the safe rate is n times smaller. Tab 7's learning-rate check tests for the second.

What 111 public prediction challenge reports answer (as of 23 Nov 2026)

We read the 111 public Skill-Lync reports titled "Supervised Learning - Prediction Week 3 Challenge", as of 23 Nov 2026 (texts fetched 23 Nov 2026 23:4x IST), n = 111. 48 carry at least one image and 38 carry three or more, so code and formulas in screenshots are not counted: every row is a floor. None is image-only. A row's "of" is the number of reports where that question could be found. The links are examples.

What stands out: 50 answer the L1/L2 question as regularisation, 40 as losses and only 5 give both meanings. Of the 35 reports with gradient descent code in the text, 2 scale the features, and 17 use η = 0.001 or 0.0001. 4 say adjusted R² lies between 0 and 1, which it need not. These are first-party counts, a starting point rather than a measure of ability.

How we checked the calculator

An independent Python script, scripts/verify/gradient_descent.py, recomputes the numbers with its own code. This page refuses to build if the browser code differs from it in any of 2,093 numbers, flags or index lists (201 more assertions run inside the script, 202 cases). It generates the demo data with its own 32-bit mulberry32 and solves least squares by Gauss-Jordan. It gets the Hessian's eigenvalues from NumPy's eigvalsh and checks λmax by power iteration. It checks that gradient descent converges at 0.95 of the limit and diverges at 1.05, and finds the MAE line by trying every pair of points. Huber and log-cosh use its own Newton's method; lasso uses coordinate descent with the full residual, checked against the KKT conditions. It also checks scikit-learn's documented example (MSE 0.375, MAE 0.5, R² 0.948…) and runs the tab 6 script. Two deliberate bugs (the MSE derivative r instead of 2r, and n − p in place of n − p − 1) each make the build fail.

What this calculator does not cover

  • Stochastic and mini-batch gradient descent, momentum, Adam. Every step here uses all rows and a fixed η. The limit 2/λmax is for this plain method.
  • Classification. Logistic regression and its log loss are not here; this is regression only.
  • Non-linear models. For a polynomial or any curve, use the curve fitting calculator. A polynomial is still linear in its weights, so the method here applies if you paste x, x², … as columns.
  • Statistical tests. No p-values, confidence intervals or F-tests.
Learn machine learning with Python

Gradient descent, loss functions and model evaluation are the prediction week of Skill-Lync's PG program in data analytics and data science, before the classification and clustering weeks.

Frequently asked questions

What is the learning rate in gradient descent?

The learning rate η is the step size: each update moves the weights by η times the gradient of the loss. Too small and the loss falls slowly; above 2/λmax, where λmax is the largest eigenvalue of the loss's Hessian, the steps overshoot and grow. For least squares this limit can be computed from the data.

Why does my gradient descent diverge?

Usually the learning rate is above 2/λmax for your data. Unscaled features make λmax large: for x between 20 and 80 the limit is about 0.0003, so η = 0.001 blows up. Standardise the features, or lower η. Also check that the gradient is averaged over n and that the update subtracts it.

What is the difference between L1 and L2 in machine learning?

The words are used two ways. As losses, L1 is the mean absolute error and L2 the mean squared error. As regularisation, L1 (lasso) adds α times the sum of |w| to the loss and can set weights exactly to zero, while L2 (ridge) adds α times the sum of w² and only shrinks them.

What is the difference between R² and adjusted R²?

R² is the share of the variance of y that the model explains. Adding any predictor, even random numbers, never lowers it. Adjusted R² = 1 − (1 − R²)(n − 1)/(n − p − 1) charges for each predictor p, so it falls when a new predictor explains less than it costs. It can be negative.

Which loss function is best for regression with outliers?

MAE, Huber and log-cosh all limit the pull of large residuals, because their gradients stop growing: sign(r), δ·sign(r) and tanh(r). MSE's gradient 2r grows with the residual, so a few outliers drag the line. Huber with a δ near the typical noise size keeps MSE's smoothness for small residuals.

Should I scale features before gradient descent?

Yes for gradient descent. Scaling does not change the least-squares answer, but it changes the Hessian. Standardising each feature to mean 0 and standard deviation 1 makes the condition number small, so one learning rate suits every weight. On raw data the safe rate is set by the largest feature.

Related on Skill-Lync

Sources

  • Goodfellow, Bengio and Courville, Deep Learning (MIT Press, 2016), deeplearningbook.org: 4.3 and 4.3.1 (gradient descent, learning rate, Hessian eigenvalues and condition number, optimal step 1/λmax), 5.1.4 (MSE, normal equations), 7.1.1 and 7.1.2 (weight decay = ridge, L1 sparsity).
  • Gabriel Goh, "Why Momentum Really Works", Distill, 4 April 2017: 0 < αλi < 2, optimal step 2/(λ1 + λn), condition number.
  • scikit-learn 1.9 documentation: r2_score, mean_squared_error, mean_absolute_error, root_mean_squared_error (user guide 3.4.6); Lasso and Ridge objectives (user guide 1.1.2-1.1.3); HuberRegressor (epsilon 1.35, 95 % efficiency, scale σ); SGDRegressor (learning_rate, eta0).
  • Keras 3 API, regression losses: Huber (δ) and LogCosh definitions.
  • Robert Nau, Duke University, "Linear regression models: mathematics of simple regression": adjusted R² and n − (k + 1).
  • Skill-Lync, the 111 public prediction challenge reports, read 23 Nov 2026.
Free counselling

From a loss curve to a model you can defend.

Data roles want people who can say why a model converged, what its error means in the units of the problem, and whether it will hold on new data. A Skill-Lync counsellor can map the data science or machine learning course that fits your background.

Talk to a course counsellor

Free. We call you back, usually the same day.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.