🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
Search courses…
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Linear Regression — Complete Guide with Math and Code

ML FoundationsRegression🟢 Free Lesson

Advertisement

Supervised Learning

From Scatter Plots to Predictions — The Simplest ML Algorithm

Linear regression finds the best straight line through your data. It is fast, interpretable, and a powerful baseline for any regression problem.

  • Ordinary Least Squares — The closed-form solution for optimal parameters

  • Gradient Descent — The iterative optimization approach that scales

  • Evaluation Metrics — R², MSE, and MAE for measuring performance

"All models are wrong, but some are useful." — George Box

Linear Regression — Complete Guide

Linear regression is the simplest and most fundamental ML algorithm. It models the relationship between variables as a straight line.


Simple Linear Regression

Linear Regression: Fitting the Best LinexyTraining data pointsŷ = wx + b (best fit line)Cost Function: ResidualsL(w,b) = Σ(yᵢ¢ ≈ ŷᵢ¢)²Each residual:eᵢ¢ = yᵢ¢ ≈ (wxᵢ¢ + b)Minimize sum of squared residuals:L = Σeᵢ¢² = Σ(yᵢ¢ ≈ wxᵢ¢ ≈ b)²Analytical solution (partial derivatives):∂L/∂w = 0 → w = Σ(xᵢ¢≈xÌ„)(yᵢ¢≈ȳ) / Σ(xᵢ¢≈xÌ„)²∂L/∂b = 0 → b = ȳ ≈ wxÌ„

Finding the Best Line

Ordinary Least Squares (OLS)

Gradient Descent

Cost Function Surface and Gradient Descent Path

Cost Function Surface and Gradient Descent TrajectoryContour Plot of L(w, b)StartOptimalw (weight)3D Loss Surface L(w, b)t=0MinThe loss surface is convex for linear regression — gradient descent finds the global minimum

Multiple Linear Regression


Evaluation Metrics

Regression Evaluation MetricsMSEMean Squared Error1/N Σ(yᵢ¢ ≈ ŷᵢ¢)²• Penalizes large errors• Differentiable ✓• Sensitive to outliersRMSERoot MSE√(1/N Σ(yᵢ¢ ≈ ŷᵢ¢)²)• Same units as y• Interpretable• Most common metricMAEMean Absolute Error1/N Σ|yᵢ¢ ≈ ŷᵢ¢|• Robust to outliers• L1 loss variant• Not differentiable at 0Coefficient of Determination1 ≈ SS_res/SS_tot• Scale-independent• 1.0 = perfect• % variance explained

Assumptions

Assumption Diagnostics1. LinearityResidual plot2. NormalityQ-Q plot / Histogram3. HomoscedasticityEqual spread4. IndependenceDurbin-Watson test5. No MulticollinearityX₁ X₂X₃ Xâ‚„VIF < 10

Polynomial Regression


from sklearn.preprocessing import PolynomialFeatures

poly = PolynomialFeatures(degree=2)

X_poly = poly.fit_transform(X)

model = LinearRegression().fit(X_poly, y)

Key Takeaways


What to Learn Next

-> Logistic Regression

Classification with probability — from linear to sigmoid.

-> Regularization

Prevent overfitting with Ridge, Lasso, and Elastic Net.

-> Model Evaluation

How to know if your model actually works — beyond accuracy.

Need Expert Machine Learning Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement