@@ -405,6 +405,8 @@ weights_2 = 0.2 * np.random.random((hidden_size, num_labels)) - 0.1
405
405
```
406
406
407
407
** 5.** Set up the neural network's learning experiment with a training loop and start the training process.
408
+ Note that the model is evaluated at each epoch by running the model on test
409
+ set, thus the model improvement can be tracked vs. epoch.
408
410
409
411
Start the training process:
410
412
@@ -419,6 +421,11 @@ store_test_accurate_pred = []
419
421
# This is a training loop.
420
422
# Run the learning experiment for a defined number of epochs (iterations).
421
423
for j in range(epochs):
424
+
425
+ #################
426
+ # Training step #
427
+ #################
428
+
422
429
# Set the initial loss/error and the number of accurate predictions to zero.
423
430
training_loss = 0.0
424
431
training_accurate_predictions = 0
@@ -467,26 +474,26 @@ for j in range(epochs):
467
474
store_training_loss.append(training_loss)
468
475
store_training_accurate_pred.append(training_accurate_predictions)
469
476
470
- # Evaluate on the test set:
471
- # 1. Set the initial error and the number of accurate predictions to zero.
472
- test_loss = 0.0
473
- test_accurate_predictions = 0
474
-
475
- # 2. Start testing the model by evaluating on the test image dataset.
476
- for i in range(len(test_images)):
477
- # 1. Pass the test images through the input layer.
478
- layer_0 = test_images[i]
479
- # 2. Compute the weighted sum of the test image inputs in and
480
- # pass the hidden layer's output through ReLU.
481
- layer_1 = relu(np.dot(layer_0, weights_1))
482
- # 3. Compute the weighted sum of the hidden layer's inputs.
483
- # Produce a 10-dimensional vector with 10 scores .
484
- layer_2 = np.dot(layer_1, weights_2 )
477
+ ################
478
+ # Testing step #
479
+ ################
480
+
481
+ # Evaluate model performance on the test set at each epoch.
482
+
483
+ # Unlike the training step, the weights are not modified for each image
484
+ # (or batch). Therefore the model can be applied to the test images in a
485
+ # vectorized manner, eliminating the need to loop over each image
486
+ # individually:
487
+
488
+ results = relu(test_images @ weights_1) @ weights_2
489
+
490
+ # Measure the error between the actual label (truth) and prediction values .
491
+ test_loss = np.sum((test_labels - results)**2 )
485
492
486
- # 4. Measure the error between the actual label (truth) and prediction values.
487
- test_loss + = np.sum((test_labels[i] - layer_2) ** 2)
488
- # 5. Increment the accurate prediction count.
489
- test_accurate_predictions += int(np.argmax(layer_2) == np.argmax(test_labels[i]) )
493
+ # Measure prediction accuracy on test set
494
+ test_accurate_predictions = np.sum(
495
+ np.argmax(results, axis=1) == np.argmax(test_labels, axis=1)
496
+ )
490
497
491
498
# Store test set losses and accurate predictions.
492
499
store_test_loss.append(test_loss)
0 commit comments