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.
@@ -0,0 +1,271 @@
1
+ """nn_simulator main module. Contains the NeuralNetwork class."""
2
+ import numpy as np
3
+ from .classes import (
4
+ TrainingParameters,
5
+ UpdateParameters,
6
+ Architecture,
7
+ TrainingLog,
8
+ StoppingCriteria
9
+ )
10
+ from .propagation import forward_propagation
11
+ from .utils import check_input, initialize_weights
12
+ from .training.trainer import Trainer
13
+
14
+ class NeuralNetwork:
15
+ """
16
+ Implement a feedforward neural network.
17
+
18
+ This class provides the main interface for creating, training and
19
+ using a neural network. It manages the network architecture, weight
20
+ matrices, training and update parameters, and training history.
21
+
22
+ The network supports saving and loading models, making predictions
23
+ and training using the configured optimization parameters.
24
+
25
+ Parameters
26
+ ----------
27
+ architecture : Architecture
28
+ Architecture defining the number of neurons and activation
29
+ functions in each layer.
30
+ training_parameters : TrainingParameters, default=None
31
+ Parameters controlling the training process and its stopping
32
+ criteria. If None, training parameters must be provided when
33
+ calling the train method.
34
+ update_parameters : UpdateParameters, default=None
35
+ Parameters controlling weight updates, including learning rate,
36
+ momentum and regularization. If None, update parameters must be
37
+ provided when calling the train method.
38
+ stopping_criteria : StoppingCriteria or None, default=None
39
+ Criteria determining when the training process terminates.
40
+ If None, they must be provided before calling the train method.
41
+
42
+ Attributes
43
+ ----------
44
+ architecture : Architecture
45
+ Architecture of the neural network.
46
+ weights : list of numpy.ndarray or None
47
+ List of weight matrices connecting consecutive layers.
48
+ Initialized during the first training process or when loading
49
+ a model.
50
+ update_params : UpdateParameters or None
51
+ Parameters controlling weight updates.
52
+ training_params : TrainingParameters or None
53
+ Parameters controlling the training process.
54
+ stopping_crit : StoppingCriteria or None
55
+ Criteria determining when the training process terminates.
56
+ training_log : TrainingLog or None
57
+ Log containing the results and history of the latest training
58
+ process.
59
+
60
+ Notes
61
+ -----
62
+ The input and target datasets are expected to have examples
63
+ arranged in columns.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ architecture: Architecture,
69
+ training_parameters: TrainingParameters | None = None,
70
+ update_parameters: UpdateParameters | None = None,
71
+ stopping_criteria: StoppingCriteria | None = None
72
+ ):
73
+ # Initialize nn architecture attribute
74
+ self.architecture = architecture
75
+ # Initialize layer weights matrices list
76
+ self.weights: list[np.ndarray | None] = [
77
+ None
78
+ ] * len(self.architecture.layers)
79
+ # Initialize nn training/update parameters attributes
80
+ self.update_params = update_parameters
81
+ self.training_params = training_parameters
82
+ self.stopping_crit = stopping_criteria
83
+ # Initialize training log attribute to None
84
+ self.training_log: TrainingLog = None
85
+
86
+ def __repr__(self) -> str:
87
+ weights_initialized = all(
88
+ w is not None for w in self.weights
89
+ )
90
+ weights_status = (
91
+ "initialized"
92
+ if weights_initialized
93
+ else "uninitialized"
94
+ )
95
+
96
+ nn_weights = [None] * len(self.architecture.layers)
97
+ initialize_weights(self.architecture, nn_weights)
98
+ total_params = sum(w.size for w in nn_weights)
99
+ lines = [
100
+ "NeuralNetwork(",
101
+ f" Architecture = {self.architecture},",
102
+ f" Weights status = {weights_status},",
103
+ f" Total trainable parameters = {total_params},"
104
+ ]
105
+ if self.training_params is not None:
106
+ lines.append(
107
+ f" training_params = {self.training_params},"
108
+ )
109
+ if self.update_params is not None:
110
+ lines.append(
111
+ f" update_params = {self.update_params},"
112
+ )
113
+ if self.stopping_crit is not None:
114
+ lines.append(
115
+ f" stopping_crit = {self.stopping_crit},"
116
+ )
117
+ if self.training_log is not None:
118
+ lines.append(
119
+ f" training_log = {self.training_log},"
120
+ )
121
+ lines.append(")")
122
+
123
+ return "\n".join(lines)
124
+
125
+ def configure(
126
+ self,
127
+ update_params: UpdateParameters | None = None,
128
+ training_params: TrainingParameters | None = None,
129
+ stopping_crit: StoppingCriteria | None = None
130
+ ) -> None:
131
+ """
132
+ Configure the training and update parameters of the network.
133
+
134
+ Only the parameters explicitly provided are updated. Parameters
135
+ passed as None leave the corresponding attributes unchanged.
136
+
137
+ Parameters
138
+ ----------
139
+ update_params : UpdateParameters or None, default=None
140
+ Parameters controlling weight updates, including learning
141
+ rate, momentum and regularization.
142
+ training_params : TrainingParameters or None, default=None
143
+ Parameters controlling the training process, including
144
+ batch size and weight initialization settings.
145
+ stopping_crit : StoppingCriteria or None, default=None
146
+ Criteria determining when the training process terminates.
147
+ """
148
+ if update_params is not None:
149
+ self.update_params = update_params
150
+ if training_params is not None:
151
+ self.training_params = training_params
152
+ if stopping_crit is not None:
153
+ self.stopping_crit = stopping_crit
154
+
155
+ @check_input
156
+ def predict(
157
+ self,
158
+ input_vector: np.ndarray
159
+ ) -> np.ndarray:
160
+ """
161
+ Compute the neural network predictions.
162
+
163
+ Performs forward propagation on the provided input examples
164
+ and returns the output of the final network layer.
165
+
166
+ Parameters
167
+ ----------
168
+ input_vector : np.ndarray
169
+ Input vector to be forwarded into the neural network.
170
+
171
+ Returns
172
+ -------
173
+ numpy.ndarray
174
+ Predictions produced by the output layer. Each column
175
+ corresponds to an input example.
176
+ """
177
+ # Checks if the model has been trained or loaded from
178
+ # memory before attempting a prediction
179
+ if all(w is None for w in self.weights):
180
+ raise RuntimeError(
181
+ "Cannot perform prediction: the model has not been trained or " \
182
+ "loaded from memory."
183
+ )
184
+
185
+ # Performs forward propagation in the neural network
186
+ output_vector = forward_propagation(
187
+ weights=self.weights,
188
+ act_funcs=self.architecture.act_funcs,
189
+ input_vector=input_vector
190
+ )[0][-1]
191
+
192
+ # Returns only the output layer output vector
193
+ # a.k.a. final prediction
194
+ return output_vector
195
+
196
+ @check_input
197
+ def train(
198
+ self,
199
+ input_vector: np.ndarray,
200
+ target_vector: np.ndarray,
201
+ valid_input_vector: np.ndarray | None = None,
202
+ valid_target_vector: np.ndarray | None = None
203
+ ) -> None:
204
+ """
205
+ Train the neural network using the provided dataset.
206
+
207
+ Initializes the network weights if necessary and performs
208
+ training according to the configured training, update and
209
+ stopping parameters.
210
+
211
+ The training history is stored in the ``training_log``
212
+ attribute after the training process is completed.
213
+
214
+ Parameters
215
+ ----------
216
+ input_vector : np.ndarray
217
+ Training input data, with features arranged in rows and
218
+ examples arranged in columns.
219
+ target_vector : np.ndarray
220
+ Training target values, with output features arranged
221
+ in rows and examples arranged in columns.
222
+ valid_input_vector : np.ndarray or None, default=None
223
+ Validation input data, with features arranged in rows
224
+ and examples arranged in columns. Required when
225
+ validation-loss-based early stopping is enabled.
226
+ valid_target_vector : np.ndarray or None, default=None
227
+ Validation target values, with output features arranged
228
+ in rows and examples arranged in columns. Required when
229
+ validation-loss-based early stopping is enabled.
230
+
231
+ Raises
232
+ ------
233
+ ValueError
234
+ If validation input data is provided without validation
235
+ target data, or vice versa.
236
+ If validation-loss-based early stopping is enabled but
237
+ either validation dataset is missing.
238
+
239
+ Notes
240
+ -----
241
+ The network weights are initialized by the Trainer if they
242
+ have not already been initialized.
243
+
244
+ The training results are stored in the ``training_log``
245
+ attribute.
246
+ """
247
+ # Check if both validation vectors are passed to the function
248
+ if self.stopping_crit.min_delta_valid_loss is not None:
249
+ if valid_input_vector is None or valid_target_vector is None:
250
+ raise ValueError(
251
+ "Both validation input vector and target vector must be passed during training."
252
+ )
253
+ # Check validation vectors type
254
+ if valid_input_vector is not None and valid_target_vector is not None:
255
+ if not isinstance(valid_input_vector, np.ndarray):
256
+ valid_input_vector = np.array(valid_input_vector)
257
+ if not isinstance(valid_target_vector, np.ndarray):
258
+ valid_target_vector = np.array(valid_target_vector)
259
+
260
+ # Initialize Trainer instance
261
+ tr = Trainer(
262
+ neural_network=self
263
+ )
264
+
265
+ # Start training loop
266
+ self.training_log = tr.training_loop(
267
+ input_vector=input_vector,
268
+ target_vector=target_vector,
269
+ valid_input_vector=valid_input_vector,
270
+ valid_target_vector=valid_target_vector
271
+ )
@@ -0,0 +1,222 @@
1
+ """
2
+ Module containing the functions to perform forward/backward propagation
3
+ and weights update in a neural network.
4
+ """
5
+ import numpy as np
6
+ from . import activation_functions as af
7
+ from .utils import add_bias, compute_delta, compute_gradient
8
+ from .classes import UpdateParameters
9
+
10
+ def forward_propagation(
11
+ weights: list[np.ndarray],
12
+ act_funcs: list[str],
13
+ input_vector: np.ndarray
14
+ ) -> tuple[list[np.ndarray], list[np.ndarray]]:
15
+ """
16
+ Performs the forwarding in a neural network.
17
+
18
+ Parameters
19
+ ----------
20
+ weights : list of np.ndarray
21
+ List of weights matrices of the neural network.
22
+ act_funcs : list of str
23
+ List of activation functions of each layer
24
+ represented by a string.
25
+ input_vector : np.ndarray
26
+ Input vector to be forwarded into the neural network.
27
+
28
+ Returns
29
+ -------
30
+ output_vectors : list of np.ndarray
31
+ Output vector of each layer, including the bias term for all
32
+ hidden layers. The final element, output_vectors[-1], is the
33
+ network's prediction and does not include a bias term.
34
+ computed_nets : list of np.ndarray
35
+ Net input of each layer before applying the activation function.
36
+ """
37
+
38
+ # Initialize ouput_vector and computed_nets lists
39
+ num_layers = len(weights)
40
+ output_vectors = [None] * (num_layers + 1)
41
+ computed_nets = [None] * num_layers
42
+
43
+ # Apply bias to the input vector
44
+ # output_vector[0] represents the output of the input layer
45
+ # that will be fed into the first hidden layer
46
+ is_single_example = input_vector.ndim == 1
47
+ output_vectors[0] = add_bias(input_vector, is_single_example)
48
+
49
+ # Start propagating through layers
50
+ for i, layer_weights in enumerate(weights):
51
+ # Compute net of the whole layer
52
+ net = layer_weights @ output_vectors[i]
53
+ # Store the net of the layer
54
+ computed_nets[i] = net
55
+
56
+ # Apply activation function
57
+ layer_output = af.af_list[act_funcs[i]](net)
58
+
59
+ # Compute the output to be passed as input onto the next layer
60
+ if i < num_layers-1:
61
+ # The next layer input will be the biased version of the current layer output
62
+ output_vectors[i+1] = add_bias(layer_output, is_single_example)
63
+ else:
64
+ # When we arrive at the output layer we save the output without adding a bias
65
+ # This represents the neural network final prediction
66
+ output_vectors[i+1] = layer_output
67
+
68
+ return output_vectors, computed_nets
69
+
70
+ def backward_propagation(
71
+ weights: list[np.ndarray],
72
+ act_funcs: list[str],
73
+ output_vectors: list[np.ndarray],
74
+ computed_nets: list[np.ndarray],
75
+ error_vector: np.ndarray
76
+ ) -> list[np.ndarray]:
77
+ """
78
+ Performs the back-propagation in a neural network.
79
+ Goes backward trough the layers comptuing their delta
80
+ vectors and weights gradient matrices.
81
+
82
+ Parameters
83
+ ----------
84
+ weights : list of np.ndarray
85
+ List of weights matrices of the neural network.
86
+ act_funcs : list of str
87
+ List of activation functions of each layer
88
+ represented by a string.
89
+ output_vectors : list of np.ndarray
90
+ Output vector of each layer, including the bias term for all
91
+ hidden layers. The final element, output_vectors[-1], is the
92
+ network's prediction and does not include a bias term.
93
+ computed_nets : list of np.ndarray
94
+ Net input of each layer before applying the activation function.
95
+ error_vector : np.ndarray
96
+ Difference between prediction and target.
97
+
98
+ Returns
99
+ -------
100
+ weights_gradients : list of np.ndarray
101
+ List containing the negative weights gradient matrix of each layer.
102
+ """
103
+
104
+ num_layers = len(weights)
105
+ is_single_example = output_vectors[-1].ndim == 1
106
+
107
+ # Initialize the weight gradients list
108
+ weights_gradients = [None] * num_layers
109
+
110
+ # Compute the output layer delta
111
+ prev_delta = compute_delta(
112
+ propagated_error=error_vector,
113
+ act_func=act_funcs[-1],
114
+ computed_net=computed_nets[-1]
115
+ )
116
+
117
+ # Compute the output layer gradient
118
+ weights_gradients[-1] = compute_gradient(
119
+ delta=prev_delta,
120
+ prev_layer_output=output_vectors[-2],
121
+ is_single_example=is_single_example
122
+ )
123
+
124
+ # Backpropagate through the hidden layers
125
+ # We start looping from -2 since we already computed delta
126
+ # and gradient for the output layer outside the loop
127
+ for i in range(num_layers - 2, -1, -1):
128
+ # Propagate the delta vector from the previous layer to the current
129
+ propagated_error = (
130
+ weights[i + 1][:, :-1].T @ prev_delta
131
+ )
132
+
133
+ # Compute delta vector for the current layer
134
+ delta = compute_delta(
135
+ propagated_error=propagated_error,
136
+ act_func=act_funcs[i],
137
+ computed_net=computed_nets[i]
138
+ )
139
+
140
+ # Compute weights gradient for the current layer
141
+ weights_gradients[i] = compute_gradient(
142
+ delta=delta,
143
+ prev_layer_output=output_vectors[i],
144
+ is_single_example=is_single_example
145
+ )
146
+
147
+ # Go to the previous layer
148
+ prev_delta = delta
149
+
150
+ return weights_gradients
151
+
152
+ def update_weights(
153
+ weights: list[np.ndarray],
154
+ weights_gradients: list[np.ndarray],
155
+ previous_weights_deltas: list[np.ndarray],
156
+ update_params: UpdateParameters
157
+ ) -> list[np.ndarray]:
158
+ """
159
+ Updates weights using gradient descent with L2 regularization
160
+ and momentum.
161
+
162
+ Implements two different weights update algorithms:
163
+ one obtains full independence between the three terms while the
164
+ other absorbs the regularization term inside the weights delta.
165
+
166
+ Parameters
167
+ ----------
168
+ weights : list of np.ndarray
169
+ List of weights matrices of the neural network.
170
+ weights_gradients : list of np.ndarray
171
+ List containing the negative weights gradient matrix of each layer.
172
+ previous_weights_deltas : listo of np.ndarray
173
+ List containing the weights deltas of the previous weights update
174
+ iteration. Needed to apply momentum to the weight update.
175
+ update_params : UpdateParameters
176
+ Contains the parameters needed to perform the weights update.
177
+
178
+ Returns
179
+ -------
180
+ weights_deltas : list of np.ndarray
181
+ List containing the delta applied to the weights.
182
+ To be used in future iteration of the training cycle
183
+ as previous_weights_delta.
184
+
185
+ Notes
186
+ -----
187
+ The weights update will be performed following:
188
+ delta_w = - eta * w_grad - lambda * w + alpha * delta_w_old
189
+ w_new = w + delta_w
190
+ if full_independence=False, or:
191
+ delta_w = - eta * w_grad + alpha * delta_w_old
192
+ w_new = w + delta_w - lambda * w
193
+ if full_independence=True.
194
+ """
195
+
196
+ # Initialize weights delta list
197
+ weights_deltas = []
198
+
199
+ for weight, previous_delta, gradient in zip(
200
+ weights,
201
+ previous_weights_deltas,
202
+ weights_gradients,
203
+ strict=True
204
+ ):
205
+
206
+ # Computes partial weights delta
207
+ weights_delta = (
208
+ update_params.eta * gradient
209
+ + update_params.alpha * previous_delta
210
+ )
211
+
212
+ if update_params.full_independence:
213
+ # Fully independent weights update
214
+ weight += weights_delta - update_params.lambda_ * weight
215
+ else:
216
+ # Regularization term inside weights delta
217
+ weights_delta -= update_params.lambda_ * weight
218
+ weight += weights_delta
219
+
220
+ weights_deltas.append(weights_delta)
221
+
222
+ return weights_deltas
@@ -0,0 +1,3 @@
1
+ """Module exposing the Trainer class."""
2
+
3
+ from .trainer import Trainer