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
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?
- Converged: the weights agree with the normal equations to 14 digits. η = 0.1 is 0.1 of the limit for standardised x.
Which learning rates converge on this data? The Hessian of the MSE gives the limit 2/λmax; five rates around it show what happens.
| Hessian of the MSE | Standardised | Raw |
|---|
| η / limit | η | slowest factor |1 − ηλ| | What happens |
|---|
The sweep uses the features as set above (standardised or raw) and the MSE. Huber's and log-cosh's curvature is at most half of the MSE's, so their limit is at least twice this one.
How do MSE, MAE, Huber and log-cosh treat a large residual, and how far do three outliers pull each one's best line?
| Loss | Slope w | Intercept b | Slope moved by |
|---|
Demo A only (one feature). Each line is the exact minimum of that loss: least squares by the normal equations, MAE by the best line through two data points, Huber and log-cosh by Newton's method. Gradient descent in tab 1 reaches the same lines.
L1/L2 regularisation: which coefficients does lasso set to exactly zero, and how does ridge shrink them, as α grows?
Same objectives as scikit-learn: Ridge minimises ‖y − Xw − b‖² + α‖w‖², Lasso minimises (1/2n)‖y − Xw − b‖² + α‖w‖₁; the intercept is not penalised. So the same α is far stronger in Lasso. With "standardise" on, the coefficients are for the standardised features, as after StandardScaler. Try demo B: x4 and x5 do not enter y.
How good is the least-squares fit: MSE, RMSE, MAE, R² and adjusted R², on all rows, on a training split and on held-out rows?
| Rows | n | MSE | RMSE | MAE | R² | adj. R² |
|---|
The split shuffles the rows with mulberry32 and holds out the first ceil(share × n), like train_test_split's default test share of 0.25, but scikit-learn's random_state gives a different shuffle. Test R² uses the test rows' own mean, as r2_score does.
Gradient descent in Python from scratch with any of the four losses, then the scikit-learn equivalents, on demo A.
# Gradient descent for linear regression from scratch (NumPy), on the demo A data of
# https://skill-lync.com/tools/gradient-descent-calculator (same seeded generator, so the numbers match the tool).
import numpy as np
def mulberry32(seed): # the tool's random number generator, written for Python
a = seed & 0xFFFFFFFF
def rnd():
nonlocal a
a = (a + 0x6D2B79F5) & 0xFFFFFFFF
t = ((a ^ (a >> 15)) * (1 | a)) & 0xFFFFFFFF
t = ((t + (((t ^ (t >> 7)) * (61 | t)) & 0xFFFFFFFF)) & 0xFFFFFFFF) ^ t
return ((t ^ (t >> 14)) & 0xFFFFFFFF) / 4294967296
return rnd
rnd, xs, ys = mulberry32(2026), [], []
for _ in range(30): # demo A: x uniform in [20, 80], y = 12 + 0.8 x + 2 z
x = 20 + 60 * rnd()
u1, u2 = 1 - rnd(), rnd()
xs.append(x)
ys.append(12 + 0.8 * x + 2 * np.sqrt(-2 * np.log(u1)) * np.cos(2 * np.pi * u2))
X, y = np.array(xs).reshape(-1, 1), np.array(ys)
def loss_grad(r, kind="mse", delta=1.0): # mean loss, and its derivative per sample; r = y_hat - y
if kind == "mse":
return np.mean(r ** 2), 2 * r
if kind == "mae":
return np.mean(np.abs(r)), np.sign(r)
if kind == "huber":
q = np.abs(r) <= delta
return np.mean(np.where(q, 0.5 * r ** 2, delta * np.abs(r) - 0.5 * delta ** 2)), np.where(q, r, delta * np.sign(r))
if kind == "logcosh":
return np.mean(np.logaddexp(r, -r) - np.log(2)), np.tanh(r)
raise ValueError(kind)
def gradient_descent(X, y, eta=0.1, iters=200, kind="mse", delta=1.0, scale=True):
mu, sd = X.mean(axis=0), X.std(axis=0) # population sd, as StandardScaler
Z = (X - mu) / sd if scale else X
w, b, hist = np.zeros(X.shape[1]), 0.0, []
for k in range(iters + 1):
r = Z @ w + b - y
L, g = loss_grad(r, kind, delta)
hist.append(L)
if k == iters or not np.isfinite(L) or L > 1e200:
break
w = w - eta * (Z.T @ g) / len(y)
b = b - eta * g.mean()
if scale: # back to the original units of x
b, w = b - np.sum(w * mu / sd), w / sd
return w, b, hist
w, b, hist = gradient_descent(X, y, eta=0.1, iters=200)
wh, bh, _ = gradient_descent(X, y, eta=0.5, iters=2000, kind="huber", delta=1.0)
X1 = np.column_stack([X, np.ones(len(y))])
theta = np.linalg.lstsq(X1, y, rcond=None)[0] # least squares (normal equations)
H = 2 * X1.T @ X1 / len(y) # Hessian of the MSE in (w, b), raw x
print("gd_w =", w[0])
print("gd_b =", b)
print("gd_loss =", hist[-1])
print("huber_w =", wh[0])
print("huber_b =", bh)
print("ols_w =", theta[0])
print("ols_b =", theta[1])
print("eta_crit_raw =", 2 / np.linalg.eigvalsh(H).max())
try:
from sklearn.linear_model import LinearRegression, Ridge, Lasso, HuberRegressor, SGDRegressor
from sklearn.metrics import r2_score
from sklearn.preprocessing import StandardScaler
lr = LinearRegression().fit(X, y)
print("sk_ols_w =", lr.coef_[0])
print("sk_r2 =", r2_score(y, lr.predict(X)))
print("sk_ridge_w =", Ridge(alpha=10.0).fit(X, y).coef_[0]) # ||y - Xw||^2 + alpha ||w||^2
print("sk_lasso_w =", Lasso(alpha=0.5, tol=1e-12, max_iter=100000).fit(X, y).coef_[0]) # (1/2n)||y - Xw||^2 + alpha ||w||_1
print("sk_huber_w =", HuberRegressor(epsilon=1.35).fit(X, y).coef_[0]) # also fits a scale sigma
Z = StandardScaler().fit_transform(X)
print("sk_sgd_w =", SGDRegressor(random_state=0).fit(Z, y).coef_[0] / X.std()) # stochastic: close, not equal
except ImportError:
print("scikit-learn is not installed: from-scratch results only")
With NumPy 2.5.5 and scikit-learn 1.9.1 it prints gd_w = 0.8233669439, gd_b = 10.92025803 and huber_w = 0.8232706105: the tool's numbers (tab 1 with demo A, η = 0.1 and 200 iterations; Huber δ = 1, η = 0.5, 2,000 iterations) to 10 digits. eta_crit_raw = 0.000301292 is tab 2's limit for raw x. Our verifier runs this exact script at every update. LinearRegression and Ridge(alpha=10) match the tool to 10 digits (0.82336694, 0.82254722), and Lasso(alpha=0.5) to its tolerance (0.82187208). HuberRegressor gives 0.822668, not the same as the fixed-δ Huber above: it also fits a scale σ and reads epsilon = 1.35 in units of σ, plus a small α‖w‖² penalty. SGDRegressor gives 0.82154: it updates on one sample at a time with a decaying rate, so it lands near, not on, the answer.
Adjusted R²: type R², n, the number of predictors p and the adjusted R² you got. The tool finds the formula that gives your number.
- Type all four numbers, or fill the example.
Learning rate: say what η you used on the loaded data and what happened. The tool says whether it should have converged, and why not.
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.
- 50 / 111Q2 answered as regularisation (lasso / ridge, penalty on weights). report 1report 2
- 40 / 111Q2 answered as loss functions (L1 = MAE / absolute, L2 = MSE / squared). report 1report 2
- 5 / 111Q2 gives both readings (loss and regularisation). report 1report 2
- 8 / 111Q2 claims L1 estimates the median and L2 the mean of the data. report 1report 2
- 101 / 106Q3 names MSE (squared error). report 1report 2
- 57 / 106Q3 names Huber loss. report 1report 2
- 39 / 106Q3 names log-cosh. report 1report 2
- 25 / 106Q3 names quantile loss. report 1report 2
- 45 / 88Q4 mentions overshooting, divergence, oscillation or missing the minimum. report 1report 2
- 84 / 97Q5 names R-squared (or coefficient of determination). report 1report 2
- 39 / 97Q5 names adjusted R-squared. report 1report 2
- 12 / 97Q5 names a train/test split. report 1report 2
- 15 / 97Q5 names residual plots or residual analysis. report 1report 2
- 26 / 111Adjusted R-squared formula written in the answer (any form). report 1report 2
- 4 / 111Claims adjusted R-squared lies between 0 and 1. report 1report 2
- 35 / 111Q1 Python gradient-descent code visible in the text, written from scratch (loop with a parameter update). report 1report 2
- 2 / 35Q1 code scales or normalises features first. report 1report 2
- 8 / 35Q1 code prints or states how many iterations it took to converge. report 1report 2
- 3 / 35Q1 code declares 1000 iterations or epochs but loops len(x) times. report 1report 2
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.
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
- Sample vs population variance calculator (the statistics week of the same program: n vs n − 1)
- Curve fitting calculator (polyfit and curve_fit: least squares for curves)
- Newton-Raphson method calculator (the other way down a curve: steps from the second derivative)
- Genetic algorithm simulator (optimisation without any gradient)
- All free engineering tools
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.