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,229 @@
1
+ """
2
+ Module containing functions to manage neural network propagation
3
+ and weight updates during training.
4
+ """
5
+ from typing import TYPE_CHECKING
6
+ import numpy as np
7
+ from ..propagation import (
8
+ forward_propagation,
9
+ backward_propagation,
10
+ update_weights
11
+ )
12
+ from ..loss import compute_error, compute_loss
13
+
14
+ # NeuralNetwork is only imported during type checking and
15
+ # ignored during runtime, preventing circular imports while
16
+ # allowing type hinting
17
+ if TYPE_CHECKING:
18
+ from ..nn_sim import NeuralNetwork
19
+
20
+ def propagate(
21
+ nn: "NeuralNetwork",
22
+ input_vector: np.ndarray,
23
+ target_vector: np.ndarray
24
+ ) -> tuple[list[np.ndarray], float]:
25
+ """
26
+ Performs forward and backward propagation on a set of training samples.
27
+
28
+ Computes the network outputs through forward propagation, evaluates
29
+ the prediction errors, and calculates the weight gradients through
30
+ backward propagation. It also computes the loss over the training
31
+ samples.
32
+
33
+ No weight updates are performed.
34
+
35
+ Parameters
36
+ ----------
37
+ nn : NeuralNetwork
38
+ Neural network used for propagation.
39
+ input_vector : np.ndarray
40
+ Training input samples, arranged in columns.
41
+ target_vector : np.ndarray
42
+ Target values corresponding to the training samples,
43
+ arranged in columns.
44
+
45
+ Returns
46
+ -------
47
+ tuple[list[np.ndarray], float]
48
+ A tuple containing:
49
+ - weights_gradients : list of np.ndarray
50
+ Gradients of the loss with respect to the network weights.
51
+ - loss : float
52
+ Loss computed over the training samples.
53
+ """
54
+ outputs, nets = forward_propagation(
55
+ weights=nn.weights,
56
+ act_funcs=nn.architecture.act_funcs,
57
+ input_vector=input_vector
58
+ )
59
+ error = compute_error(
60
+ output_vectors=outputs,
61
+ target_vector=target_vector
62
+ )
63
+ weights_gradients = backward_propagation(
64
+ weights=nn.weights,
65
+ act_funcs=nn.architecture.act_funcs,
66
+ output_vectors=outputs,
67
+ computed_nets=nets,
68
+ error_vector=error
69
+ )
70
+ loss = compute_loss(
71
+ output_vectors=outputs,
72
+ target_vector=target_vector
73
+ )
74
+
75
+ return weights_gradients, loss
76
+
77
+ def propagate_valid(
78
+ nn: "NeuralNetwork",
79
+ input_vector: np.ndarray,
80
+ target_vector: np.ndarray
81
+ ) -> float:
82
+ """
83
+ Computes the loss over a set of validation samples.
84
+
85
+ Performs forward propagation to obtain the network predictions
86
+ and evaluates the corresponding loss. No gradients are computed
87
+ and the network weights remain unchanged.
88
+
89
+ Parameters
90
+ ----------
91
+ nn : NeuralNetwork
92
+ Neural network used for validation.
93
+ input_vector : np.ndarray
94
+ Validation input samples, arranged in columns.
95
+ target_vector : np.ndarray
96
+ Target values corresponding to the validation samples,
97
+ arranged in columns.
98
+
99
+ Returns
100
+ -------
101
+ float
102
+ Loss computed over the validation samples.
103
+ """
104
+ outputs, _ = forward_propagation(
105
+ weights=nn.weights,
106
+ act_funcs=nn.architecture.act_funcs,
107
+ input_vector=input_vector
108
+ )
109
+ loss = compute_loss(
110
+ output_vectors=outputs,
111
+ target_vector=target_vector
112
+ )
113
+
114
+ return loss
115
+
116
+ def update_mini_batches(
117
+ nn: "NeuralNetwork",
118
+ previous_weights_deltas: list[np.ndarray],
119
+ input_vector: np.ndarray,
120
+ target_vector: np.ndarray,
121
+ seed: int | None = None
122
+ ) -> list[np.ndarray]:
123
+ """
124
+ Updates the network weights using shuffled mini-batches.
125
+
126
+ Shuffles the training samples, divides them into mini-batches
127
+ according to the configured batch size, and performs forward
128
+ propagation, backward propagation, and weight updates for each
129
+ mini-batch.
130
+
131
+ Weight deltas are retained between consecutive mini-batches
132
+ to support momentum-based updates.
133
+
134
+ Parameters
135
+ ----------
136
+ nn : NeuralNetwork
137
+ Neural network whose weights are updated.
138
+ previous_weights_deltas : list of np.ndarray
139
+ Weight deltas from the previous update step, used to compute
140
+ momentum-based updates.
141
+ input_vector : np.ndarray
142
+ Training input samples, arranged in columns.
143
+ target_vector : np.ndarray
144
+ Target values corresponding to the training samples,
145
+ arranged in columns.
146
+ seed : int or None, default=None
147
+ Random seed used to shuffle the training samples.
148
+
149
+ If an integer is provided, the same permutation is generated
150
+ every time the function is called with that seed.
151
+
152
+ If None, a new random seed is generated at each call,
153
+ resulting in a different permutation.
154
+
155
+ Returns
156
+ -------
157
+ list of np.ndarray
158
+ Weight deltas resulting from the final mini-batch update.
159
+ These are used as the previous weight deltas in the next
160
+ training iteration.
161
+
162
+ Notes
163
+ -----
164
+ The batch size is retrieved from the neural network training
165
+ parameters.
166
+
167
+ The final mini-batch may contain fewer samples than the configured
168
+ batch size if the number of training samples is not divisible
169
+ by the batch size.
170
+
171
+ Providing a fixed seed ensures reproducible shuffling across
172
+ function calls, while using None generates independent shuffling
173
+ sequences across calls.
174
+ """
175
+ batch_size = nn.training_params.batch_size
176
+
177
+ # If no seed is provided generate a different seed for each
178
+ # mini-batch training cycle
179
+ if seed is None:
180
+ seed = np.random.SeedSequence().generate_state(
181
+ 1, dtype=np.uint32
182
+ )[0].item()
183
+
184
+ # Shuffle training samples
185
+ indices = np.random.default_rng(seed).permutation(input_vector.shape[1])
186
+ input_vector = input_vector[:, indices]
187
+ target_vector = target_vector[:, indices]
188
+
189
+ # Split input and target samples into mini-batches
190
+ mini_batch_input = np.array_split(
191
+ input_vector,
192
+ np.arange(batch_size, input_vector.shape[1], batch_size),
193
+ axis=1
194
+ )
195
+ mini_batch_target = np.array_split(
196
+ target_vector,
197
+ np.arange(batch_size, target_vector.shape[1], batch_size),
198
+ axis=1
199
+ )
200
+
201
+ # Perform updates for each mini-batch
202
+ for batch_input, batch_target in zip(
203
+ mini_batch_input,
204
+ mini_batch_target
205
+ ):
206
+ output, net = forward_propagation(
207
+ weights=nn.weights,
208
+ act_funcs=nn.architecture.act_funcs,
209
+ input_vector=batch_input
210
+ )
211
+ error = compute_error(
212
+ output_vectors=output,
213
+ target_vector=batch_target
214
+ )
215
+ weights_grad = backward_propagation(
216
+ weights=nn.weights,
217
+ act_funcs=nn.architecture.act_funcs,
218
+ output_vectors=output,
219
+ computed_nets=net,
220
+ error_vector=error
221
+ )
222
+ previous_weights_deltas = update_weights(
223
+ weights=nn.weights,
224
+ weights_gradients=weights_grad,
225
+ previous_weights_deltas=previous_weights_deltas,
226
+ update_params=nn.update_params
227
+ )
228
+
229
+ return previous_weights_deltas
@@ -0,0 +1,220 @@
1
+
2
+ """Module for managing neural network training stopping criteria."""
3
+ from typing import TYPE_CHECKING
4
+ import numpy as np
5
+ from ..classes import TrainingLog
6
+ from ..utils import compute_gradient_norm
7
+ from .steps import propagate_valid
8
+
9
+ # NeuralNetwork is only imported during type checking and
10
+ # ignored during runtime, preventing circular imports while
11
+ # allowing type hinting
12
+ if TYPE_CHECKING:
13
+ from ..nn_sim import NeuralNetwork
14
+
15
+ class StoppingManager:
16
+ """
17
+ Manages stopping criteria and early stopping during neural network training.
18
+
19
+ The manager evaluates the configured stopping criteria at the end of
20
+ each epoch, records the corresponding stopping causes, and handles
21
+ weight restoration when early stopping is triggered.
22
+
23
+ Parameters
24
+ ----------
25
+ nn : NeuralNetwork
26
+ Neural network being trained. Provides access to its weights and
27
+ configured stopping criteria.
28
+ training_log : TrainingLog
29
+ Training log used to record losses, validation losses, and
30
+ stopping information.
31
+
32
+ Attributes
33
+ ----------
34
+ nn : NeuralNetwork
35
+ Neural network being trained.
36
+ training_log : TrainingLog
37
+ Training log associated with the training process.
38
+ gradient_norms : list[float]
39
+ Gradient norms computed at the end of each epoch.
40
+ best_weights : list[np.ndarray] or None
41
+ Copy of the network weights corresponding to the best validation
42
+ loss observed so far. None until the first validation improvement.
43
+ best_epoch : int or None
44
+ Epoch at which the best validation loss was achieved.
45
+ best_validation_loss : float
46
+ Lowest validation loss observed so far.
47
+ epochs_no_improv : int
48
+ Number of consecutive epochs without a sufficient improvement
49
+ in validation loss.
50
+ """
51
+ def __init__(
52
+ self,
53
+ nn: "NeuralNetwork",
54
+ training_log: TrainingLog
55
+ ):
56
+ self.nn = nn
57
+ self.training_log = training_log
58
+
59
+ # Initialize stopping criteria states attributes
60
+ self.gradient_norms = []
61
+ self.best_weights: list[np.ndarray] | None = None
62
+ self.best_epoch: int | None = None
63
+ self.best_validation_loss: float = np.inf
64
+ self.epochs_no_improv: int = 0
65
+
66
+ def update_early_stopping(
67
+ self
68
+ ) -> None:
69
+ """
70
+ Updates the early stopping state using the latest validation loss.
71
+
72
+ A new best model is recorded if the validation loss improves by
73
+ more than the configured minimum improvement threshold. Otherwise,
74
+ the number of consecutive epochs without sufficient improvement
75
+ is incremented.
76
+
77
+ When an improvement occurs, the current network weights are copied
78
+ and the corresponding epoch is stored in the training log.
79
+ """
80
+ min_delta, _ = self.nn.stopping_crit.min_delta_valid_loss
81
+
82
+ if self.training_log.validation_loss[-1] < self.best_validation_loss - min_delta:
83
+ self.best_validation_loss = self.training_log.validation_loss[-1]
84
+ self.epochs_no_improv = 0
85
+
86
+ self.best_weights = [
87
+ w.copy() for w in self.nn.weights
88
+ ]
89
+ self.best_epoch = len(self.training_log.validation_loss)
90
+ self.training_log.best_epoch = self.best_epoch
91
+ else:
92
+ self.epochs_no_improv += 1
93
+
94
+ def check_criteria(
95
+ self
96
+ ) -> list[str]:
97
+ """
98
+ Evaluates all configured training stopping criteria.
99
+
100
+ The following criteria are checked:
101
+ - Maximum number of epochs.
102
+ - Target training loss.
103
+ - Minimum variation in training loss.
104
+ - Minimum gradient norm.
105
+ - Early stopping based on validation loss.
106
+
107
+ If early stopping is triggered, the network weights are restored
108
+ to those corresponding to the best validation loss.
109
+
110
+ Returns
111
+ -------
112
+ list[str]
113
+ List of stopping causes triggered during the current epoch.
114
+ An empty list indicates that no stopping criterion was met.
115
+ """
116
+ causes = []
117
+
118
+ # Maximum number of epochs
119
+ if (
120
+ self.nn.stopping_crit.epochs is not None
121
+ and len(self.training_log.loss) >= self.nn.stopping_crit.epochs
122
+ ):
123
+ causes.append("Maximum_epochs_reached")
124
+
125
+ # Target loss
126
+ if (
127
+ self.nn.stopping_crit.target_loss is not None
128
+ and self.training_log.loss[-1] <= self.nn.stopping_crit.target_loss
129
+ ):
130
+ causes.append("Target_loss_reached")
131
+
132
+ # Minimum loss variation
133
+ if self.nn.stopping_crit.min_delta_loss is not None:
134
+ threshold, patience = self.nn.stopping_crit.min_delta_loss
135
+
136
+ if len(self.training_log.loss) >= patience + 1:
137
+ delta_loss = np.abs(np.diff(self.training_log.loss[-(patience + 1):]))
138
+
139
+ if np.all(delta_loss <= threshold):
140
+ causes.append("Minimum_loss_variation_reached")
141
+
142
+ # Minimum gradient norm
143
+ if self.nn.stopping_crit.min_gradient_norm is not None:
144
+ threshold, patience = self.nn.stopping_crit.min_gradient_norm
145
+
146
+ if len(self.gradient_norms) >= patience:
147
+ if np.all(np.array(self.gradient_norms[-patience:]) <= threshold):
148
+ causes.append("Minimum_gradient_norm_reached")
149
+
150
+ # Validation based early stopping
151
+ if self.nn.stopping_crit.min_delta_valid_loss is not None:
152
+ _, patience = self.nn.stopping_crit.min_delta_valid_loss
153
+
154
+ if self.epochs_no_improv >= patience:
155
+ causes.append("Minimum_validation_loss_variation_reached (ES)")
156
+
157
+ self.training_log.best_epoch = self.best_epoch
158
+ self._restore_weights()
159
+
160
+ return causes
161
+
162
+ def _restore_weights(
163
+ self
164
+ ) -> None:
165
+ """
166
+ Restores the network weights to the best validation checkpoint.
167
+ """
168
+ if self.best_weights is not None:
169
+ self.nn.weights[:] = [
170
+ w.copy() for w in self.best_weights
171
+ ]
172
+
173
+ def check_stopping(
174
+ self,
175
+ valid_input_vector: np.ndarray,
176
+ valid_target_vector: np.ndarray,
177
+ loss: float,
178
+ weights_gradients: list[np.ndarray]
179
+ ) -> None:
180
+ """
181
+ Updates training metrics and checks whether training should stop.
182
+
183
+ At the end of each epoch, this method:
184
+ 1. Records the training loss.
185
+ 2. Computes and records the validation loss, if early stopping
186
+ based on validation loss is enabled.
187
+ 3. Updates the early stopping state.
188
+ 4. Computes and records the gradient norm, if the corresponding
189
+ stopping criterion is enabled.
190
+ 5. Evaluates all stopping criteria and updates the training log
191
+ with the resulting stopping causes.
192
+
193
+ Parameters
194
+ ----------
195
+ valid_input_vector : np.ndarray
196
+ Input data used to evaluate the validation loss.
197
+ valid_target_vector : np.ndarray
198
+ Target values corresponding to the validation input data.
199
+ loss : float
200
+ Training loss computed during the current epoch.
201
+ weights_gradients : list[np.ndarray]
202
+ Weight gradient matrices computed during the current epoch.
203
+ """
204
+ self.training_log.loss.append(loss)
205
+
206
+ if self.nn.stopping_crit.min_delta_valid_loss is not None:
207
+ valid_loss = propagate_valid(
208
+ nn=self.nn,
209
+ input_vector=valid_input_vector,
210
+ target_vector=valid_target_vector
211
+ )
212
+ self.training_log.validation_loss.append(valid_loss)
213
+ self.update_early_stopping()
214
+
215
+ if self.nn.stopping_crit.min_gradient_norm is not None:
216
+ self.gradient_norms.append(compute_gradient_norm(weights_gradients))
217
+
218
+ causes = self.check_criteria()
219
+
220
+ self.training_log.stopping_cause = causes
@@ -0,0 +1,233 @@
1
+ """Module containing the class responsible for training the neural network."""
2
+ from typing import TYPE_CHECKING
3
+ from datetime import datetime
4
+ import sys
5
+ import numpy as np
6
+ from ..classes import TrainingLog
7
+ from ..utils import initialize_weights
8
+ from .steps import propagate, update_weights, update_mini_batches
9
+ from .stopping import StoppingManager
10
+
11
+ # NeuralNetwork is only imported during type checking and
12
+ # ignored during runtime, preventing circular imports while
13
+ # allowing type hinting
14
+ if TYPE_CHECKING:
15
+ from ..nn_sim import NeuralNetwork
16
+
17
+ class Trainer:
18
+ """
19
+ Coordinates the training process of a neural network.
20
+
21
+ The Trainer initializes the network weights, manages the training
22
+ loop, performs weight updates, and monitors the configured stopping
23
+ criteria.
24
+
25
+ Parameters
26
+ ----------
27
+ neural_network : NeuralNetwork
28
+ Neural network to be trained. The Trainer operates directly on
29
+ its weights, architecture, training parameters, and stopping
30
+ criteria.
31
+
32
+ Attributes
33
+ ----------
34
+ nn : NeuralNetwork
35
+ Neural network being trained.
36
+ training_log : TrainingLog
37
+ Log containing training metrics, validation metrics (if enabled),
38
+ initialization information, and stopping information.
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ neural_network: "NeuralNetwork"
44
+ ):
45
+ """
46
+ Initializes the Trainer and prepares the neural network for training.
47
+
48
+ Initializes the network weights according to its architecture
49
+ and training parameters, then creates a TrainingLog instance
50
+ to record the training process.
51
+
52
+ Parameters
53
+ ----------
54
+ neural_network : NeuralNetwork
55
+ Neural network to be trained.
56
+ """
57
+ self.nn = neural_network
58
+
59
+ # Initialize weights matrices
60
+ seed = initialize_weights(
61
+ architecture=self.nn.architecture,
62
+ weights=self.nn.weights,
63
+ bounds=self.nn.training_params.bounds,
64
+ seed=self.nn.training_params.seed
65
+ )
66
+
67
+ # Initialize TrainingLog instance
68
+ self.training_log = TrainingLog(
69
+ seed=seed,
70
+ loss=[],
71
+ stopping_cause=[],
72
+ validation_loss=(
73
+ []
74
+ if (self.nn.stopping_crit.min_delta_valid_loss is not None)
75
+ else None
76
+ )
77
+ )
78
+
79
+ def _progress(
80
+ self
81
+ ) -> None:
82
+ """
83
+ Displays the current training progress in the console.
84
+
85
+ Updates a single console line with the current epoch,
86
+ training loss, and validation loss (if available).
87
+ """
88
+ message = (
89
+ f"Epoch {len(self.training_log.loss)}"
90
+ f", loss: {self.training_log.loss[-1]:.5g}"
91
+ + (
92
+ f", validation loss: "
93
+ f"{self.training_log.validation_loss[-1]:.5g}"
94
+ if self.training_log.validation_loss is not None
95
+ else ""
96
+ )
97
+ )
98
+ sys.stdout.write("\r" + message + "\033[K")
99
+ sys.stdout.flush()
100
+
101
+ def training_loop(
102
+ self,
103
+ input_vector: np.ndarray,
104
+ target_vector: np.ndarray,
105
+ valid_input_vector: np.ndarray | None = None,
106
+ valid_target_vector: np.ndarray | None = None
107
+ ) -> TrainingLog:
108
+ """
109
+ Executes the neural network training loop.
110
+
111
+ At each training iteration, the method:
112
+ 1. Computes weight gradients and training loss through propagation.
113
+ 2. Evaluates the configured stopping criteria using a
114
+ StoppingManager.
115
+ 3. Stops training if one or more stopping criteria are met.
116
+ 4. Updates the network weights using full-batch or mini-batch
117
+ gradient descent.
118
+
119
+ For mini-batch training, the training samples are shuffled and
120
+ divided into batches before the weight updates are performed.
121
+
122
+ Momentum-related updates are handled by retaining the weight
123
+ deltas from the previous update step.
124
+
125
+ The training start and end timestamps are recorded in the
126
+ associated TrainingLog.
127
+
128
+ Parameters
129
+ ----------
130
+ input_vector : np.ndarray
131
+ Training input samples, arranged in columns.
132
+ target_vector : np.ndarray
133
+ Target values corresponding to the training samples,
134
+ arranged in columns.
135
+ valid_input_vector : np.ndarray or None, optional
136
+ Validation input samples, arranged in columns. Used to
137
+ evaluate validation loss when validation-based stopping
138
+ criteria are enabled. Defaults to None.
139
+ valid_target_vector : np.ndarray or None, optional
140
+ Target values corresponding to the validation samples,
141
+ arranged in columns. Defaults to None.
142
+
143
+ Returns
144
+ -------
145
+ TrainingLog
146
+ Training log containing the recorded training losses,
147
+ validation losses (if enabled), stopping causes, random
148
+ seed, and training timestamps.
149
+
150
+ Notes
151
+ -----
152
+ Training progress is displayed in real time in the console,
153
+ including training and validation losses when available.
154
+
155
+ The training log is printed automatically after training
156
+ is completed.
157
+
158
+ The training loop terminates when at least one configured
159
+ stopping criterion is met.
160
+ """
161
+ # Initialize previous weights deltas to zero
162
+ previous_weights_deltas = [
163
+ np.zeros_like(w) for w in self.nn.weights
164
+ ]
165
+
166
+ # Initialize an instance of StoppingManager
167
+ st = StoppingManager(
168
+ nn=self.nn,
169
+ training_log=self.training_log
170
+ )
171
+
172
+ # Store training starting time in training_log
173
+ self.training_log.training_start_stop = [datetime.now()]
174
+
175
+ # Loop until a stopping condition is met
176
+ while True:
177
+ # Propagate through the network
178
+ weights_gradients, loss = propagate(
179
+ nn=self.nn,
180
+ input_vector=input_vector,
181
+ target_vector=target_vector
182
+ )
183
+
184
+ # Evaluate the configured stopping criteria
185
+ st.check_stopping(
186
+ valid_input_vector=valid_input_vector,
187
+ valid_target_vector=valid_target_vector,
188
+ loss=loss,
189
+ weights_gradients=weights_gradients
190
+ )
191
+
192
+ self._progress()
193
+
194
+ # Stop training if a stopping condition is met
195
+ if self.training_log.stopping_cause:
196
+ print()
197
+ break
198
+
199
+ # Update the network weights
200
+ # Full-batch training
201
+ if self.nn.training_params.batch_size is None:
202
+ previous_weights_deltas = update_weights(
203
+ weights=self.nn.weights,
204
+ weights_gradients=weights_gradients,
205
+ previous_weights_deltas=previous_weights_deltas,
206
+ update_params=self.nn.update_params
207
+ )
208
+
209
+ # Mini-batch training
210
+ else:
211
+ previous_weights_deltas = update_mini_batches(
212
+ nn=self.nn,
213
+ previous_weights_deltas=previous_weights_deltas,
214
+ input_vector=input_vector,
215
+ target_vector=target_vector,
216
+ seed=self.nn.training_params.seed
217
+ )
218
+
219
+ # Store training stopping time in training_log
220
+ self.training_log.training_start_stop.append(datetime.now())
221
+
222
+ self.log()
223
+
224
+ return self.training_log
225
+
226
+ def log(
227
+ self
228
+ ) -> None:
229
+ """
230
+ Prints the training log to the console.
231
+ """
232
+ if self.training_log is not None:
233
+ print(self.training_log)