Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

In dit labo passen we verschillende methoden toe om lineaire regressie parameters te schatten:

  1. De closed form OLS oplossing

  2. Vergelijking met scikit-learn, NumPy en statsmodels OLS implementaties

  3. Gradient berekening met PyTorch autograd

  4. Implementatie van Stochastic Gradient Descent

Dataset shape: (20640, 9)

Features: ['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population', 'AveOccup', 'Latitude', 'Longitude']

First rows:
Loading...

Basic statistics:
Loading...

Design matrix

We werken met slechts twee predictor-variabelen:

  1. MedInc: median income in block group

  2. AveRooms: average number of rooms per household

De target variabele is MedHouseVal: median house value for California districts, expressed in hundreds of thousands of dollars ($100,000)

✍️

Hoe ziet de algemene matrix vorm van het model eruit?

y=Xb+e\pmb{y} = \pmb{X}\pmb{b} + \pmb{e}

✍️

Hoe ziet de parameter tensor er specifiek uit?

b=[b1b2b3]\pmb{b} = \begin{bmatrix} b_1 \cr b_2 \cr b_3 \cr \end{bmatrix}

✍️

Hoe die de design/feature matrix er specifiek uit?

X=[1x1,1x1,21x2,1x2,2⋮⋮⋮1xn,1xn,2]\pmb{X} = \begin{bmatrix} 1 & x_{1,1} & x_{1, 2} \cr 1 & x_{2,1} & x_{2, 2} \cr \vdots & \vdots & \vdots \cr 1 & x_{n,1} & x_{n, 2} \cr \end{bmatrix}

✍️

Hoe implementeren we deze tensors in Python?

Design matrix X shape: (20640, 3)
Target vector y shape: (20640,)

First 5 rows of design matrix (bias, MedInc, AveRooms):
[[1.         8.3252     6.98412698]
 [1.         8.3014     6.23813708]
 [1.         7.2574     8.28813559]
 [1.         5.6431     5.8173516 ]
 [1.         3.8462     6.28185328]]

First 5 target values:
[4.526 3.585 3.521 3.413 3.422]

Standard Scaling

x‾ic=0std(xi)=1\begin{align} \pmb{\overline{x}_i}^c &= \pmb{0} \cr std(\pmb{x_i}) &= 1 \end{align}

✍️

Conditienummer en Correlatie

✍️

Hoe is het gesteld met het conditienummer van de design matrix en de multicollineariteit bij de predictoren?

Condition number of design matrix: 1.40

Interpretation:
- Excellent: Matrix is well-conditioned
Correlation matrix:
Loading...
<Figure size 800x600 with 2 Axes>

Correlation between MedInc and AveRooms: 0.3269
Multicollinearity assessment: Low

Manuele OLS

✍️

Hoe implementeren we de analytische oplossing in Python?

b^=(XTX)−1XTy\hat{\pmb{b}} = (\pmb{X}^T\pmb{X})^{-1}\pmb{X}^T\pmb{y}
Closed-form OLS coefficients:
  β₀ (bias):        0.000000
  β₁ (MedInc):    0.714787
  β₂ (AveRooms): -0.081712

Model performance:
  MSE:  0.520589
  R²:   0.479411

Scikit-learn OLS

Hoe implementeren we OLS met scikit-learn?

Scikit-learn OLS coefficients:
  β₀ (bias):        0.000000
  β₁ (MedInc):    0.714787
  β₂ (AveRooms): -0.081712

Model performance:
  MSE:  0.520589
  R²:   0.479411

NumPy OLS

Hoe implementeren we OLS met NumPy[1]?

NumPy lstsq OLS coefficients:
  β₀ (bias):        0.000000
  β₁ (MedInc):    0.714787
  β₂ (AveRooms): -0.081712

Model performance:
  MSE:  0.520589
  R²:   0.479411

Additional info:
  Residual sum of squares: 10744.959552
  Rank of design matrix: 3

Statsmodels OLS

Hoe implementeren we OLS met statsmodels?

Statsmodels OLS coefficients:
  β₀ (bias):        0.000000
  β₁ (MedInc):    0.714787
  β₂ (AveRooms): -0.081712

Full statistical summary:
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      y   R-squared:                       0.479
Model:                            OLS   Adj. R-squared:                  0.479
Method:                 Least Squares   F-statistic:                     9502.
Date:                Fri, 17 Oct 2025   Prob (F-statistic):               0.00
Time:                        15:18:07   Log-Likelihood:                -22550.
No. Observations:               20640   AIC:                         4.511e+04
Df Residuals:                   20637   BIC:                         4.513e+04
Df Model:                           2                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const       4.753e-16      0.005   9.46e-14      1.000      -0.010       0.010
x1             0.7148      0.005    134.497      0.000       0.704       0.725
x2            -0.0817      0.005    -15.375      0.000      -0.092      -0.071
==============================================================================
Omnibus:                     4804.179   Durbin-Watson:                   0.692
Prob(Omnibus):                  0.000   Jarque-Bera (JB):            12852.863
Skew:                           1.250   Prob(JB):                         0.00
Kurtosis:                       5.949   Cond. No.                         1.40
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

Samenvatting

Coefficient comparison:
Loading...

Automatische differentiatie

PyTorch’s automatische differentiatie autograd berekent gradiënten automatisch. De bibliotheek is voornamelijk bedoeld voor gebruik bij neurale netwerken, maar hier kunnen we er al een eerste keer gebruik van maken om gradient descent te implementeren voor ons lineaire regressiemodel.

Hieronder eerst een demonstratie met een eenvoudig voorbeeld.

Example: f(x) = x² + 3x + 5
Analytical gradient: f'(x) = 2x + 3

Evaluate at x = 2.0
f(x) = 15.0
Computed gradient f'(x) = 7.0
Analytical gradient at x=2: 2(2) + 3 = 7

Hoe werkt automatische differentiatie?

In het bovenstaande voorbeeld zien we hoe PyTorch de gradiënt automatisch berekent:

  1. Forward pass: We definiëren de functie f = x² + 3x + 5 en PyTorch houdt alle operaties bij in een computational graph.

  2. Backward pass: Bij het aanroepen van f.backward() past PyTorch de som regel toe om de gradiënt te berekenen. Voor elke operatie in de graph kent PyTorch de afgeleide:

    • Afgeleide van x²: 2x

    • Afgeleide van 3x: 3

    • Afgeleide van constante: 0

  3. Resultaat: De gradiënt wordt opgeslagen in x.grad. Bij x=2 vinden we f’(2) = 2(2) + 3 = 7.

Dit mechanisme is fundamenteel voor gradient descent: we kunnen complexe functies definiëren en PyTorch berekent automatisch de gradiënten die nodig zijn om de parameters te optimaliseren.

✍️

Hoe implementeren we automatische differentiatie voor:

f(x,y)=x2y+3xy2f(x, y) = x^2y + 3xy^2
Example: f(x, y) = x²y + 3xy²
∂f/∂x = 2xy + 3y²
∂f/∂y = x² + 6xy

Evaluate at x = 3.0, y = 2.0
f(x, y) = 54.0

Computed gradients:
  ∂f/∂x = 24.0
  ∂f/∂y = 45.0

Analytical gradients at x=3, y=2:
  ∂f/∂x = 2(3)(2) + 3(2)² = 24
  ∂f/∂y = (3)² + 6(3)(2) = 45

Gradient Descent met autograd

✍️

Initial parameters: tensor([0., 0., 0.], requires_grad=True)
Iteration 1/1000, Loss: 1.000000
Iteration 100/1000, Loss: 0.536470
Iteration 200/1000, Loss: 0.521565
Iteration 300/1000, Loss: 0.520654
Iteration 400/1000, Loss: 0.520593
Iteration 500/1000, Loss: 0.520589
Iteration 600/1000, Loss: 0.520589
Iteration 700/1000, Loss: 0.520589
Iteration 800/1000, Loss: 0.520589
Iteration 900/1000, Loss: 0.520589
Iteration 1000/1000, Loss: 0.520589

Final parameters: {b}

Comparison with closed-form OLS:
  β₀: GD=0.000000, OLS=0.000000
  β₁: GD=0.714785, OLS=0.714787
  β₂: GD=-0.081711, OLS=-0.081712

Stochastic Gradient Descent

🎯

Mini-batch Stochastic Gradient Descent
==================================================
Dataset size: 20640
Batch size: 256
Batches per epoch: 81
Number of epochs: 50

Epoch 1/50, Avg Loss: 0.669930
Epoch 10/50, Avg Loss: 0.522375
Epoch 10/50, Avg Loss: 0.522375
Epoch 20/50, Avg Loss: 0.521220
Epoch 20/50, Avg Loss: 0.521220
Epoch 30/50, Avg Loss: 0.520929
Epoch 30/50, Avg Loss: 0.520929
Epoch 40/50, Avg Loss: 0.520946
Epoch 40/50, Avg Loss: 0.520946
Epoch 50/50, Avg Loss: 0.521442

Training completed!

Final SGD parameters:
  β₀ (bias):        0.000466
  β₁ (MedInc):    0.711527
  β₂ (AveRooms): -0.072727

Comparison with other methods:
  β₀: SGD=0.000466, GD=0.000000, OLS=0.000000
  β₁: SGD=0.711527, GD=0.714785, OLS=0.714787
  β₂: SGD=-0.072727, GD=-0.081711, OLS=-0.081712
Epoch 50/50, Avg Loss: 0.521442

Training completed!

Final SGD parameters:
  β₀ (bias):        0.000466
  β₁ (MedInc):    0.711527
  β₂ (AveRooms): -0.072727

Comparison with other methods:
  β₀: SGD=0.000466, GD=0.000000, OLS=0.000000
  β₁: SGD=0.711527, GD=0.714785, OLS=0.714787
  β₂: SGD=-0.072727, GD=-0.081711, OLS=-0.081712
<Figure size 1500x500 with 2 Axes>

Final SGD model performance:
  MSE:  0.520662
  R²:   0.479338
Footnotes
  1. NumPy’s lstsq gebruikt SVD (Singular Value Decomposition) wat numeriek stabieler is dan directe matrix inversie.