BaseNeuralNet

Defined in fynance.models._base

class BaseNeuralNet[source]

Bases: Module

Base object for neural network model with PyTorch.

Thin wrapper around torch.nn.Module that bundles the boilerplate of training a financial model: criterion + optimizer setup, a one-batch train_on step, gradient-free predict, data coercion from NumPy / pandas / tensor, and weight serialization. Subclass it (or one of the higher-level subclasses such as MultiLayerPerceptron) and implement the forward method 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 — feed-forward subclasses (e.g. MultiLayerPerceptron) expect X of shape (T, N) and y of shape (T, M), where T is the number of observations, N the number of input features and M the number of targets. Recurrent subclasses in fynance.models.rnn, fynance.models.gru, fynance.models.lstm consume X of shape (T, S, N), where S is the sequence length.

  • Dtypesset_data coerces inputs through _set_data. The expected default for both X and y is a floating tensor (torch.float32 is the de-facto convention in the project doctests). Pass x_type / y_type explicitly to override; mismatched dtypes between X, y and the model parameters will raise at the first forward pass.

  • 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_optimizerset_data (optional) → train_on (loops) → predict. train_on requires criterion and optimizer to be set; calling it before set_optimizer raises AttributeError.

  • Serializationsave_model / load_model persist the module state_dict and, when save_optimizer / load_optimizer is True, the optimizer state_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])

Save the model with this weights and parameters.

See also

fynance.models.mlp.MultiLayerPerceptron
fynance.models.rolling.RollMultiLayerPerceptron
load_model(path, load_optimizer=False)[source]

Save the model with this weights and parameters.

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) under torch.no_grad, so no autograd graph is built. The returned tensor is detached and lives on the same device as the model parameters.

Parameters:
Xtorch.Tensor

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 X and y to torch.Tensor and caches them as self.X / self.y. After the call the attributes self.T (number of observations), self.N (input columns) and self.M (output columns) are set.

Parameters:
X, yarray-like

Respectively input and output data. Accepted types: numpy.ndarray, torch.Tensor, pandas.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 preserves the input dtype.

Returns:
BaseNeuralNet

self, to allow chaining.

Raises:
ValueError

If self.N / self.M were already set and X / y do not match, or if X and y have 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_scheduler to wrap self.optimizer, cf module torch.optim.lr_scheduler in 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:
criterionCallabletorch.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.

Parameters:
seed_torch, seed_numpybool or int, optional

If seed is an int \(0 < seed < 2^32\) set respectively PyTorch and NumPy seed with the number. Otherwise if is True then choose a random number, else doesn’t set seed.

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). 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 via set_lr_scheduler, its step is also called.

Parameters:
X, ytorch.Tensor

Respectively inputs and outputs to train model. Shapes must match what self.forward expects (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 by loss.backward().

Raises:
AttributeError

If set_optimizer has not been called yet.