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.

Feedforward neuraal netwerk met back propagation

Leerdoelenยถ

  • Feedforward neural network implementeren met PyTorch

  • PyTorch nn.Module gebruiken voor model definitie

  • ReLU activatie en Softmax output voor multi-class classificatie

  • Cross-entropy loss gebruiken met PyTorch

  • Model trainen met PyTorch optimizer (SGD)

  • Model performance evalueren op 3-class classificatie

  • PyTorchโ€™s ingebouwde tools gebruiken voor visualisatie en debugging

Using device: cpu

1. Data Loading en Exploratieยถ

We gebruiken de volledige Iris dataset met alle 3 klassen:

  • Setosa (klasse 0)

  • Versicolor (klasse 1)

  • Virginica (klasse 2)

Total samples: 150

Class distribution:
  Setosa (0): 50 samples (33.3%)
  Versicolor (1): 50 samples (33.3%)
  Virginica (2): 50 samples (33.3%)

Features: {iris.feature_names}

First few rows from each class:
Loading...
Loading...

2. Data Voorbereidingยถ

We bereiden de data voor door:

  1. Train/test split (80/20)

  2. Feature standardization (mean=0, std=1)

  3. One-hot encoding van de target labels voor multi-class classificatie

Training set: 120 samples
Test set: 30 samples
Number of features: 4
Number of classes: 3

Data is on device: cpu

Class distribution in training set:
  Setosa (0): 40 samples (33.3%)
  Versicolor (1): 40 samples (33.3%)
  Virginica (2): 40 samples (33.3%)

Note: PyTorch's CrossEntropyLoss handles softmax and one-hot encoding internally!

3. Neural Network Architectuur met PyTorchยถ

We bouwen een feedforward neural network met PyTorchโ€™s nn.Module:

Input Layer โ†’ Hidden Layer โ†’ Output Layer

  • Input: 4 features (sepal length, sepal width, petal length, petal width)

  • Hidden Layer: 8 neurons met ReLU activatie

  • Output Layer: 3 neurons (voor 3 klassen)

Loss Functieยถ

CrossEntropyLoss in PyTorch (incl. Softmax):

LCE=โˆ’1nโˆ‘i=1nlogโก(ezyiโˆ‘j=1Kezj)\mathcal{L}_{CE} = -\frac{1}{n} \sum_{i=1}^{n} \log\left(\frac{e^{z_{y_i}}}{\sum_{j=1}^{K} e^{z_j}}\right)
โœ“ PyTorch Neural Network Model Created!

Model Architecture:
NeuralNetwork(
  (fc1): Linear(in_features=4, out_features=8, bias=True)
  (relu): ReLU()
  (fc2): Linear(in_features=8, out_features=3, bias=True)
)

Total parameters: 67

Parameter details:
  fc1.weight: torch.Size([8, 4]) (32 parameters)
  fc1.bias: torch.Size([8]) (8 parameters)
  fc2.weight: torch.Size([3, 8]) (24 parameters)
  fc2.bias: torch.Size([3]) (3 parameters)

4. Loss Functie en Optimizerยถ

PyTorch maakt training veel eenvoudiger:

  • Loss functie: nn.CrossEntropyLoss() combineert Softmax + Cross-Entropy

  • Optimizer: optim.SGD() implementeert gradient descent met momentum optie

  • Backpropagation: Gebeurt automatisch met loss.backward()

โœ“ Loss function and optimizer configured!

Loss function: CrossEntropyLoss()
Optimizer: SGD (
Parameter Group 0
    dampening: 0
    differentiable: False
    foreach: None
    fused: None
    lr: 0.1
    maximize: False
    momentum: 0
    nesterov: False
    weight_decay: 0
)
Learning rate: 0.1

5. Training het Neural Network met PyTorchยถ

De training loop is veel eenvoudiger met PyTorch:

  1. Forward pass: outputs = model(inputs)

  2. Compute loss: loss = criterion(outputs, targets)

  3. Backward pass: loss.backward() (automatische backpropagation!)

  4. Update weights: optimizer.step()

Training Neural Network with PyTorch...
Architecture: 4 โ†’ 8 (ReLU) โ†’ 3
Learning rate: 0.1
Epochs: 2000

Training progress:
----------------------------------------------------------------------
Epoch    1 | Train Loss: 1.1086 | Test Loss: 0.8888 | Train Acc: 43.33% | Test Acc: 63.33%
Epoch  200 | Train Loss: 0.1244 | Test Loss: 0.1427 | Train Acc: 96.67% | Test Acc: 96.67%
Epoch  400 | Train Loss: 0.0727 | Test Loss: 0.0897 | Train Acc: 97.50% | Test Acc: 96.67%
Epoch  600 | Train Loss: 0.0565 | Test Loss: 0.0759 | Train Acc: 97.50% | Test Acc: 96.67%
Epoch  800 | Train Loss: 0.0488 | Test Loss: 0.0707 | Train Acc: 98.33% | Test Acc: 96.67%
Epoch 1000 | Train Loss: 0.0442 | Test Loss: 0.0692 | Train Acc: 98.33% | Test Acc: 96.67%
Epoch 1200 | Train Loss: 0.0411 | Test Loss: 0.0695 | Train Acc: 98.33% | Test Acc: 96.67%
Epoch 1400 | Train Loss: 0.0388 | Test Loss: 0.0713 | Train Acc: 98.33% | Test Acc: 96.67%
Epoch 1600 | Train Loss: 0.0369 | Test Loss: 0.0742 | Train Acc: 98.33% | Test Acc: 96.67%
Epoch 1800 | Train Loss: 0.0354 | Test Loss: 0.0766 | Train Acc: 98.33% | Test Acc: 96.67%
Epoch 2000 | Train Loss: 0.0341 | Test Loss: 0.0790 | Train Acc: 98.33% | Test Acc: 96.67%
----------------------------------------------------------------------

โœ“ Training completed!

Final Results:
  Training Loss: 0.0341
  Test Loss: 0.0790
  Training Accuracy: 98.33%
  Test Accuracy: 96.67%

6. Visualisatie van Training Procesยถ

We visualiseren hoe de loss en accuracy evolueren tijdens training.

Loading...
Loading...

7. Model Evaluatieยถ

Laten we de voorspellingen analyseren en een confusion matrix maken om te zien hoe goed het model elke klasse herkent.

Test Set Predictions:
    True Label True Species  Predicted Label Predicted Species  Correct  \
0            0       Setosa                0            Setosa     True   
1            2    Virginica                2         Virginica     True   
2            1   Versicolor                1        Versicolor     True   
3            1   Versicolor                1        Versicolor     True   
4            0       Setosa                0            Setosa     True   
5            1   Versicolor                1        Versicolor     True   
6            0       Setosa                0            Setosa     True   
7            0       Setosa                0            Setosa     True   
8            2    Virginica                2         Virginica     True   
9            1   Versicolor                1        Versicolor     True   
10           2    Virginica                2         Virginica     True   
11           2    Virginica                2         Virginica     True   
12           2    Virginica                2         Virginica     True   
13           1   Versicolor                1        Versicolor     True   
14           0       Setosa                0            Setosa     True   
15           0       Setosa                0            Setosa     True   
16           0       Setosa                0            Setosa     True   
17           1   Versicolor                1        Versicolor     True   
18           1   Versicolor                1        Versicolor     True   
19           2    Virginica                2         Virginica     True   
20           0       Setosa                0            Setosa     True   
21           2    Virginica                2         Virginica     True   
22           1   Versicolor                1        Versicolor     True   
23           2    Virginica                2         Virginica     True   
24           2    Virginica                2         Virginica     True   
25           1   Versicolor                2         Virginica    False   
26           1   Versicolor                1        Versicolor     True   
27           0       Setosa                0            Setosa     True   
28           2    Virginica                2         Virginica     True   
29           0       Setosa                0            Setosa     True   

       P(Setosa)  P(Versicolor)  P(Virginica)  
0   9.999610e-01       0.000039  1.757449e-10  
1   9.504844e-05       0.239251  7.606544e-01  
2   1.875296e-02       0.980820  4.270269e-04  
3   5.445493e-03       0.994315  2.393856e-04  
4   9.999787e-01       0.000021  3.070104e-11  
5   2.603072e-03       0.989533  7.863755e-03  
6   9.999881e-01       0.000012  9.195798e-13  
7   9.981330e-01       0.001867  1.980528e-11  
8   1.961295e-07       0.002403  9.975963e-01  
9   6.045294e-03       0.986548  7.407081e-03  
10  2.199855e-11       0.000032  9.999676e-01  
11  5.100688e-09       0.000081  9.999187e-01  
12  3.367440e-10       0.000007  9.999931e-01  
13  9.462506e-04       0.997271  1.782788e-03  
14  9.997646e-01       0.000235  1.141330e-11  
15  9.997123e-01       0.000288  2.536426e-11  
16  9.972774e-01       0.002723  2.407829e-13  
17  2.418574e-04       0.999639  1.188727e-04  
18  1.700104e-04       0.991062  8.768411e-03  
19  2.315869e-04       0.371975  6.277933e-01  
20  9.993082e-01       0.000692  1.394408e-12  
21  1.453819e-10       0.000002  9.999981e-01  
22  3.425601e-05       0.998091  1.874920e-03  
23  1.270035e-06       0.188950  8.110488e-01  
24  1.833154e-10       0.000009  9.999906e-01  
25  1.128598e-05       0.264268  7.357206e-01  
26  9.528662e-05       0.998217  1.687202e-03  
27  9.934990e-01       0.006501  4.232325e-12  
28  4.847093e-07       0.009062  9.909378e-01  
29  9.994584e-01       0.000542  1.297925e-11  

Test Accuracy: 96.67%
Correct predictions: 29 / 30
Loading...

Confusion Matrix Analysis:
Diagonal (correct predictions): [10  9 10]
Total correct: 29 / 30

Per-class accuracy:
  Setosa: 10/10 = 100.00%
  Versicolor: 9/10 = 90.00%
  Virginica: 10/10 = 100.00%

8. Decision Boundaries Visualisatieยถ

We visualiseren de decision boundaries van het neural network in 2D (gebruikmakend van de twee belangrijkste features).

Training 2D neural network for visualization...
2D Model Test Accuracy: 96.67%
Loading...

โœ“ Decision boundaries visualisatie compleet!
Merk op hoe het neural network non-lineaire decision boundaries kan leren dankzij de hidden layer.

9. Model Inspectie met PyTorchยถ

PyTorch biedt handige tools om het model te inspecteren.

======================================================================
MODEL SUMMARY
======================================================================

NeuralNetwork(
  (fc1): Linear(in_features=4, out_features=8, bias=True)
  (relu): ReLU()
  (fc2): Linear(in_features=8, out_features=3, bias=True)
)

======================================================================
PARAMETER DETAILS
======================================================================

fc1.weight:
  Shape: torch.Size([8, 4])
  Number of parameters: 32
  Requires gradient: True
  Sample values:
tensor([[ 0.8500, -0.7660,  2.8484,  1.1504],
        [-0.8707, -0.0582,  0.6883,  0.7688],
        [-0.8666,  0.2275, -1.0095, -1.8327]])

fc1.bias:
  Shape: torch.Size([8])
  Number of parameters: 8
  Requires gradient: True
  Sample values:
tensor([-0.1341,  0.3674,  0.1801,  0.7176,  0.6453, -0.5758,  2.2791,  0.4985])

fc2.weight:
  Shape: torch.Size([3, 8])
  Number of parameters: 24
  Requires gradient: True
  Sample values:
tensor([[-1.0107, -0.9730,  1.2355,  0.3388, -1.5030, -0.5591,  0.0304, -0.8294],
        [-0.3976, -0.1520, -1.5935,  0.0036, -0.0645, -0.7683,  1.4653, -0.1179],
        [ 1.9803,  0.4127, -0.7380, -1.3845, -0.0356,  1.1195, -2.5978, -0.1518]])

fc2.bias:
  Shape: torch.Size([3])
  Number of parameters: 3
  Requires gradient: True
  Sample values:
tensor([ 0.0111,  1.0494, -1.1958])

======================================================================
TOTAL PARAMETERS: 67
TRAINABLE PARAMETERS: 67
======================================================================

======================================================================
GRADIENT INFORMATION (from last training step)
======================================================================

fc1.weight:
  Gradient shape: torch.Size([8, 4])
  Gradient mean: -0.000161
  Gradient std: 0.000948
  Gradient norm: 0.005355

fc1.bias:
  Gradient shape: torch.Size([8])
  Gradient mean: -0.000050
  Gradient std: 0.001579
  Gradient norm: 0.004181

fc2.weight:
  Gradient shape: torch.Size([3, 8])
  Gradient mean: -0.000000
  Gradient std: 0.001164
  Gradient norm: 0.005580

fc2.bias:
  Gradient shape: torch.Size([3])
  Gradient mean: -0.000000
  Gradient std: 0.000545
  Gradient norm: 0.000771