ReWheel 1.2.0__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rewheel/__init__.py +14 -0
- rewheel/engine/__init__.py +9 -0
- rewheel/engine/activation_functions.py +104 -0
- rewheel/engine/classes/__init__.py +7 -0
- rewheel/engine/classes/architecture.py +75 -0
- rewheel/engine/classes/stopping_crit.py +61 -0
- rewheel/engine/classes/training_log.py +103 -0
- rewheel/engine/classes/training_params.py +27 -0
- rewheel/engine/classes/update_params.py +61 -0
- rewheel/engine/loss.py +60 -0
- rewheel/engine/nn_sim.py +271 -0
- rewheel/engine/propagation.py +222 -0
- rewheel/engine/training/__init__.py +3 -0
- rewheel/engine/training/steps.py +229 -0
- rewheel/engine/training/stopping.py +220 -0
- rewheel/engine/training/trainer.py +233 -0
- rewheel/engine/utils.py +221 -0
- rewheel/tools/__init__.py +3 -0
- rewheel/tools/save_n_load.py +175 -0
- rewheel-1.2.0.dist-info/METADATA +958 -0
- rewheel-1.2.0.dist-info/RECORD +23 -0
- rewheel-1.2.0.dist-info/WHEEL +5 -0
- rewheel-1.2.0.dist-info/licenses/LICENSE +674 -0
rewheel/__init__.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Module containing the activation functions and their derivatives."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
# Linear
|
|
5
|
+
def linear(x):
|
|
6
|
+
"""Linear activation function."""
|
|
7
|
+
return x
|
|
8
|
+
|
|
9
|
+
def linear_derivative(x):
|
|
10
|
+
"""Derivative of the linear activation function."""
|
|
11
|
+
return np.ones_like(x)
|
|
12
|
+
|
|
13
|
+
# Sigmoid
|
|
14
|
+
def sigmoid(x):
|
|
15
|
+
"""Sigmoid activation function."""
|
|
16
|
+
return 1 / (1 + np.exp(-x))
|
|
17
|
+
|
|
18
|
+
def sigmoid_derivative(x):
|
|
19
|
+
"""Derivative of the sigmoid activation function."""
|
|
20
|
+
s = sigmoid(x)
|
|
21
|
+
return s * (1 - s)
|
|
22
|
+
|
|
23
|
+
# Hyperbolic tangent
|
|
24
|
+
def tanh(x):
|
|
25
|
+
"""Hyperbolic tangent activation function."""
|
|
26
|
+
return np.tanh(x)
|
|
27
|
+
|
|
28
|
+
def tanh_derivative(x):
|
|
29
|
+
"""Derivative of the hyperbolic tangent activation function."""
|
|
30
|
+
return 1 - np.tanh(x)**2
|
|
31
|
+
|
|
32
|
+
# ReLU
|
|
33
|
+
def relu(x):
|
|
34
|
+
"""Rectified Linear Unit activation function."""
|
|
35
|
+
return np.maximum(0, x)
|
|
36
|
+
|
|
37
|
+
def relu_derivative(x):
|
|
38
|
+
"""Derivative of the ReLU activation function."""
|
|
39
|
+
return np.where(x > 0, 1, 0)
|
|
40
|
+
|
|
41
|
+
# Leaky ReLU
|
|
42
|
+
def leaky_relu(x, alpha=0.01):
|
|
43
|
+
"""Leaky ReLU activation function."""
|
|
44
|
+
return np.where(x > 0, x, alpha * x)
|
|
45
|
+
|
|
46
|
+
def leaky_relu_derivative(x, alpha=0.01):
|
|
47
|
+
"""Derivative of the Leaky ReLU activation function."""
|
|
48
|
+
return np.where(x > 0, 1, alpha)
|
|
49
|
+
|
|
50
|
+
# ELU
|
|
51
|
+
def elu(x, alpha=1.0):
|
|
52
|
+
"""Exponential Linear Unit activation function."""
|
|
53
|
+
return np.where(x > 0, x, alpha * np.expm1(x))
|
|
54
|
+
|
|
55
|
+
def elu_derivative(x, alpha=1.0):
|
|
56
|
+
"""Derivative of the ELU activation function."""
|
|
57
|
+
return np.where(x > 0, 1, alpha * np.exp(x))
|
|
58
|
+
|
|
59
|
+
# Softplus
|
|
60
|
+
def softplus(x):
|
|
61
|
+
"""Softplus activation function."""
|
|
62
|
+
return np.logaddexp(0, x)
|
|
63
|
+
|
|
64
|
+
def softplus_derivative(x):
|
|
65
|
+
"""Derivative of the Softplus activation function."""
|
|
66
|
+
return sigmoid(x)
|
|
67
|
+
|
|
68
|
+
# Softmax
|
|
69
|
+
def softmax(x):
|
|
70
|
+
"""Softmax activation function."""
|
|
71
|
+
exp_x = np.exp(x - np.max(x, axis=0, keepdims=True))
|
|
72
|
+
return exp_x / np.sum(exp_x, axis=0, keepdims=True)
|
|
73
|
+
|
|
74
|
+
def softmax_derivative(x):
|
|
75
|
+
"""Jacobian matrix of the Softmax activation function."""
|
|
76
|
+
s = softmax(x)
|
|
77
|
+
return np.diag(s) - np.outer(s, s)
|
|
78
|
+
|
|
79
|
+
# Activation functions dictionary
|
|
80
|
+
af_list = {
|
|
81
|
+
"LINEAR": linear,
|
|
82
|
+
"LINEAR_DERIVATIVE": linear_derivative,
|
|
83
|
+
|
|
84
|
+
"SIGMOID": sigmoid,
|
|
85
|
+
"SIGMOID_DERIVATIVE": sigmoid_derivative,
|
|
86
|
+
|
|
87
|
+
"TANH": tanh,
|
|
88
|
+
"TANH_DERIVATIVE": tanh_derivative,
|
|
89
|
+
|
|
90
|
+
"RELU": relu,
|
|
91
|
+
"RELU_DERIVATIVE": relu_derivative,
|
|
92
|
+
|
|
93
|
+
"LEAKY_RELU": leaky_relu,
|
|
94
|
+
"LEAKY_RELU_DERIVATIVE": leaky_relu_derivative,
|
|
95
|
+
|
|
96
|
+
"ELU": elu,
|
|
97
|
+
"ELU_DERIVATIVE": elu_derivative,
|
|
98
|
+
|
|
99
|
+
"SOFTPLUS": softplus,
|
|
100
|
+
"SOFTPLUS_DERIVATIVE": softplus_derivative,
|
|
101
|
+
|
|
102
|
+
"SOFTMAX": softmax,
|
|
103
|
+
"SOFTMAX_DERIVATIVE": softmax_derivative,
|
|
104
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Module exposing the dataclasses needed for the neural network simulator."""
|
|
2
|
+
|
|
3
|
+
from .architecture import Architecture
|
|
4
|
+
from .training_params import TrainingParameters
|
|
5
|
+
from .training_log import TrainingLog
|
|
6
|
+
from .stopping_crit import StoppingCriteria
|
|
7
|
+
from .update_params import UpdateParameters
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Module defining the Architecture dataclass."""
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from .. import activation_functions as af
|
|
4
|
+
|
|
5
|
+
@dataclass
|
|
6
|
+
class Architecture:
|
|
7
|
+
"""
|
|
8
|
+
Store and validate the architecture of a neural network.
|
|
9
|
+
|
|
10
|
+
Parameters
|
|
11
|
+
----------
|
|
12
|
+
input_vector_size : int
|
|
13
|
+
Number of features in the input vectors.
|
|
14
|
+
layers : list of tuple[int, str]
|
|
15
|
+
Network layer specifications. Each tuple contains the
|
|
16
|
+
number of neurons in the layer and the name of its
|
|
17
|
+
activation function.
|
|
18
|
+
|
|
19
|
+
Attributes
|
|
20
|
+
----------
|
|
21
|
+
input_vector_size : int
|
|
22
|
+
Number of features accepted by the input layer.
|
|
23
|
+
layers : list of int
|
|
24
|
+
Number of neurons in each network layer.
|
|
25
|
+
act_funcs : list of str
|
|
26
|
+
Activation function associated with each network layer.
|
|
27
|
+
Function names are stored in uppercase.
|
|
28
|
+
|
|
29
|
+
Raises
|
|
30
|
+
------
|
|
31
|
+
ValueError
|
|
32
|
+
If one or more activation functions are not supported.
|
|
33
|
+
|
|
34
|
+
Notes
|
|
35
|
+
-----
|
|
36
|
+
The input layer is not included in ``layers``. Its size is
|
|
37
|
+
stored separately in ``input_vector_size``.
|
|
38
|
+
|
|
39
|
+
The activation function names are case-insensitive and are
|
|
40
|
+
normalized to uppercase during initialization.
|
|
41
|
+
|
|
42
|
+
Examples
|
|
43
|
+
--------
|
|
44
|
+
>>> architecture = Architecture(
|
|
45
|
+
... input_vector_size=2,
|
|
46
|
+
... layers=[
|
|
47
|
+
... (3, "Linear"),
|
|
48
|
+
... (2, "Sigmoid"),
|
|
49
|
+
... (1, "SoftMax"),
|
|
50
|
+
... ],
|
|
51
|
+
... )
|
|
52
|
+
>>> architecture.layers
|
|
53
|
+
[3, 2, 1]
|
|
54
|
+
>>> architecture.act_funcs
|
|
55
|
+
['LINEAR', 'SIGMOID', 'SOFTMAX']
|
|
56
|
+
"""
|
|
57
|
+
input_vector_size: int
|
|
58
|
+
layers: list[tuple]
|
|
59
|
+
act_funcs: list = field(init=False, default_factory=list)
|
|
60
|
+
|
|
61
|
+
def __post_init__(self):
|
|
62
|
+
self.act_funcs = []
|
|
63
|
+
layer_specs = self.layers
|
|
64
|
+
self.layers = []
|
|
65
|
+
|
|
66
|
+
for layer in layer_specs:
|
|
67
|
+
act_func_name = layer[1].upper()
|
|
68
|
+
if act_func_name not in af.af_list:
|
|
69
|
+
raise ValueError(
|
|
70
|
+
f"Activation function {layer[1]} is not supported. "
|
|
71
|
+
f"Supported functions are: {af.af_list}"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
self.act_funcs.append(act_func_name)
|
|
75
|
+
self.layers.append(layer[0])
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Module defining the StoppingCriteria dataclass."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
|
|
4
|
+
@dataclass
|
|
5
|
+
class StoppingCriteria:
|
|
6
|
+
"""
|
|
7
|
+
Define the stopping criteria for neural network training.
|
|
8
|
+
|
|
9
|
+
Attributes
|
|
10
|
+
----------
|
|
11
|
+
epochs : int or None, default=None
|
|
12
|
+
Maximum number of training epochs. If None, this criterion
|
|
13
|
+
is not considered.
|
|
14
|
+
min_delta_loss : tuple[float, int] or None, default=None
|
|
15
|
+
Minimum required change in training loss and the number
|
|
16
|
+
of consecutive epochs over which the change is evaluated.
|
|
17
|
+
If None, this criterion is not considered.
|
|
18
|
+
min_gradient_norm : tuple[float, int] or None, default=None
|
|
19
|
+
Minimum gradient norm and the number of consecutive epochs
|
|
20
|
+
for which the gradient norm must satisfy the specified
|
|
21
|
+
condition. If None, this criterion is not considered.
|
|
22
|
+
min_delta_valid_loss : tuple[float, int] or None, default=None
|
|
23
|
+
Minimum required change in validation loss and the number
|
|
24
|
+
of consecutive epochs over which the change is evaluated.
|
|
25
|
+
If None, this criterion is not considered.
|
|
26
|
+
target_loss : float or None, default=None
|
|
27
|
+
Target training loss. Training stops when this value is
|
|
28
|
+
reached. If None, this criterion is not considered.
|
|
29
|
+
|
|
30
|
+
Raises
|
|
31
|
+
------
|
|
32
|
+
ValueError
|
|
33
|
+
If no stopping criterion is specified.
|
|
34
|
+
|
|
35
|
+
Notes
|
|
36
|
+
-----
|
|
37
|
+
At least one stopping criterion must be specified when
|
|
38
|
+
creating an instance of this class.
|
|
39
|
+
|
|
40
|
+
The tuple-based criteria specify a threshold and a number
|
|
41
|
+
of consecutive epochs used to evaluate the corresponding
|
|
42
|
+
stopping condition.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
epochs: int | None = None
|
|
46
|
+
min_delta_loss: tuple[float, int] | None = None
|
|
47
|
+
min_gradient_norm: tuple[float, int] | None = None
|
|
48
|
+
min_delta_valid_loss: tuple[float, int] | None = None
|
|
49
|
+
target_loss: float | None = None
|
|
50
|
+
|
|
51
|
+
def __post_init__(self):
|
|
52
|
+
if (
|
|
53
|
+
self.epochs is None
|
|
54
|
+
and self.min_delta_loss is None
|
|
55
|
+
and self.min_gradient_norm is None
|
|
56
|
+
and self.min_delta_valid_loss is None
|
|
57
|
+
and self.target_loss is None
|
|
58
|
+
):
|
|
59
|
+
raise ValueError(
|
|
60
|
+
"At least one stopping criterion must be specified."
|
|
61
|
+
)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Module defining the TrainingLog dataclass."""
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
@dataclass
|
|
6
|
+
class TrainingLog:
|
|
7
|
+
"""
|
|
8
|
+
Store the results and metadata of a neural network training session.
|
|
9
|
+
|
|
10
|
+
Attributes
|
|
11
|
+
----------
|
|
12
|
+
seed : int or None, default=None
|
|
13
|
+
Random seed used to initialize the network weights.
|
|
14
|
+
Can be reused to reproduce the same initialization.
|
|
15
|
+
loss : list[float] or None, default=None
|
|
16
|
+
Loss values recorded during training. Each element
|
|
17
|
+
corresponds to the loss evaluated at a training epoch.
|
|
18
|
+
stopping_cause : list[str] or None, default=None
|
|
19
|
+
Stopping criteria satisfied when training terminates.
|
|
20
|
+
Multiple criteria may be satisfied simultaneously.
|
|
21
|
+
training_start_stop : tuple[datetime, datetime] or None, default=None
|
|
22
|
+
Start and stop timestamps of the training session.
|
|
23
|
+
validation_loss : list[float] or None, default=None
|
|
24
|
+
Validation loss values recorded during training.
|
|
25
|
+
Each element corresponds to the validation loss evaluated
|
|
26
|
+
at a training epoch.
|
|
27
|
+
best_epoch : int or None, default=None
|
|
28
|
+
Epoch associated with the lowest validation loss.
|
|
29
|
+
Used to identify the best model according to its
|
|
30
|
+
generalization performance.
|
|
31
|
+
|
|
32
|
+
Notes
|
|
33
|
+
-----
|
|
34
|
+
The class stores the information required to inspect and
|
|
35
|
+
reproduce a training session.
|
|
36
|
+
|
|
37
|
+
Several useful quantities can be derived from its attributes:
|
|
38
|
+
|
|
39
|
+
- Number of training epochs: ``len(loss)``.
|
|
40
|
+
- Initial training loss: ``loss[0]``.
|
|
41
|
+
- Final training loss: ``loss[-1]``.
|
|
42
|
+
- Initial validation loss: ``validation_loss[0]``.
|
|
43
|
+
- Final validation loss: ``validation_loss[-1]``.
|
|
44
|
+
- Best validation loss: ``min(validation_loss)``.
|
|
45
|
+
- Elapsed training time: difference between the stop and
|
|
46
|
+
start timestamps in ``training_start_stop``.
|
|
47
|
+
|
|
48
|
+
The ``stopping_cause`` attribute can contain multiple entries
|
|
49
|
+
when different stopping criteria are satisfied simultaneously.
|
|
50
|
+
|
|
51
|
+
If a validation set is provided, ``best_epoch`` identifies
|
|
52
|
+
the epoch at which the validation loss reaches its minimum.
|
|
53
|
+
This information can be used for model selection and early
|
|
54
|
+
stopping.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
seed: int | None = None
|
|
58
|
+
loss: list[float] | None = None
|
|
59
|
+
stopping_cause: list[str] | None = None
|
|
60
|
+
training_start_stop: tuple[datetime, datetime] | None = None
|
|
61
|
+
validation_loss: list[float] | None = None
|
|
62
|
+
best_epoch: int | None = None
|
|
63
|
+
|
|
64
|
+
def __repr__(self):
|
|
65
|
+
"""Return a formatted summary of the training session."""
|
|
66
|
+
elapsed_time = None
|
|
67
|
+
training_start = None
|
|
68
|
+
training_stop = None
|
|
69
|
+
elapsed_epoch = len(self.loss) if self.loss is not None else None
|
|
70
|
+
|
|
71
|
+
if self.training_start_stop is not None:
|
|
72
|
+
training_start, training_stop = self.training_start_stop
|
|
73
|
+
elapsed_time = (
|
|
74
|
+
training_stop - training_start
|
|
75
|
+
).total_seconds()
|
|
76
|
+
|
|
77
|
+
stdout = [
|
|
78
|
+
"TrainingLog(",
|
|
79
|
+
f" seed={self.seed},",
|
|
80
|
+
f" elapsed_epoch={elapsed_epoch},",
|
|
81
|
+
f" elapsed_time={elapsed_time:.3f}s,"
|
|
82
|
+
if elapsed_time is not None
|
|
83
|
+
else " elapsed_time=None,",
|
|
84
|
+
f" training_start={training_start},",
|
|
85
|
+
f" training_stop={training_stop},",
|
|
86
|
+
f" stopping_cause={self.stopping_cause},",
|
|
87
|
+
]
|
|
88
|
+
|
|
89
|
+
if self.loss is not None:
|
|
90
|
+
stdout.extend([
|
|
91
|
+
f" initial_loss={self.loss[0]},",
|
|
92
|
+
f" final_loss={self.loss[-1]},",
|
|
93
|
+
])
|
|
94
|
+
|
|
95
|
+
if self.validation_loss is not None:
|
|
96
|
+
stdout.extend([
|
|
97
|
+
f" initial_validation_loss={self.validation_loss[0]},",
|
|
98
|
+
f" final_validation_loss={self.validation_loss[-1]},",
|
|
99
|
+
f" best_epoch={self.best_epoch},",
|
|
100
|
+
])
|
|
101
|
+
|
|
102
|
+
stdout.append(")")
|
|
103
|
+
return "\n".join(stdout)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Module defining the TrainingParameters dataclass."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
|
|
4
|
+
@dataclass
|
|
5
|
+
class TrainingParameters:
|
|
6
|
+
"""
|
|
7
|
+
Store the parameters controlling the neural network training process.
|
|
8
|
+
|
|
9
|
+
Parameters
|
|
10
|
+
----------
|
|
11
|
+
bounds : tuple[float, float], default=(-1, 1)
|
|
12
|
+
Lower and upper bounds of the uniform distribution used
|
|
13
|
+
to initialize the network weights.
|
|
14
|
+
seed : int or None, default=None
|
|
15
|
+
Seed used to initialize the random number generator.
|
|
16
|
+
If None, a seed is generated automatically. The resulting
|
|
17
|
+
seed can be retrieved from the training log and reused
|
|
18
|
+
to reproduce the initialization, provided that the
|
|
19
|
+
architecture and initialization bounds remain unchanged.
|
|
20
|
+
batch_size : int or None, default=None
|
|
21
|
+
Number of training examples processed in each weight update.
|
|
22
|
+
If None, the entire training dataset is processed in a
|
|
23
|
+
single batch. A value of 1 corresponds to online training.
|
|
24
|
+
"""
|
|
25
|
+
bounds: tuple[float, float] = (-1, 1)
|
|
26
|
+
seed: int | None = None
|
|
27
|
+
batch_size: int | None = None
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Module defining the UpdateParameters dataclass."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
|
|
4
|
+
@dataclass
|
|
5
|
+
class UpdateParameters:
|
|
6
|
+
"""
|
|
7
|
+
Store the hyperparameters controlling the network weight updates.
|
|
8
|
+
|
|
9
|
+
Parameters
|
|
10
|
+
----------
|
|
11
|
+
eta : float
|
|
12
|
+
Learning rate controlling the magnitude of gradient-based
|
|
13
|
+
weight updates.
|
|
14
|
+
alpha : float, default=0
|
|
15
|
+
Momentum coefficient controlling the contribution of the
|
|
16
|
+
previous weight update.
|
|
17
|
+
lambda_ : float, default=0
|
|
18
|
+
L2 regularization coefficient controlling the strength
|
|
19
|
+
of the weight decay.
|
|
20
|
+
full_independence : bool, default=False
|
|
21
|
+
If True, applies regularization independently of the
|
|
22
|
+
gradient and momentum contributions. Otherwise, the
|
|
23
|
+
regularization term is included directly in the weight
|
|
24
|
+
update.
|
|
25
|
+
|
|
26
|
+
Notes
|
|
27
|
+
-----
|
|
28
|
+
The weight update depends on the value of
|
|
29
|
+
``full_independence``.
|
|
30
|
+
|
|
31
|
+
If ``full_independence=False``, regularization is included
|
|
32
|
+
directly in the weight update:
|
|
33
|
+
|
|
34
|
+
delta_w(t) = -eta * grad_L(w(t))
|
|
35
|
+
- lambda * w(t)
|
|
36
|
+
+ alpha * delta_w(t-1)
|
|
37
|
+
|
|
38
|
+
w(t+1) = w(t) + delta_w(t)
|
|
39
|
+
|
|
40
|
+
If ``full_independence=True``, regularization is applied
|
|
41
|
+
independently after the gradient and momentum update:
|
|
42
|
+
|
|
43
|
+
delta_w(t) = -eta * grad_L(w(t))
|
|
44
|
+
+ alpha * delta_w(t-1)
|
|
45
|
+
|
|
46
|
+
w(t+1) = w(t) + delta_w(t) - lambda * w(t)
|
|
47
|
+
|
|
48
|
+
where:
|
|
49
|
+
|
|
50
|
+
- ``w(t)`` is the current weight.
|
|
51
|
+
- ``grad_L(w(t))`` is the gradient of the loss function
|
|
52
|
+
with respect to the current weight.
|
|
53
|
+
- ``delta_w(t-1)`` is the previous weight update.
|
|
54
|
+
- ``eta`` is the learning rate.
|
|
55
|
+
- ``alpha`` is the momentum coefficient.
|
|
56
|
+
- ``lambda`` is the regularization coefficient.
|
|
57
|
+
"""
|
|
58
|
+
eta: float
|
|
59
|
+
alpha: float = 0.
|
|
60
|
+
lambda_: float = 0.
|
|
61
|
+
full_independence: bool = False
|
rewheel/engine/loss.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Module containing functions to compute errors and losses."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
def compute_error(
|
|
5
|
+
output_vectors: list[np.ndarray],
|
|
6
|
+
target_vector: np.ndarray
|
|
7
|
+
) -> np.ndarray:
|
|
8
|
+
"""
|
|
9
|
+
Computes the residual error of a neural network prediction.
|
|
10
|
+
|
|
11
|
+
Parameters
|
|
12
|
+
----------
|
|
13
|
+
output_vectors : list of np.ndarray
|
|
14
|
+
Output vector of each layer in the neural network
|
|
15
|
+
(output_vector[-1] represents the final prediction).
|
|
16
|
+
target_vector : np.ndarray
|
|
17
|
+
Target vector for the training example.
|
|
18
|
+
|
|
19
|
+
Returns
|
|
20
|
+
-------
|
|
21
|
+
error : np.ndarray
|
|
22
|
+
Difference between prediction and target.
|
|
23
|
+
"""
|
|
24
|
+
# Automatically select the output layer's output vector from the list
|
|
25
|
+
if isinstance(output_vectors, (list, tuple)):
|
|
26
|
+
prediction = output_vectors[-1]
|
|
27
|
+
else:
|
|
28
|
+
prediction = output_vectors
|
|
29
|
+
|
|
30
|
+
return target_vector - prediction
|
|
31
|
+
|
|
32
|
+
def compute_loss(
|
|
33
|
+
output_vectors: list[np.ndarray],
|
|
34
|
+
target_vector: np.ndarray,
|
|
35
|
+
) -> float:
|
|
36
|
+
"""
|
|
37
|
+
Computes the total empirical loss (HMSE)
|
|
38
|
+
over a batch of examples.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
output_vectors : list of np.ndarray
|
|
43
|
+
Output vector of each layer in the neural network
|
|
44
|
+
(output_vector[-1] represents the final prediction).
|
|
45
|
+
target_vector : np.ndarray
|
|
46
|
+
Target vector for the training example.
|
|
47
|
+
|
|
48
|
+
Returns
|
|
49
|
+
-------
|
|
50
|
+
loss : float
|
|
51
|
+
Total loss computed as the Half Mean Squared Error (HMSE).
|
|
52
|
+
"""
|
|
53
|
+
error_vector = compute_error(
|
|
54
|
+
output_vectors=output_vectors,
|
|
55
|
+
target_vector=target_vector
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
loss = 0.5*(np.mean(np.sum(error_vector**2, axis=0)))
|
|
59
|
+
|
|
60
|
+
return loss
|