BaseNeuralNet¶
Defined in fynance.models._base
- class BaseNeuralNet[source]
Bases:
ModuleBase object for neural network model with PyTorch.
Thin wrapper around
torch.nn.Modulethat bundles the boilerplate of training a financial model: criterion + optimizer setup, a one-batchtrain_onstep, gradient-freepredict, data coercion from NumPy / polars / tensor, and weight serialization. Subclass it (or one of the higher-level subclasses such asMultiLayerPerceptron) and implement theforwardmethod to define a new architecture; everything else is inherited.Inherits of torch.nn.Module object with some higher level methods.
Public API contract (stable for the 1.x series)
Shapes — all current subclasses (the feed-forward
MultiLayerPerceptron, the gated cells infynance.models.rnn,fynance.models.gru,fynance.models.lstm, and the convolutional / attention models) expectXof shape(T, N)andyof shape(T, M), whereTis the number of observations,Nthe number of input features andMthe number of targets. The gated “recurrent” cells process each of theTrows independently (they are stateless gated feed-forward cells — see their own class docstrings); they do not thread a hidden state across a time axis.Dtypes —
set_datacoerces inputs through_set_data, which casts floating-point inputs totorch.get_default_dtype()(float32by default) so plainfloat64NumPy arrays train without manual.astype. Integer inputs keep their dtype. Passx_type/y_typeexplicitly to force a specific dtype.Device — the wrapper does not move tensors automatically. Models live on CPU unless the caller explicitly calls
.to(device)on both the module and the data tensors before training.State invariants — typical lifecycle:
set_optimizer→set_data(optional) →train_on(loops) →predict.train_onrequirescriterionandoptimizerto be set; calling it beforeset_optimizerraisesAttributeError.Serialization —
save_model/load_modelpersist the modulestate_dictand, whensave_optimizer/load_optimizeris True, the optimizerstate_dict. Random seeds, learning-rate schedulers and the cached training data (self.X,self.y) are not serialized.
- Attributes:
- criteriontorch.nn.modules.loss.Loss
A loss function.
- optimizertorch.optim.Optimizer
An optimizer algorithm.
- N, Mint
Respectively input and output dimension.
Methods
set_optimizer(criterion, optimizer[, params])Set the optimizer object.
train_on(X, y)Trains the neural network model on a single batch.
predict(X)Predicts outputs of neural network model.
set_data(X, y[, x_type, y_type])Set data inputs and outputs.
save_model(path[, save_optimizer])Save the model with this weights and parameters.
load_model(path[, load_optimizer])Load the model weights and parameters from a file.
See also
fynance.models.mlp.MultiLayerPerceptronfynance.models.rolling.RollMultiLayerPerceptron
- fit(X, y, epochs=1, x_type=None, y_type=None)[source]
Fit the model on
(X, y)forepochsfull-batch steps.Convenience wrapper that makes the network conform to the
SignalModelprotocol: it coerces the data viaset_dataand runstrain_onepochstimes. An optimizer must have been registered withset_optimizer.- Parameters:
- X, yarray-like
Input and output data (numpy / torch / polars), shapes
(T, N)and(T, M).- epochsint
Number of full-batch training steps.
- x_type, y_typetorch.dtype, optional
Target dtypes forwarded to
set_data.
- Returns:
- BaseNeuralNet
self, to allow chaining.
- load_model(path, load_optimizer=False)[source]
Load the model weights and parameters from a file.
- Parameters:
- pathstr or os.PathLike object
Path to load the model.
- load_optimizerbool, optional
If True, then load also the optimizer.
- predict(X)[source]
Predicts outputs of neural network model.
Runs
self.forward(X)undertorch.no_gradwith the module switched to evaluation mode, so no autograd graph is built and stochastic layers (dropout, batch-norm) behave deterministically. The previous training/eval mode is restored on exit. The returned tensor is detached and lives on the same device as the model parameters; the coerced input is moved to that device too. Array-like inputs (numpy / polars) are coerced to a tensor first, so the method also satisfies theSignalModelcontract.- Parameters:
- Xarray-like
Inputs to compute prediction. Same shape and dtype contract as
train_on.
- Returns:
- torch.Tensor
Outputs prediction (detached, gradient-free).
- save_model(path, save_optimizer=False)[source]
Save the model with this weights and parameters.
- Parameters:
- pathstr or os.PathLike object
Path to save the model.
- save_optimizerbool, optional
If True, then save also the optimizer.
- set_data(X, y, x_type=None, y_type=None)[source]
Set data inputs and outputs.
Coerces
Xandytotorch.Tensorand caches them asself.X/self.y. After the call the attributesself.T(number of observations),self.N(input columns) andself.M(output columns) are set.- Parameters:
- X, yarray-like
Respectively input and output data. Accepted types:
numpy.ndarray,torch.Tensor,polars.DataFrame. Shapes must be(T, N)and(T, M)respectively.- x_type, y_typetorch.dtype, optional
Target dtypes for the resulting tensors. Default is None, which casts floating-point inputs to
torch.get_default_dtype()(float32by default) and leaves integer inputs unchanged. See_set_data.
- Returns:
- BaseNeuralNet
self, to allow chaining.
- Raises:
- ValueError
If
self.N/self.Mwere already set andX/ydo not match, or ifXandyhave different lengths.
- set_lr_scheduler(lr_scheduler, **kwargs)[source]
Set dynamic learning rate.
- Parameters:
- lr_schedulertorch.optim.lr_scheduler._LRScheduler
Method from
torch.optim.lr_schedulerto wrapself.optimizer, cf moduletorch.optim.lr_schedulerin PyTorch documentation [2].- **kwargs
Keyword arguments to pass to the learning rate scheduler.
References
- set_optimizer(criterion, optimizer, params=None, **kwargs)[source]
Set the optimizer object.
Set optimizer object with specified criterion as loss function and any kwargs as optional parameters.
- Parameters:
- criterionCallable, torch.nn.modules.loss
A loss function.
- optimizertorch.optim.Optimizer
An optimizer algorithm.
- paramsobject or iterable object
Layer of parameters to optimize or dicts defining parameter groups. If set to None then all parameters of model will be optimized. Default is None.
- **kwargs
Keyword arguments of
optimizer, cf PyTorch documentation [1].
- Returns:
- BaseNeuralNet
Self object model.
References
- set_seed(seed_torch=None, seed_numpy=None)[source]
Set seed for PyTorch and NumPy random number generator.
Each generator is only (re)seeded when its argument is provided: passing
seed_torchalone leaves the global NumPy RNG untouched, and vice versa.- Parameters:
- seed_torch, seed_numpybool or int, optional
If an int \(0 \leq seed < 2^{32}\), seed respectively the PyTorch and NumPy generator with that number. If
True, draw a random seed. IfNone(default), leave that generator untouched.
Examples
>>> from fynance.models.mlp import MultiLayerPerceptron >>> model = MultiLayerPerceptron(3, 1, layers=[4]) >>> model.set_seed(seed_torch=42) >>> model.seed_torch 42 >>> model.seed_numpy is None True
- train_on(X, y)[source]
Trains the neural network model on a single batch.
Runs one forward / backward / optimizer-step cycle on the batch
(X, y). The module is switched to training mode (so dropout and batch-norm behave as expected) before the forward pass. As a side effect, gradients of all parameters are zeroed before the forward pass and the optimizer state is advanced afterwards. If a learning-rate scheduler has been registered viaset_lr_scheduler, itsstepis also called.- Parameters:
- X, ytorch.Tensor
Respectively inputs and outputs to train model. Shapes must match what
self.forwardexpects (see the class-level “Public API contract” section).
- Returns:
- torch.Tensor
The loss tensor produced by
self.criterion(self(X), y), with gradient already consumed byloss.backward().
- Raises:
- AttributeError
If
set_optimizerhas not been called yet.