Linear Regression maths — the equation behind .fit()
model.fit() is not magic. It solves y = Xβ + ε using least squares. Understand the equation, the cost function, and the geometry.
The output will appear here.
Linear Regression maths: EQUATION: y = β₀ + β₁x₁ + ... + ε. β are coefficients, ε is error. COST FUNCTION: MSE = (1/n)Σ(y - ŷ)². Convex bowl shape — one minimum. SOLUTION (Normal Equation): β = (XᵀX)⁻¹Xᵀy. Closed-form — computed in one matrix op. XᵀX is the Gram matrix. Xᵀy is the feature-target correlation. Inverse makes it a 'divide'. sklearn uses SVD (more stable than inverse). GEOMETRY: X defines a plane. y is a point above the plane. ŷ is the projection. Residual (y - ŷ) is perpendicular to the plane. Least squares = minimize squared perpendicular distance. GRADIENT DESCENT (alternative): start at random β, take steps in -gradient direction. Used when XᵀX is too big to invert (millions of features). ASSUMPTIONS (often violated, often don't matter): Linearity, independence, homoscedasticity (constant variance), normal residuals. KEY INSIGHT: .fit() is not magic. It's matrix algebra. Understand it = debug models.
-
Increase noise from 2 to 10→ learned coefficients will be further from true — more error -
Change true_slope from 3 to -2→ negative relationship — cost function still works -
Add a non-linear term: y = 2 + 3x + 0.5x² + noise→ LinearRegression will underfit — need PolynomialFeatures -
Compute R² manually: 1 - SS_res/SS_tot→ matches model.score()