How OLS Linear Regression and Ridge Regression work
Ordinary Least Squares (OLS) linear regression models a continuous target y as a weighted linear combination of numeric features x₁, x₂, …, xₚ plus an intercept β₀, choosing weights that minimize the sum of squared residuals Σ (yᵢ − ŷᵢ)². Because OLS has a closed-form solution via QR factorization, it fits deterministically in milliseconds and produces directly interpretable coefficients: holding other features constant, a one-unit increase in xⱼ shifts the expected prediction by βⱼ.
In real-world tables, however, predictors are often correlated—such as website sessions and pageviews, or home square footage and room count. When columns move together (multicollinearity), ordinary least squares can assign wildly opposing positive and negative weights that cancel on training rows yet explode on slightly perturbed inputs. Ridge Regression resolves this instability by adding an L2 penalty α Σ βⱼ² to the squared-error objective (leaving the intercept unpenalized). Raising α smoothly shrinks large coefficients toward zero, trading a small amount of training bias for lower variance and far more reliable out-of-sample predictions.
Interpreting raw coefficients vs standardized β weights
A common mistake in multiple linear regression is ranking feature importance by raw coefficient magnitude. In the Multivariate Housing preset above, bedrooms carries a much larger raw coefficient than sqft simply because one extra bedroom is a large jump whereas one extra square foot is tiny.
To compare predictors fairly on a common scale, inspect the Standardized β column and relative magnitude bars in the table above. Standardized β equals βⱼ × (σₓⱼ / σᵧ): the predicted shift in standard deviations of y for a one-standard-deviation increase in predictor xⱼ. Use raw coefficients for algebraic prediction equations and business unit explanations, and use standardized β to spot which columns drive the majority of target variation.
Reading R², Adjusted R², RMSE, and MAE together
No single regression metric tells the entire story. Combine scale-free goodness-of-fit summaries with error metrics measured in your target’s original units:
- R² (Coefficient of Determination): Fraction of variance in
yexplained by the model relative to predicting the constant mean. Useful for high-level communication, but remember that adding noise columns never decreases training R². - Adjusted R²: Corrects R² for degrees of freedom
(n − p − 1). If you paste an irrelevant column into a small CSV, Adjusted R² drops—warning you against overfitting. - RMSE (Root Mean Squared Error): Square root of average squared error, expressed in the exact units of
y(for example thousands of dollars). Because errors are squared before averaging, RMSE penalizes occasional large misses heavily. - MAE (Mean Absolute Error): Average absolute prediction error. Comparing RMSE against MAE immediately reveals tail behavior: when RMSE is much larger than MAE, a handful of high-leverage outliers are dominating squared loss.
Diagnosing model assumptions with residual plots
A high R² does not guarantee that a linear model is appropriate. Inspect the Residuals (y − ŷ) vs Predicted chart every time you fit a CSV:
1. Curved or U-shaped residuals
Systematic curvature above and below zero means a straight hyperplane misses nonlinear structure. Try the Polynomial Regression Calculator or add spline basis features with SplineTransformer.
2. Funnel-shaped spread (heteroscedasticity)
When residual variance expands as predicted values grow—common in prices, revenue, and latency—consider modeling a log-transformed target with Compose.TransformedTargetRegressor or fitting a Gamma / Tweedie GLM.
3. Isolated extreme residuals
Because OLS squares residuals, one corrupted row can tilt the entire hyperplane. Flag bad rows first with the Outlier Calculator, or switch to Huber, RANSAC, or Theil–Sen estimators documented in Robust Regression in JS.
Tuning Ridge α and choosing between OLS, Ridge, Lasso, and ElasticNet
Choosing the right regularization strength α is a classic bias–variance tradeoff. At α = 0, Ridge Regression reduces mathematically to Ordinary Least Squares: zero shrinkage bias, lowest possible training MSE, but maximum sensitivity to collinearity and small-sample noise. As you sweep the α slider upward from 0.01 toward 50, correlated weights share credit smoothly rather than canceling each other with giant opposite signs. Pushing α too far eventually underfits, pulling every slope toward zero until predictions flatten near the sample mean of y.
In production code, never pick α purely from training R²—because training R² always peaks at α = 0. Instead, wrap StandardScaler and Linear.RidgeRegression inside a Pipeline and evaluate a logarithmic grid (for example [0.01, 0.1, 1, 10, 100]) via GridSearchCV in utils.ModelSelection. That way scaling statistics fit strictly inside each training fold without leaking validation information.
- Use OLS Linear Regression when sample count comfortably exceeds feature count, predictors are low-correlation, and you want unbiased classical parameter estimates.
- Use Ridge Regression (L2) when predictors are correlated or noisy and you expect most features to carry small real contributions.
- Use Lasso Regression (L1) when you suspect most columns are irrelevant and want automatic sparse feature selection that drives weak weights to exact zero.
- Use ElasticNet (L1 + L2) when your dataset combines both challenges—correlated predictor groups plus irrelevant noise columns.
Moving from browser exploration to JavaScript or Python code
Every fit above runs locally in pure TypeScript using Linear.LinearRegression (QR least squares) and Linear.RidgeRegression from @kanaries/ml, with numerical results verified against scikit-learn. Use the JavaScript and Python tabs to copy a runnable pipeline with your exact CSV values, export predictions and residuals for spreadsheets, or share your configured model via Share link or Embed in the header bar.
Once your model passes validation on held-out data, serialize the entire preprocessing and regression Pipeline with JSON.stringify(model) and revive it inside a browser tab, Web Worker, Cloudflare Worker, or Node.js API using loadModel(). Because linear models store only one weight per feature plus an intercept, serialized artifacts stay under a few kilobytes and score thousands of rows in sub-millisecond latency without maintaining a Python backend.