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,221 @@
1
+ """
2
+ Module containing support utilities for the functions needed
3
+ in the neural network simulator.
4
+ """
5
+ from functools import wraps
6
+ import numpy as np
7
+ from . import activation_functions as af
8
+ from .classes import Architecture
9
+
10
+ def check_input(func: callable) -> callable:
11
+ """
12
+ Decorator that validates and converts the input vector before
13
+ passing it to a neural network method.
14
+
15
+ The input vector is converted to a np.ndarray if necessary.
16
+ Its first dimension is then checked against the number of
17
+ input units specified in the network architecture.
18
+
19
+ Parameters
20
+ ----------
21
+ func : callable
22
+ Instance method of a NeuralNetwork object to be decorated.
23
+ The method must accept the input vector as its first
24
+ argument after self.
25
+
26
+ Returns
27
+ -------
28
+ callable
29
+ Wrapped method that validates the input vector before
30
+ executing the original function.
31
+
32
+ Raises
33
+ ------
34
+ ValueError
35
+ If the number of input features does not match the
36
+ network's input layer size.
37
+ """
38
+ @wraps(func) # Needed to keep the original function metadata
39
+ def wrapper(self, input_vector, *args, **kwargs):
40
+ # Check if the input is a NumPy array,
41
+ # if not attempt a conversion
42
+ if not isinstance(input_vector, np.ndarray):
43
+ input_vector = np.array(input_vector)
44
+
45
+ # Check if input vector number of features matches input layer
46
+ # number of units
47
+ if input_vector.shape[0] != self.architecture.input_vector_size:
48
+ raise ValueError(
49
+ "Input vector size does not match the network's "
50
+ "input layer number of units."
51
+ )
52
+
53
+ # Execute the decorated method
54
+ return func(self, input_vector, *args, **kwargs)
55
+
56
+ return wrapper
57
+
58
+ def add_bias(
59
+ array: np.ndarray,
60
+ is_single_example: bool
61
+ ) -> np.ndarray:
62
+ """
63
+ Inserts the bias component in a np.ndarray.
64
+
65
+ Parameters
66
+ ----------
67
+ array : np.ndarray
68
+ Array to be expanded.
69
+ is_single_example : bool
70
+ True if a single example is being fed into the neural network,
71
+ false otherwise.
72
+
73
+ Returns
74
+ -------
75
+ np.ndarray
76
+ Expanded array.
77
+ """
78
+ return (np.append(array, 1)
79
+ if is_single_example
80
+ else np.concatenate(
81
+ (array, np.ones((1, array.shape[1]))),
82
+ axis=0
83
+ )
84
+ )
85
+
86
+ def compute_delta(
87
+ propagated_error: np.ndarray,
88
+ act_func: str,
89
+ computed_net: np.ndarray
90
+ ) -> np.ndarray:
91
+ """
92
+ Computes the delta vector of a layer, needed to compute the
93
+ weights gradient when back-propagating.
94
+
95
+ Parameters
96
+ ----------
97
+ propagated_error : np.ndarray
98
+ Array containing the propagated delta coming from the previous layer.
99
+ For the output layer is simply the residual error vector.
100
+ act_func : str
101
+ Activation function of the layer, represented by a
102
+ string. Needed to compute it's derivative.
103
+ computed_net : np.ndarray
104
+ Net vector of the layer, previously computed during
105
+ forwarding.
106
+
107
+ Returns
108
+ -------
109
+ np.ndarray
110
+ Computed delta vector of the layer.
111
+ """
112
+ # Here * performs element-wise matrix product
113
+ return propagated_error * (
114
+ af.af_list[str(act_func) + "_DERIVATIVE"](computed_net)
115
+ )
116
+
117
+ def compute_gradient(
118
+ delta: np.ndarray,
119
+ prev_layer_output: np.ndarray,
120
+ is_single_example: bool
121
+ ) -> np.ndarray:
122
+ """
123
+ Computes the weights gradient of a layer when back-propagating.
124
+
125
+ Parameters
126
+ ----------
127
+ delta : np.ndarray
128
+ Delta vector of the layer.
129
+ prev_layer_output : np.ndarray
130
+ Output vector of the previous layer.
131
+ is_single_example : bool
132
+ True if a single example is being fed into the neural network,
133
+ false otherwise.
134
+
135
+ Returns
136
+ -------
137
+ np.ndarray
138
+ Computed weights gradient of the layer.
139
+ """
140
+ return (np.outer(delta, prev_layer_output)
141
+ if is_single_example
142
+ else delta @ prev_layer_output.T / prev_layer_output.shape[1]
143
+ )
144
+
145
+ def initialize_weights(
146
+ architecture: Architecture,
147
+ weights: list[np.ndarray],
148
+ bounds: tuple[float, float] = (-1, 1),
149
+ seed: int = None
150
+ ) -> int:
151
+ """
152
+ Initializes weights matrices with random floats
153
+ following a uniform distribution. A seed can be
154
+ passed as a parameter to reproduce certain
155
+ weights starting values. If a seed is not provided
156
+ it will be generated. The seed that was used will
157
+ be returned.
158
+
159
+ Parameters
160
+ ----------
161
+ architecture : Architecture
162
+ Neural network architecture.
163
+ weights : list of np.ndarray
164
+ List of weights matrices of the neural network.
165
+ bounds : tuple[float, float], default=(-1, 1)
166
+ Lower and upper bounds of the uniform distribution used
167
+ to initialize the network weights.
168
+ seed : int or None, default=None
169
+ Seed used to initialize the random number generator.
170
+ If None, a random seed is generated automatically.
171
+ The generated seed can be saved and reused to reproduce
172
+ the same initial weights, provided that the network
173
+ architecture and bounds remain unchanged.
174
+
175
+ Returns
176
+ -------
177
+ seed : int
178
+ The seed that was used to initialize the weights.
179
+ """
180
+ if seed is None:
181
+ seed = np.random.SeedSequence().generate_state(
182
+ 1, dtype=np.uint32
183
+ )[0].item()
184
+
185
+ rng = np.random.default_rng(seed)
186
+
187
+ for i, layer in enumerate(architecture.layers):
188
+ if i == 0:
189
+ weights[i] = rng.uniform(
190
+ low=bounds[0],
191
+ high=bounds[1],
192
+ size=(layer, architecture.input_vector_size+1)
193
+ )
194
+ else:
195
+ weights[i] = rng.uniform(
196
+ low=bounds[0],
197
+ high=bounds[1],
198
+ size=(layer, architecture.layers[i-1]+1)
199
+ )
200
+
201
+ return seed
202
+
203
+ def compute_gradient_norm(
204
+ weights_gradients: list[np.ndarray]
205
+ ) -> float:
206
+ """
207
+ Compute the global L2 norm of the weights gradients.
208
+
209
+ Parameters
210
+ ----------
211
+ weights_gradients : list of np.ndarray
212
+ List containing the negative weights gradient matrix of each layer.
213
+
214
+ Returns
215
+ -------
216
+ float
217
+ Global L2 norm of all weights gradients.
218
+ """
219
+ return np.sqrt(
220
+ sum(np.sum(grad ** 2) for grad in weights_gradients)
221
+ )
@@ -0,0 +1,3 @@
1
+ """Additional utilities for the neural network simulator."""
2
+
3
+ from .save_n_load import save_model, load_model
@@ -0,0 +1,175 @@
1
+ """
2
+ Module providing utilities to save and load neural network models.
3
+ """
4
+ import os
5
+ from datetime import datetime
6
+ import numpy as np
7
+ from ..engine.nn_sim import NeuralNetwork
8
+
9
+ def save_model(
10
+ nn: NeuralNetwork,
11
+ model_name: str = None,
12
+ models_dir: str = "models"
13
+ ) -> str:
14
+ """
15
+ Save a neural network model to disk.
16
+
17
+ The model is saved in a dedicated directory containing NumPy
18
+ files with the network architecture, weight matrices and
19
+ available training configuration.
20
+
21
+ If no model name is provided, a name based on the current
22
+ date and time is generated.
23
+
24
+ Parameters
25
+ ----------
26
+ nn : NeuralNetwork
27
+ Neural network instance to be saved.
28
+ model_name : str or None, default=None
29
+ Name of the directory where the model will be saved.
30
+ If None, a timestamp-based name is generated.
31
+ models_dir : str, default="models"
32
+ Parent directory where the model directory will be created.
33
+ It is created if it does not already exist.
34
+
35
+ Returns
36
+ -------
37
+ str
38
+ Path to the directory containing the saved model.
39
+
40
+ Notes
41
+ -----
42
+ The following files are saved:
43
+
44
+ - ``weights.npy``: network weight matrices.
45
+ - ``architecture.npy``: network architecture.
46
+ - ``training_parameters.npy``: training parameters, if available.
47
+ - ``update_parameters.npy``: weight update parameters, if available.
48
+ - ``stopping_criteria.npy``: stopping criteria, if available.
49
+ - ``training_log.npy``: training history, if available.
50
+ """
51
+ # Generate model name if not provided
52
+ if model_name is None:
53
+ model_name = (
54
+ f"model_{datetime.now().strftime('%Y%m%d_%H%M')}"
55
+ )
56
+
57
+ # Create model directory
58
+ model_path = os.path.join(models_dir, model_name)
59
+ os.makedirs(model_path, exist_ok=True)
60
+
61
+ # Save weights
62
+ np.save(
63
+ os.path.join(model_path, "weights.npy"),
64
+ np.array(nn.weights, dtype=object),
65
+ allow_pickle=True
66
+ )
67
+
68
+ # Save architecture
69
+ np.save(
70
+ os.path.join(model_path, "architecture.npy"),
71
+ nn.architecture,
72
+ allow_pickle=True
73
+ )
74
+
75
+ # Save training parameters
76
+ if nn.training_params is not None:
77
+ np.save(
78
+ os.path.join(model_path, "training_parameters.npy"),
79
+ nn.training_params,
80
+ allow_pickle=True
81
+ )
82
+
83
+ # Save update parameters
84
+ if nn.update_params is not None:
85
+ np.save(
86
+ os.path.join(model_path, "update_parameters.npy"),
87
+ nn.update_params,
88
+ allow_pickle=True
89
+ )
90
+
91
+ # Save stopping criteria
92
+ if nn.stopping_crit is not None:
93
+ np.save(
94
+ os.path.join(model_path, "stopping_criteria.npy"),
95
+ nn.stopping_crit,
96
+ allow_pickle=True
97
+ )
98
+
99
+ # Save training log
100
+ if nn.training_log is not None:
101
+ np.save(
102
+ os.path.join(model_path, "training_log.npy"),
103
+ nn.training_log,
104
+ allow_pickle=True
105
+ )
106
+
107
+ return model_path
108
+
109
+ def load_model(
110
+ model_path: str
111
+ ) -> NeuralNetwork:
112
+ """
113
+ Load a neural network model from disk.
114
+
115
+ The function restores the network architecture, weight matrices
116
+ and available training configuration, returning a new
117
+ NeuralNetwork instance.
118
+
119
+ Parameters
120
+ ----------
121
+ model_path : str
122
+ Path to the directory containing the saved model files.
123
+
124
+ Returns
125
+ -------
126
+ NeuralNetwork
127
+ Restored neural network instance initialized with the
128
+ loaded architecture, weights and available parameters.
129
+
130
+ Notes
131
+ -----
132
+ The following files are required:
133
+
134
+ - ``architecture.npy``: network architecture.
135
+ - ``weights.npy``: network weight matrices.
136
+
137
+ Training, update and stopping parameters are restored only
138
+ if their corresponding files are present.
139
+ """
140
+ # Load architecture
141
+ architecture = np.load(
142
+ os.path.join(model_path, "architecture.npy"),
143
+ allow_pickle=True
144
+ ).item()
145
+
146
+ # Initialize neural network
147
+ nn = NeuralNetwork(architecture=architecture)
148
+
149
+ # Load weights
150
+ nn.weights = np.load(
151
+ os.path.join(model_path, "weights.npy"),
152
+ allow_pickle=True
153
+ ).tolist()
154
+
155
+ # Define optional parameter files
156
+ parameter_files = {
157
+ "training_params": "training_parameters.npy",
158
+ "update_params": "update_parameters.npy",
159
+ "stopping_crit": "stopping_criteria.npy"
160
+ }
161
+
162
+ # Restore available training configuration
163
+ for attribute, filename in parameter_files.items():
164
+ parameter_path = os.path.join(model_path, filename)
165
+ if os.path.isfile(parameter_path):
166
+ setattr(
167
+ nn,
168
+ attribute,
169
+ np.load(
170
+ parameter_path,
171
+ allow_pickle=True
172
+ ).item()
173
+ )
174
+
175
+ return nn