API reference

Everything you need is in the djinn package:

from djinn import DJINN_Regressor, DJINN_Classifier, load

Models

class djinn.DJINN_Regressor(n_trees=1, max_tree_depth=4, dropout_keep_prob=1.0, *, epochs=None, learning_rate=None, batch_size=None, weight_decay=1e-08, clip_inputs=False, random_state=None, device='cpu', verbose=0)[source]

DJINN regression model (PyTorch backend).

A scikit-learn compatible regressor: it supports sklearn.base.clone(), get_params()/set_params(), and score() (R²).

Parameters:
  • n_trees (int, optional) – Number of trees in the random forest (equal to the number of neural networks).

  • max_tree_depth (int, optional) – Maximum depth of decision tree. The neural network has max_tree_depth - 1 hidden layers.

  • dropout_keep_prob (float, optional) – Probability of keeping a neuron in dropout layers.

  • epochs (int or None, optional) – Training epochs used by fit(). None picks them automatically when learning_rate is also None, otherwise uses 1000.

  • learning_rate (float or None, optional) – Learning rate used by fit(). None runs get_hyperparameters() to choose it.

  • batch_size (int or None, optional) – Minibatch size used by fit(). None uses 5% of the samples.

  • weight_decay (float, optional) – Multiplier for the L2 penalty on weights.

  • clip_inputs (bool, optional) – Clip inputs to the range seen in training before predicting. The networks can give very large errors far outside that range, so this trades extrapolation for safer predictions.

  • random_state (int or None, optional) – Seed for the forest, weight initialization, and training.

  • device (str or torch.device, optional) – Device used for training and inference, such as "cpu", "cuda" or "mps". "auto" picks CUDA if it is available, then MPS, then the CPU. Default "cpu".

  • verbose (int, optional) – Print progress messages when greater than 0.

n_trees_

Number of trained networks.

Type:

int

models_

Trained networks, keyed by tree index.

Type:

dict of torch.nn.Module

xscale_

Scaler fit to the training inputs.

Type:

sklearn.preprocessing.MinMaxScaler

yscale_

Scaler fit to the training targets.

Type:

sklearn.preprocessing.MinMaxScaler

n_features_in_

Number of features seen during fit.

Type:

int

feature_names_in_

Names of the features seen during fit. Only set when X has feature names that are all strings.

Type:

ndarray of str

nninfo_

Details from the last training run, including the loss per epoch in train_cost and valid_cost. Not set on loaded models.

Type:

dict

calibration_residuals_

Sorted absolute errors on the calibration data. Only set after calibrate(), and cleared when the model is trained again.

Type:

ndarray of shape (n_calibration, n_outputs)

Examples

>>> from sklearn.datasets import load_diabetes
>>> from djinn import DJINN_Regressor
>>> X, y = load_diabetes(return_X_y=True)
>>> model = DJINN_Regressor(n_trees=3, learning_rate=0.005, epochs=200)
>>> model.fit(X, y).predict(X[:2]).shape
(2,)
bayesian_predict(x_test, n_iters, seed=None)

Bayesian distribution of predictions for a set of test inputs.

Evaluates each tree network n_iters times (with dropout active) to build a predictive distribution, then returns the 25th, 50th, and 75th percentiles alongside the raw sample dictionary.

Parameters:
  • x_test (ndarray) – Input feature matrix for testing.

  • n_iters (int or None) – Number of forward passes per network per test point. Pass None for a single non-Bayesian pass.

  • seed (int or None, optional) – Random seed for reproducibility.

Returns:

If n_iters is None, returns mean predictions with shape (n_test, n_outputs). Otherwise returns (lower, middle, upper, samples), where percentile arrays have shape (n_test, n_outputs) and samples contains per-tree prediction draws.

Return type:

ndarray or tuple

bma_predict(x_test, n_iters=100, seed=None)

Return Bayesian model averaging samples and summary statistics.

The percentiles show how much the networks disagree, but they are not calibrated and usually hold fewer true values than their range suggests. For regression, DJINN_Regressor.predict_interval() gives intervals with a known coverage.

Parameters:
  • x_test (ndarray) – Input feature matrix for testing.

  • n_iters (int, optional) – Number of stochastic forward passes per tree.

  • seed (int or None, optional) – Random seed for reproducibility.

Returns:

Dictionary containing percentile summaries and stacked prediction samples under predictions with shape (n_iters * n_trees, n_test, n_outputs).

Return type:

dict

calibrate(X, y)[source]

Store the prediction errors on held-out data.

predict_interval() uses them to set the interval width. X and y must not have been used to fit the model, otherwise the errors are too small and the intervals too narrow.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Calibration inputs.

  • y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – Calibration targets.

Return type:

self

close_model()

Release all loaded PyTorch models from memory.

Return type:

None

collect_tree_predictions(predictions)

Gather and reshape the full distribution of per-tree predictions.

Parameters:

predictions (dict) – "predictions" sub-dictionary from the dictionary returned by bayesian_predict().

Returns:

Reshaped predictions with shape (n_iters * n_trees, n_test, n_outputs).

Return type:

ndarray

continue_training(X, Y, training_epochs, learning_rate, batch_size, learn_rate=None, seed=None)

Continue training a saved model.

Load the model with djinn.load() first. Each network is trained from its checkpoint for training_epochs more epochs, the checkpoints are saved in place, and the updated networks are used by predict() afterwards.

Parameters:
  • X (ndarray) – Input feature matrix for training.

  • Y (ndarray) – Target array for training.

  • training_epochs (int) – Additional epochs to train.

  • learning_rate (float) – Learning rate.

  • learn_rate (float or None, optional) – Backward-compatible alias for learning_rate.

  • batch_size (int) – Number of samples per batch.

  • seed (int or None, optional) – Random seed for reproducibility.

Return type:

None

fit(X, y, **kwargs)

Train DJINN using the settings given to the constructor.

When learning_rate is None, get_hyperparameters() picks the learning rate, and also the epochs and batch size unless they were set.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Training features.

  • y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – Training targets.

  • **kwargs – Deprecated. epochs, learning_rate, learn_rate, batch_size, weight_decay, save_files, save_model, model_name, model_path, and seed are still accepted but will be removed in 2.0. Set them in the constructor, or use train() and save().

Returns:

The trained model.

Return type:

self

classmethod from_json(json_path)

Reconstruct a model from a saved JSON state file.

Restores all hyperparameters and scalers so the instance is ready for load_model(), predict(), or continue_training().

Parameters:

json_path (str or pathlib.Path) – Path to the .json file written by train().

Returns:

Restored model instance.

Return type:

DJINN_Regressor or DJINN_Classifier

get_hyperparameters(X, Y, weight_decay=1e-08, seed=None)

Automatically select DJINN hyperparameters.

Returns learning rate, number of epochs, and batch size by running a short auto-tuning search using the PyTorch training utilities in neural_network.py.

Parameters:
  • X (ndarray) – Input feature matrix for training.

  • Y (ndarray) – Target array for training.

  • weight_decay (float, optional) – Multiplier for L2 penalty on weights.

  • seed (int or None, optional) – Random seed for reproducibility. Defaults to random_state.

Raises:

Exception – If a decision tree cannot be built from the data.

Returns:

Dictionary with keys batch_size, learning_rate, and epochs.

Return type:

dict

get_params(deep=True)

Get parameters for this estimator.

Parameters:

deep (bool, default=True) – If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns:

params – Parameter names mapped to their values.

Return type:

dict

load_model(model_name, model_path)

Reload PyTorch checkpoints for a saved model.

Restores each tree’s .pt checkpoint from disk using neural_network.load_tree_model.

Parameters:
  • model_name (str) – Name of the saved model directory.

  • model_path (str or pathlib.Path) – Parent directory that contains the model folder.

Return type:

None

predict(x_test, seed=None)

Predict target values for a set of test inputs.

Calls bayesian_predict() with n_iters=None (single deterministic forward pass per network) and returns the mean.

Parameters:
  • x_test (ndarray) – Input feature matrix for testing.

  • seed (int or None, optional) – Random seed for reproducibility.

Returns:

Mean target value prediction for each test point, shape (n_test,) if the model was trained on a 1-D target, otherwise (n_test, n_outputs).

Return type:

ndarray

predict_interval(X, coverage=0.9)[source]

Prediction intervals calibrated on held-out data.

Uses split conformal prediction: the interval is predict() plus or minus the error that a coverage fraction of the calibration points fall within. If new data comes from the same distribution as the calibration data, at least coverage of the true values will be inside. The width is the same for every input. Call calibrate() first.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Input feature matrix.

  • coverage (float, optional) – Fraction of true values the intervals should contain.

Returns:

lower, upper – Interval bounds, with the same shape as predict().

Return type:

ndarray

Raises:

ValueError – If coverage is not between 0 and 1, or there are too few calibration points for it.

save(model_path, overwrite=False)

Persist the currently loaded model under an explicit output path.

Checkpoints are written from the in-memory models, so this works whether or not train() was called with save_model=True.

Parameters:
  • model_path (str or pathlib.Path) – Target base path. Writes checkpoints to <model_path>/ and metadata to <model_path>.json.

  • overwrite (bool, optional) – If True, delete and replace model_path when it already exists. Defaults to False, which raises instead of silently deleting an existing directory.

Returns:

Saved model directory path.

Return type:

pathlib.Path

Raises:
  • RuntimeError – If there are no trained or loaded models to save.

  • FileExistsError – If model_path already exists and overwrite is False.

score(X, y, sample_weight=None)

Return coefficient of determination on test data.

The coefficient of determination, \(R^2\), is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)** 2).sum() and \(v\) is the total sum of squares ((y_true - y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.

  • y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True values for X.

  • sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.

Returns:

score – \(R^2\) of self.predict(X) w.r.t. y.

Return type:

float

Notes

The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score(). This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_params(**params)

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Parameters:

**params (dict) – Estimator parameters.

Returns:

self – Estimator instance.

Return type:

estimator instance

train(X, Y, epochs=1000, learning_rate=0.001, learn_rate=None, batch_size=0, weight_decay=1e-08, save_files=False, save_model=False, model_name='djinn_model', model_path='./', ntrees=None, seed=None, eval_every=1)

Train DJINN with specified hyperparameters.

Builds a random forest, maps each tree to a PyTorch MLP via random_forest.tree_to_nn_weights, then trains every network using neural_network.torch_dropout_regression.

Parameters:
  • X (ndarray) – Input feature matrix for training.

  • Y (ndarray) – Target array for training.

  • epochs (int, optional) – Number of training epochs.

  • learning_rate (float, optional) – Learning rate for weight and bias optimization.

  • learn_rate (float or None, optional) – Backward-compatible alias for learning_rate.

  • batch_size (int, optional) – Number of samples per batch. If 0, uses 5% of the dataset.

  • weight_decay (float, optional) – Multiplier for L2 penalty on weights.

  • save_files (bool, optional) – If True, saves train/validation cost per epoch and weights/biases.

  • save_model (bool, optional) – If True, saves the trained model.

  • model_name (str, optional) – File name for the model when save_model is True.

  • model_path (str, optional) – Directory where model/files are saved.

  • ntrees (int or None, optional) – Number of trees to train. Defaults to n_trees.

  • seed (int or None, optional) – Random seed for reproducibility. Defaults to random_state.

  • eval_every (int, optional) – Compute the validation loss every eval_every epochs.

Raises:

Exception – If a decision tree cannot be built from the data.

Returns:

The trained model.

Return type:

self

class djinn.DJINN_Classifier(n_trees=1, max_tree_depth=4, dropout_keep_prob=1.0, *, epochs=None, learning_rate=None, batch_size=None, weight_decay=1e-08, clip_inputs=False, random_state=None, device='cpu', verbose=0)[source]

DJINN classification model.

Shares training, saving, and loading with DJINN_Regressor. The difference is in bayesian_predict(), where no output scaling is applied and np.argmax converts softmax distributions into class predictions. score() reports accuracy.

Parameters:
  • n_trees (int, optional) – Number of trees in the random forest (equal to the number of neural networks).

  • max_tree_depth (int, optional) – Maximum depth of decision tree. The neural network has max_tree_depth - 1 hidden layers.

  • dropout_keep_prob (float, optional) – Probability of keeping a neuron in dropout layers.

  • epochs (int or None, optional) – Training epochs used by fit(). None picks them automatically when learning_rate is also None, otherwise uses 1000.

  • learning_rate (float or None, optional) – Learning rate used by fit(). None runs get_hyperparameters() to choose it.

  • batch_size (int or None, optional) – Minibatch size used by fit(). None uses 5% of the samples.

  • weight_decay (float, optional) – Multiplier for the L2 penalty on weights.

  • clip_inputs (bool, optional) – Clip inputs to the range seen in training before predicting. The networks can give very large errors far outside that range, so this trades extrapolation for safer predictions.

  • random_state (int or None, optional) – Seed for the forest, weight initialization, and training.

  • device (str or torch.device, optional) – Device used for training and inference, such as "cpu", "cuda" or "mps". "auto" picks CUDA if it is available, then MPS, then the CPU. Default "cpu".

  • verbose (int, optional) – Print progress messages when greater than 0.

classes_

Class labels seen during fit.

Type:

ndarray of shape (n_classes,)

n_trees_

Number of trained networks.

Type:

int

models_

Trained networks, keyed by tree index.

Type:

dict of torch.nn.Module

xscale_

Scaler fit to the training inputs.

Type:

sklearn.preprocessing.MinMaxScaler

n_features_in_

Number of features seen during fit.

Type:

int

feature_names_in_

Names of the features seen during fit. Only set when X has feature names that are all strings.

Type:

ndarray of str

nninfo_

Details from the last training run, including the loss per epoch in train_cost and valid_cost. Not set on loaded models.

Type:

dict

Examples

>>> from sklearn.datasets import load_iris
>>> from djinn import DJINN_Classifier
>>> X, y = load_iris(return_X_y=True)
>>> model = DJINN_Classifier(n_trees=3, learning_rate=0.01, epochs=200)
>>> model.fit(X, y).predict_proba(X[:2]).shape
(2, 3)
bayesian_predict(x_test, n_iters, seed=None)[source]

Bayesian distribution of class predictions for a set of test inputs.

Evaluates each tree network n_iters times (with dropout active) to build a predictive distribution over class probabilities, then returns the argmax of the 25th, 50th, and 75th percentiles as class labels alongside the raw sample dictionary.

Parameters:
  • x_test (ndarray) – Input feature matrix for testing.

  • n_iters (int or None) – Number of forward passes per network per test point. Pass None for a single deterministic pass.

  • seed (int or None, optional) – Random seed for reproducibility.

Returns:

If n_iters is None, returns a 1-D array of predicted class labels with shape (n_test,). Otherwise returns (lower, middle, upper, samples), where percentile outputs are 1-D arrays of class labels and samples contains per-tree probability draws.

Return type:

ndarray or tuple

bma_predict(x_test, n_iters=100, seed=None)

Return Bayesian model averaging samples and summary statistics.

The percentiles show how much the networks disagree, but they are not calibrated and usually hold fewer true values than their range suggests. For regression, DJINN_Regressor.predict_interval() gives intervals with a known coverage.

Parameters:
  • x_test (ndarray) – Input feature matrix for testing.

  • n_iters (int, optional) – Number of stochastic forward passes per tree.

  • seed (int or None, optional) – Random seed for reproducibility.

Returns:

Dictionary containing percentile summaries and stacked prediction samples under predictions with shape (n_iters * n_trees, n_test, n_outputs).

Return type:

dict

close_model()

Release all loaded PyTorch models from memory.

Return type:

None

collect_tree_predictions(predictions)

Gather and reshape the full distribution of per-tree predictions.

Parameters:

predictions (dict) – "predictions" sub-dictionary from the dictionary returned by bayesian_predict().

Returns:

Reshaped predictions with shape (n_iters * n_trees, n_test, n_outputs).

Return type:

ndarray

continue_training(X, Y, training_epochs, learning_rate, batch_size, learn_rate=None, seed=None)

Continue training a saved model.

Load the model with djinn.load() first. Each network is trained from its checkpoint for training_epochs more epochs, the checkpoints are saved in place, and the updated networks are used by predict() afterwards.

Parameters:
  • X (ndarray) – Input feature matrix for training.

  • Y (ndarray) – Target array for training.

  • training_epochs (int) – Additional epochs to train.

  • learning_rate (float) – Learning rate.

  • learn_rate (float or None, optional) – Backward-compatible alias for learning_rate.

  • batch_size (int) – Number of samples per batch.

  • seed (int or None, optional) – Random seed for reproducibility.

Return type:

None

fit(X, y, **kwargs)

Train DJINN using the settings given to the constructor.

When learning_rate is None, get_hyperparameters() picks the learning rate, and also the epochs and batch size unless they were set.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Training features.

  • y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – Training targets.

  • **kwargs – Deprecated. epochs, learning_rate, learn_rate, batch_size, weight_decay, save_files, save_model, model_name, model_path, and seed are still accepted but will be removed in 2.0. Set them in the constructor, or use train() and save().

Returns:

The trained model.

Return type:

self

classmethod from_json(json_path)

Reconstruct a model from a saved JSON state file.

Restores all hyperparameters and scalers so the instance is ready for load_model(), predict(), or continue_training().

Parameters:

json_path (str or pathlib.Path) – Path to the .json file written by train().

Returns:

Restored model instance.

Return type:

DJINN_Regressor or DJINN_Classifier

get_hyperparameters(X, Y, weight_decay=1e-08, seed=None)

Automatically select DJINN hyperparameters.

Returns learning rate, number of epochs, and batch size by running a short auto-tuning search using the PyTorch training utilities in neural_network.py.

Parameters:
  • X (ndarray) – Input feature matrix for training.

  • Y (ndarray) – Target array for training.

  • weight_decay (float, optional) – Multiplier for L2 penalty on weights.

  • seed (int or None, optional) – Random seed for reproducibility. Defaults to random_state.

Raises:

Exception – If a decision tree cannot be built from the data.

Returns:

Dictionary with keys batch_size, learning_rate, and epochs.

Return type:

dict

get_params(deep=True)

Get parameters for this estimator.

Parameters:

deep (bool, default=True) – If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns:

params – Parameter names mapped to their values.

Return type:

dict

load_model(model_name, model_path)

Reload PyTorch checkpoints for a saved model.

Restores each tree’s .pt checkpoint from disk using neural_network.load_tree_model.

Parameters:
  • model_name (str) – Name of the saved model directory.

  • model_path (str or pathlib.Path) – Parent directory that contains the model folder.

Return type:

None

predict(x_test, seed=None)[source]

Predict class labels for a set of test inputs.

Calls bayesian_predict() with n_iters=None (single deterministic forward pass per network) and returns the argmax class predictions.

Parameters:
  • x_test (ndarray) – Input feature matrix for testing.

  • seed (int or None, optional) – Random seed for reproducibility.

Returns:

Predicted class label for each test point, shape (n_test,).

Return type:

ndarray

predict_proba(x_test)[source]

Predict class probabilities for a set of test inputs.

Takes the per-class median of the tree networks’ softmax outputs (the same reduction predict() uses) and normalizes each row.

Parameters:

x_test (array-like of shape (n_test, n_features)) – Input features.

Returns:

Probabilities with shape (n_test, n_classes), columns ordered as classes_.

Return type:

ndarray

save(model_path, overwrite=False)

Persist the currently loaded model under an explicit output path.

Checkpoints are written from the in-memory models, so this works whether or not train() was called with save_model=True.

Parameters:
  • model_path (str or pathlib.Path) – Target base path. Writes checkpoints to <model_path>/ and metadata to <model_path>.json.

  • overwrite (bool, optional) – If True, delete and replace model_path when it already exists. Defaults to False, which raises instead of silently deleting an existing directory.

Returns:

Saved model directory path.

Return type:

pathlib.Path

Raises:
  • RuntimeError – If there are no trained or loaded models to save.

  • FileExistsError – If model_path already exists and overwrite is False.

score(X, y, sample_weight=None)

Return accuracy on provided data and labels.

In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Test samples.

  • y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True labels for X.

  • sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.

Returns:

score – Mean accuracy of self.predict(X) w.r.t. y.

Return type:

float

set_params(**params)

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Parameters:

**params (dict) – Estimator parameters.

Returns:

self – Estimator instance.

Return type:

estimator instance

train(X, Y, epochs=1000, learning_rate=0.001, learn_rate=None, batch_size=0, weight_decay=1e-08, save_files=False, save_model=False, model_name='djinn_model', model_path='./', ntrees=None, seed=None, eval_every=1)

Train DJINN with specified hyperparameters.

Builds a random forest, maps each tree to a PyTorch MLP via random_forest.tree_to_nn_weights, then trains every network using neural_network.torch_dropout_regression.

Parameters:
  • X (ndarray) – Input feature matrix for training.

  • Y (ndarray) – Target array for training.

  • epochs (int, optional) – Number of training epochs.

  • learning_rate (float, optional) – Learning rate for weight and bias optimization.

  • learn_rate (float or None, optional) – Backward-compatible alias for learning_rate.

  • batch_size (int, optional) – Number of samples per batch. If 0, uses 5% of the dataset.

  • weight_decay (float, optional) – Multiplier for L2 penalty on weights.

  • save_files (bool, optional) – If True, saves train/validation cost per epoch and weights/biases.

  • save_model (bool, optional) – If True, saves the trained model.

  • model_name (str, optional) – File name for the model when save_model is True.

  • model_path (str, optional) – Directory where model/files are saved.

  • ntrees (int or None, optional) – Number of trees to train. Defaults to n_trees.

  • seed (int or None, optional) – Random seed for reproducibility. Defaults to random_state.

  • eval_every (int, optional) – Compute the validation loss every eval_every epochs.

Raises:

Exception – If a decision tree cannot be built from the data.

Returns:

The trained model.

Return type:

self

Loading

djinn.load(model_path)[source]

Load a saved DJINN model from path.

Parameters:

model_path (str or pathlib.Path) – Path to the model directory or its JSON sidecar.

Returns:

Reconstructed model with checkpoints loaded.

Return type:

DJINN_Regressor or DJINN_Classifier

Internals

These modules do the work behind the models. They aren’t needed for normal use, but How DJINN builds a network from a tree uses them to show each step.

djinn.random_forest

Tree-to-network mapping utilities for DJINN random-forest initialization.

This module contains helpers to train sklearn forests, extract tree structure, and convert each tree into the layer-width and weight matrices used to initialize DJINN neural networks.

djinn.random_forest.build_djinn_architecture(num_layers, nodes_per_depth, nin, nout)[source]

Construct the DJINN layer-width vector.

Parameters:
  • num_layers (int) – Number of network layers.

  • nodes_per_depth (numpy.ndarray) – Number of split nodes observed at each tree depth.

  • nin (int) – Input feature dimension.

  • nout (int) – Output dimension.

Returns:

Network architecture array (neurons per layer).

Return type:

numpy.ndarray

djinn.random_forest.build_node_dict(tree_structure)[source]

Build a node-indexed dictionary representation of tree structure.

Parameters:

tree_structure (dict) – Output of extract_tree_structure().

Returns:

Mapping from node index to a dictionary with depth, feature, and child split information.

Return type:

dict

djinn.random_forest.compute_layer_metadata(node_depth, features, nin)[source]

Compute depth-wise tree metadata used by DJINN mapping.

Parameters:
  • node_depth (numpy.ndarray) – Depth value for each node.

  • features (numpy.ndarray) – Feature index per node, negative values for leaves.

  • nin (int) – Number of input features.

Returns:

Metadata dictionary with num_layers, nodes_per_depth, leaves_per_depth, and max_depth_feature.

Return type:

dict

djinn.random_forest.connect_leaf_path(n_layer, num_layers, kk, neurons_layer, djinn_weights)[source]

Propagate a leaf decision path directly through to output.

Parameters:
  • n_layer (int) – Layer where the leaf was encountered.

  • num_layers (int) – Total number of layers.

  • kk (int) – Parent neuron index for the leaf path.

  • neurons_layer (list[numpy.ndarray]) – New neuron indices per layer.

  • djinn_weights (dict) – Layer weight matrices.

Returns:

Updated layer weight matrices.

Return type:

dict

djinn.random_forest.connect_output_layer(djinn_weights, neurons_layer, num_layers)[source]

Connect active hidden neurons to the output layer.

Parameters:
  • djinn_weights (dict) – Layer weight matrices to modify in-place.

  • neurons_layer (list) – New neuron indices for each layer.

  • num_layers (int) – Number of network layers.

Returns:

Updates the output-layer weights in place.

Return type:

None

djinn.random_forest.connect_split_child(n_layer, nn_in, nn_out, k, kk, feature, child_feature, djinn_weights, neurons_layer)[source]

Connect a split child branch into the current NN layer.

Parameters:
  • n_layer (int) – Current layer index.

  • nn_in (int) – Output width of the layer matrix.

  • nn_out (int) – Input width of the layer matrix.

  • k (int) – Index over newly created neurons at this layer.

  • kk (int) – Index over active parent neurons from previous layer.

  • feature (int) – Parent split feature index.

  • child_feature (int) – Child split feature index (non-negative for split nodes).

  • djinn_weights (dict) – Layer weight matrices.

  • neurons_layer (list[numpy.ndarray]) – New neuron indices per layer.

Returns:

Updated (djinn_weights, k, kk).

Return type:

tuple

djinn.random_forest.extract_tree_structure(tree_)[source]

Extract structural arrays and metadata from a fitted sklearn tree.

Parameters:

tree (sklearn.tree._tree.Tree) – Internal tree object from a fitted sklearn estimator.

Returns:

Dictionary containing split features, node depths, child indices, thresholds, leaf flags, and node count.

Return type:

dict

djinn.random_forest.fill_weight_connections(djinn_weights, node, num_layers, nin, neurons_layer, max_depth_feature)[source]

Populate all DJINN layer connections from tree metadata.

Parameters:
  • djinn_weights (dict) – Layer weight matrices to modify in-place.

  • node (dict) – Node metadata dictionary.

  • num_layers (int) – Number of network layers.

  • nin (int) – Number of input features.

  • neurons_layer (list) – New neuron indices for each layer.

  • max_depth_feature (numpy.ndarray) – Maximum depth where each feature appears.

Returns:

Mutates djinn_weights in place.

Return type:

None

djinn.random_forest.fit_scalers(X, Y, regression)[source]

Fit MinMaxScalers on raw input and output data.

Parameters:
  • X (ndarray) – Input feature matrix of shape (n_samples, n_features).

  • Y (ndarray) – Target array of shape (n_samples,) or (n_samples, n_outputs).

  • regression (bool) – Whether the task is regression. Only fits yscale when True.

Returns:

Fitted (xscale, yscale). yscale is None for classification.

Return type:

tuple[MinMaxScaler, MinMaxScaler or None]

djinn.random_forest.get_dimensions(X, Y, regression)[source]

Extract input and output dimensions from training data.

Parameters:
  • X (numpy.ndarray) – Input features of shape (n_samples, n_features).

  • Y (numpy.ndarray) – Target values for regression or class labels for classification.

  • regression (bool) – Whether the task is regression.

Returns:

Input and output dimensions (nin, nout).

Return type:

tuple[int, int]

djinn.random_forest.initialize_weight_arrays(djinn_arch, num_layers)[source]

Initialize DJINN weight matrices and new-neuron index lists.

Parameters:
  • djinn_arch (numpy.ndarray) – Network architecture array.

  • num_layers (int) – Number of layers.

Returns:

Tuple (djinn_weights, neurons_layer) with empty layer matrices and indices of neurons newly introduced at each layer.

Return type:

tuple[dict, list]

djinn.random_forest.map_single_tree_to_network(tree, nin, nout)[source]

Map one fitted tree into DJINN architecture and initial weights.

Parameters:
  • tree (sklearn.tree._tree.Tree) – Internal tree object from a fitted estimator.

  • nin (int) – Input dimension.

  • nout (int) – Output dimension.

Returns:

Tuple (djinn_arch, djinn_weights).

Return type:

tuple[numpy.ndarray, dict]

Raises:

ValueError – If the tree’s depth is too shallow (<= 1) to produce at least one hidden layer.

djinn.random_forest.off_diagonal_weights(n_layer, nn_in, nn_out, num_layers, node, djinn_weights, neurons_layer)[source]

Populate off-diagonal connections that encode tree branching.

Parameters:
  • n_layer (int) – Current layer index.

  • nn_in (int) – Layer output width.

  • nn_out (int) – Layer input width.

  • num_layers (int) – Number of network layers.

  • node (dict) – Per-node tree metadata.

  • djinn_weights (dict) – Layer weight matrices.

  • neurons_layer (list[numpy.ndarray]) – New neuron indices per layer.

Returns:

Updated layer weight matrices.

Return type:

dict

djinn.random_forest.process_split_node(djinn_weights, node, nodes, i, k, kk, neurons_layer, nn_in, nn_out, num_layers)[source]

Process one split node and update mapped weight connections.

Parameters:
  • djinn_weights (dict) – Layer weight matrices to modify in-place.

  • node (dict) – Node metadata dictionary.

  • nodes (int) – Current node index.

  • i (int) – Current network layer index.

  • k (int) – Outgoing neuron counter.

  • kk (int) – Incoming neuron counter.

  • neurons_layer (list) – New neuron indices for each layer.

  • nn_in (int) – Layer output width for initialization scaling.

  • nn_out (int) – Layer input width for initialization scaling.

  • num_layers (int) – Total number of network layers.

Returns:

Updated counters (k, kk).

Return type:

tuple[int, int]

djinn.random_forest.train_forest(X, Y, n_trees, max_depth, xscale, yscale, regression, seed=None)[source]

Train a RandomForestRegressor on scaled data and return the fitted estimator.

Parameters:
  • X (ndarray) – Raw input feature matrix of shape (n_samples, n_features).

  • Y (ndarray) – Raw target array of shape (n_samples,) or (n_samples, n_outputs).

  • n_trees (int) – Number of trees in the forest.

  • max_depth (int) – Maximum depth of each decision tree.

  • xscale (MinMaxScaler) – Fitted input scaler used to transform X before fitting.

  • yscale (MinMaxScaler or None) – Fitted output scaler used to transform Y before fitting. Pass None for classification.

  • regression (bool) – Whether the task is regression.

  • seed (int or None, optional) – Random seed for reproducibility.

Raises:

Exception – If the first tree in the forest has depth less than or equal to 1, indicating the data is too simple to build a meaningful tree.

Returns:

Fitted sklearn forest estimator.

Return type:

RandomForestRegressor

djinn.random_forest.tree_to_nn_weights(regression, X, Y, num_trees, rfr, seed=None)[source]

Map every tree in an ensemble to DJINN architecture and weights.

Parameters:
  • regression (bool) – Whether the task is regression.

  • X (numpy.ndarray) – Input features.

  • Y (numpy.ndarray) – Target values.

  • num_trees (int) – Number of trees to map.

  • rfr (object) – Fitted sklearn forest-like estimator containing estimators_.

  • seed (int or None, default=None) – Random seed used for deterministic initialization.

Returns:

Dictionary with global dimensions and per-tree network shape, weights, and bias placeholders.

Return type:

dict

djinn.random_forest.xavier_init(nin, nout)[source]

Return a Xavier-initialized scalar weight.

Parameters:
  • nin (int) – Input dimension of the layer.

  • nout (int) – Output dimension of the layer.

Returns:

Randomly initialized weight value.

Return type:

float

djinn.neural_network

PyTorch training, evaluation, and persistence utilities for DJINN models.

class djinn.neural_network.BatchLoader(x, y, batch_size, generator)[source]

Minibatches of rows drawn with replacement.

Gives the same batches as a DataLoader with a RandomSampler (replacement=True), but indexes the tensors directly instead of collating one row at a time, which was most of the training time.

class djinn.neural_network.MultiLayerPerceptron(weights, biases, dropout_keep_prob)[source]

Feed-forward network initialized from DJINN tree-mapped weights.

Notes

Hidden layers and output layer are rebuilt from per-layer weight and bias dictionaries produced by DJINN tree-to-network mapping.

forward(x)[source]

Run a forward pass.

Parameters:

x (torch.Tensor) – Input minibatch tensor.

Returns:

Output tensor after hidden and output layers.

Return type:

torch.Tensor

class djinn.neural_network.NumpyEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

JSON encoder that serializes NumPy arrays as Python lists.

default(obj)[source]

Convert NumPy arrays to lists; delegate all other types to super.

Parameters:

obj (object) – The object to serialize.

Returns:

A Python list if obj is an ndarray; otherwise the result of the parent encoder’s default method.

Return type:

list or default

class djinn.neural_network.StackedAdam(params, lr, weight_decay=0.0, eps=1e-08, betas=(0.9, 0.999))[source]

Adam for stacked networks, with a learning rate per network.

Follows torch.optim.Adam (L2 weight_decay added to the gradient). Each network’s update only depends on its own slice, so this is the same as running a separate Adam for every network.

step()[source]

Update every parameter once.

zero_grad()[source]

Clear the gradients.

djinn.neural_network.build_tree_weights_and_biases(ttn, key, seed=None, tree_idx=0)[source]

Construct per-layer weights and random biases from mapped tree data.

Parameters:
  • ttn (dict) – Output from tree-to-network mapping.

  • key (str) – Tree key (for example tree_0).

  • seed (int or None, optional) – Base random seed. Combined with tree_idx so each tree in the ensemble gets a distinct but reproducible bias initialisation, regardless of how much numpy random state was consumed beforehand.

  • tree_idx (int, optional) – Zero-based index of the tree, used to derive a per-tree seed.

Returns:

(weights, biases) dictionaries keyed by h1..hN and out.

Return type:

tuple[dict, dict]

djinn.neural_network.draw_rows(n, n_samples, generator)[source]

Draw n_samples row indices from range(n) with replacement.

Uses the same calls as RandomSampler(replacement=True), in chunks of 32, so a seeded generator gives the same rows as before.

djinn.neural_network.evaluate(model, x, y, criterion)[source]

Evaluate a model on a fixed dataset without gradient tracking.

Parameters:
  • model (nn.Module) – Model to evaluate.

  • x (torch.Tensor) – Input features for evaluation.

  • y (torch.Tensor) – Targets corresponding to x.

  • criterion (callable) – Loss function used to score predictions.

Returns:

Scalar loss value on the provided dataset.

Return type:

float

djinn.neural_network.find_optimal_epochs(regression, weights, biases, xtrain, ytrain, dropout_keep_prob, lr, batch_size, weight_decay=0.0, max_training_epochs=3000, device=None)[source]

Estimate epochs-to-convergence for fixed hyperparameters.

Parameters:
  • regression (bool) – True for regression, False for classification.

  • weights (dict) – Initial per-layer weights.

  • biases (dict) – Initial per-layer biases.

  • xtrain (ndarray or torch.Tensor) – Training features.

  • ytrain (ndarray or torch.Tensor) – Training labels/targets.

  • dropout_keep_prob (float) – Hidden-layer dropout keep probability.

  • lr (float) – Learning rate.

  • batch_size (int) – Mini-batch size.

  • weight_decay (float, optional) – L2 regularization strength.

  • max_training_epochs (int, optional) – Upper bound on epochs.

  • device (torch.device, str, or None, optional) – Compute device.

Returns:

Estimated number of training epochs.

Return type:

int

djinn.neural_network.get_hyperparams(regression, ttn, xscale, yscale, x, y, dropout_keep_prob, weight_decay, seed, device=None, verbose=True)[source]

Automatically select DJINN hyperparameters for a mapped tree network.

Parameters:
  • regression (bool) – Whether the task is regression or classification.

  • ttn (dict) – Dictionary returned by tree-to-network mapping.

  • xscale (object) – Input scaler.

  • yscale (object) – Output scaler.

  • x (ndarray) – Input features.

  • y (ndarray) – Output features.

  • dropout_keep_prob (float) – Probability of keeping a hidden unit active during dropout.

  • weight_decay (float) – Multiplier for L2 penalty on weights.

  • seed (int) – Random seed used in preprocessing/splitting.

  • device (torch.device or None, optional) – Compute device.

  • verbose (bool, optional) – Print progress and the selected values.

Returns:

(batch_size, learning_rate, epochs).

Return type:

tuple[int, float, int]

djinn.neural_network.get_learning_rate(regression, weights, biases, xtrain, ytrain, dropout_keep_prob, batch_size, weight_decay=0.0, device=None)[source]

Search for an effective learning rate using two refinement passes.

Parameters:
  • regression (bool) – True for regression, False for classification.

  • weights (dict) – Initial per-layer weights.

  • biases (dict) – Initial per-layer biases.

  • xtrain (ndarray or torch.Tensor) – Training features.

  • ytrain (ndarray or torch.Tensor) – Training labels/targets.

  • dropout_keep_prob (float) – Hidden-layer dropout keep probability.

  • batch_size (int) – Mini-batch size.

  • weight_decay (float, optional) – L2 regularization strength.

  • device (torch.device, str, or None, optional) – Compute device.

Returns:

Selected learning rate.

Return type:

float

djinn.neural_network.get_min_max(x, y, n_classes)[source]

Compute per-dimension minimum and maximum values for inputs and outputs.

Parameters:
  • x (ndarray) – Input feature matrix.

  • y (ndarray) – Output targets.

  • n_classes (int) – Number of output targets/classes.

Returns:

Tuple (input_minmax, output_minmax) where each element is [min_values, max_values].

Return type:

tuple[list[numpy.ndarray], list[numpy.ndarray]]

djinn.neural_network.get_unique_model_name(model_path)[source]

Create a unique model directory path by appending a numeric suffix.

Parameters:

model_path (str or pathlib.Path) – Desired base path for model output directory.

Returns:

Newly created unique directory path.

Return type:

pathlib.Path

djinn.neural_network.get_weights_and_biases(model)[source]

Extract dense layer weights and biases from a trained model.

Parameters:

model (nn.Module) – Model whose parameters are extracted.

Returns:

Tuple (dense_weights, dense_biases) in model parameter order.

Return type:

tuple[list[numpy.ndarray], list[numpy.ndarray]]

djinn.neural_network.load_tree_data(xscale, yscale, x, y, regression, batch_size, device)[source]

Scale training data and build a retraining dataloader.

Parameters:
  • xscale (object) – Fitted scaler used to transform input features.

  • yscale (object) – Fitted scaler used to transform regression targets.

  • x (ndarray) – Input feature matrix.

  • y (ndarray) – Training targets.

  • regression (bool) – Whether the task is regression or classification.

  • batch_size (int) – Mini-batch size.

  • device (torch.device) – Device where tensors are materialized.

Returns:

Shuffled dataloader for retraining.

Return type:

BatchLoader

djinn.neural_network.load_tree_model(checkpoint_path, device, dropout_keep_prob, tree_idx, verbose=True)[source]

Restore a saved tree checkpoint as a PyTorch model.

Parameters:
  • checkpoint_path (str or pathlib.Path) – Path to the tree_*.pt checkpoint.

  • device (torch.device) – Device used to load tensors and construct the model.

  • dropout_keep_prob (float) – Keep probability used when rebuilding dropout layers.

  • tree_idx (int) – Zero-based tree index for logging.

  • verbose (bool, optional) – Print a message once the tree is restored.

Returns:

Tuple of (model, network_shape) restored from checkpoint.

Return type:

tuple[nn.Module, dict]

djinn.neural_network.prepare_dataloader(xtrain, ytrain, regression, batch_size, device, seed=None)[source]

Create a minibatch dataloader for regression or classification.

Matches the original TensorFlow DJINN: each epoch draws len(xtrain) // batch_size full batches of rows sampled with replacement, rather than a shuffled pass over every row. On the diabetes benchmark this is worth about +0.02 R² over a shuffled pass.

Parameters:
  • xtrain (ndarray or torch.Tensor) – Training features.

  • ytrain (ndarray or torch.Tensor) – Training targets.

  • regression (bool) – True for regression, False for classification.

  • batch_size (int) – Mini-batch size.

  • device (torch.device) – Device where tensors are materialized.

  • seed (int or None, optional) – Seed for the sampling generator.

Returns:

Training dataloader.

Return type:

BatchLoader

djinn.neural_network.resolve_device(device)[source]

Return device as a torch.device.

"auto" (or None) picks CUDA if it is available, then Apple’s MPS, then the CPU.

djinn.neural_network.save_experiment_metadata(model_dir, config, history)[source]

Save run configuration and loss history metadata.

Parameters:
  • model_dir (pathlib.Path) – Directory where metadata files are written.

  • config (dict) – Experiment settings used for training.

  • history (dict) – Training/validation history arrays.

djinn.neural_network.save_tree_model(model, tree_idx, ttn, model_dir)[source]

Persist one trained tree-model checkpoint to disk.

Parameters:
  • model (nn.Module) – Trained model to serialize.

  • tree_idx (int) – Zero-based index of the tree in the ensemble.

  • ttn (dict) – Tree-to-network mapping dictionary containing network_shape.

  • model_dir (pathlib.Path) – Directory where the checkpoint is written.

djinn.neural_network.scale_data(x, y, xscale, yscale, regression, seed, n_classes, test=False)[source]

Scale data and split into a training subset.

Parameters:
  • x (ndarray) – Input feature matrix.

  • y (ndarray) – Output target array.

  • xscale (object) – Fitted scaler used to transform x.

  • yscale (object) – Fitted scaler used to transform y for regression.

  • regression (bool) – Whether the task is regression or classification.

  • seed (int) – Random seed used for train_test_split.

  • n_classes (int) – Number of output classes/targets.

Returns:

Scaled (xtrain, ytrain) tensors.

Return type:

tuple[torch.Tensor, torch.Tensor]

djinn.neural_network.stack_networks(weights_list, biases_list, device)[source]

Zero-pad networks with the same number of layers and stack them.

The padded neurons have no inputs, outputs or bias, so their gradients are zero and they stay zero during training.

Parameters:
Returns:

Layer keys, weights of shape (n_nets, n_in, n_out) and biases of shape (n_nets, 1, n_out).

Return type:

tuple[list[str], list[torch.Tensor], list[torch.Tensor]]

djinn.neural_network.stacked_forward(stacked_w, stacked_b, x, dropout_p=0.0)[source]

Forward pass of stacked networks, like MultiLayerPerceptron.

x has shape (n_nets, n_rows, n_features). Dropout is applied after the second and later hidden layers when dropout_p > 0.

djinn.neural_network.stacked_loss(outputs, targets, regression)[source]

Mean loss of each network, shape (n_nets,).

Targets are floats of shape (n_nets, n_rows, n_out) for regression and class indices of shape (n_nets, n_rows) for classification.

djinn.neural_network.torch_continue_training(regression, xscale, yscale, x, y, ntrees, lr, n_epochs, batch_size, dropout_keep_prob, model_dir, model_name=None, weight_decay=0.0, seed=None, device=None, verbose=True)[source]

Continue training previously saved DJINN PyTorch models.

Parameters:
  • regression (bool) – Regression or classification task.

  • xscale (fitted scaler) – Input scaler.

  • yscale (fitted scaler) – Output scaler (regression only).

  • x (ndarray) – Training inputs.

  • y (ndarray) – Training targets.

  • ntrees (int) – Number of tree models in ensemble.

  • lr (float) – Learning rate.

  • n_epochs (int) – Additional epochs to train.

  • batch_size (int) – Mini-batch size.

  • dropout_keep_prob (float) – Keep probability for dropout.

  • model_dir (str or Path) – Directory containing saved tree_*.pt models.

  • model_name (str or None) – Optional model name used when writing retraining metadata file.

  • weight_decay (float) – L2 regularization.

  • seed (int or None) – Random seed.

  • device (torch.device, str, or None) – Device to train on.

  • verbose (bool, optional) – Print progress for each tree.

Returns:

Re-saves tree checkpoints and writes retraining metadata.

Return type:

None

djinn.neural_network.torch_dropout_regression(regression, ttn, xscale, yscale, x, y, ntrees, lr, n_epochs, batch_size, dropout_keep_prob, weight_decay, **kwargs)[source]

Train DJINN tree-initialized neural networks with PyTorch dropout.

Parameters:
  • regression (bool) – Whether the task is regression or classification.

  • ttn (dict) – Dictionary returned from tree-to-network mapping.

  • xscale (object) – Fitted scaler used to transform input features.

  • yscale (object) – Fitted scaler used to transform targets for regression.

  • x (ndarray) – Input features.

  • y (ndarray) – Output targets.

  • ntrees (int) – Number of tree-mapped networks to train.

  • lr (float) – Adam learning rate.

  • n_epochs (int) – Number of training epochs.

  • batch_size (int) – Mini-batch size.

  • dropout_keep_prob (float) – Probability of keeping hidden units active during dropout.

  • weight_decay (float) – L2 regularization strength for optimizer updates.

  • **kwargs (dict) – Optional keyword arguments including save_model, save_files, model_path, device, and seed.

Returns:

Trained network information including initial/final weights and biases, input/output min-max values, and train/validation loss history.

Return type:

dict

djinn.neural_network.train_model(model, loader, regression, lr, weight_decay, epochs=100, early_stop_patience=None)[source]

Train a model and return epoch losses.

Parameters:
  • model (nn.Module) – Model to optimize.

  • loader (BatchLoader) – Training batches.

  • regression (bool) – True for regression (MSE), False for classification.

  • lr (float) – Adam learning rate.

  • weight_decay (float) – L2 regularization strength for kernel weights.

  • epochs (int, optional) – Maximum number of epochs.

  • early_stop_patience (int or None, optional) – Optional early-stop patience.

Returns:

Mean training loss per epoch.

Return type:

list[float]

djinn.neural_network.train_one_epoch(model, loader, criterion, optimizer)[source]

Run one optimization epoch over the training loader.

Parameters:
  • model (nn.Module) – Model to train.

  • loader (BatchLoader) – Mini-batch dataloader for training data.

  • criterion (callable) – Loss function used to compute training loss.

  • optimizer (torch.optim.Optimizer) – Optimizer used to update model parameters.

Returns:

Mean loss across all mini-batches in the epoch.

Return type:

float

djinn.neural_network.train_single_tree(model, loader, criterion, optimizer, xtest, ytest, epochs, eval_every=1)[source]

Train a single tree-mapped network and track train/validation losses.

Parameters:
  • model (nn.Module) – Network initialized from one mapped tree.

  • loader (BatchLoader) – Training dataloader.

  • criterion (callable) – Loss function used for training and validation.

  • optimizer (torch.optim.Optimizer) – Optimizer used during training.

  • xtest (torch.Tensor) – Validation input features.

  • ytest (torch.Tensor) – Validation targets.

  • epochs (int) – Number of training epochs.

  • eval_every (int, optional) – Evaluate the full validation set every this many epochs (default 1). Values > 1 skip intermediate evaluations, reusing the last computed val loss, which substantially reduces overhead for large epoch counts.

Returns:

Tuple (model, train_history, valid_history) where histories hold per-epoch loss values.

Return type:

tuple[nn.Module, list[float], list[float]]

djinn.neural_network.train_stacked(stacked_w, stacked_b, xtrain, ytrain, regression, generators, batch_size, epochs, optimizer, dropout_p=0.0, xval=None, yval=None, eval_every=1)[source]

Train stacked networks together, each on its own minibatches.

Parameters:
  • stacked_w (list[torch.Tensor]) – Parameters from stack_networks(), updated in place.

  • stacked_b (list[torch.Tensor]) – Parameters from stack_networks(), updated in place.

  • xtrain (torch.Tensor) – Training features, shape (n_rows, n_features).

  • ytrain (torch.Tensor) – Float targets of shape (n_rows, n_out) for regression, class indices of shape (n_rows,) for classification.

  • regression (bool) – True for regression (MSE), False for classification.

  • generators (list[torch.Generator]) – One generator per network for drawing its minibatches.

  • batch_size (int) – Mini-batch size.

  • epochs (int) – Number of epochs.

  • optimizer (StackedAdam) – Optimizer for the stacked parameters.

  • dropout_p (float, optional) – Dropout probability.

  • xval (torch.Tensor or None, optional) – Validation data, same layout as the training data.

  • yval (torch.Tensor or None, optional) – Validation data, same layout as the training data.

  • eval_every (int, optional) – Evaluate the validation set every this many epochs.

Returns:

Training and validation loss, shape (n_nets, epochs).

Return type:

tuple[ndarray, ndarray or None]

djinn.neural_network.unstack_network(keys, stacked_w, stacked_b, idx, shapes)[source]

Return network idx from a stack as weight and bias dicts.