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(), andscore()(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 - 1hidden layers.dropout_keep_prob (float, optional) – Probability of keeping a neuron in dropout layers.
epochs (int or None, optional) – Training epochs used by
fit().Nonepicks them automatically whenlearning_rateis alsoNone, otherwise uses 1000.learning_rate (float or None, optional) – Learning rate used by
fit().Nonerunsget_hyperparameters()to choose it.batch_size (int or None, optional) – Minibatch size used by
fit().Noneuses 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.
- models_
Trained networks, keyed by tree index.
- Type:
- xscale_
Scaler fit to the training inputs.
- yscale_
Scaler fit to the training targets.
- feature_names_in_
Names of the features seen during fit. Only set when
Xhas feature names that are all strings.- Type:
ndarray of str
- nninfo_
Details from the last training run, including the loss per epoch in
train_costandvalid_cost. Not set on loaded models.- Type:
- 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_iterstimes (with dropout active) to build a predictive distribution, then returns the 25th, 50th, and 75th percentiles alongside the raw sample dictionary.- Parameters:
- Returns:
If
n_itersisNone, returns mean predictions with shape(n_test, n_outputs). Otherwise returns(lower, middle, upper, samples), where percentile arrays have shape(n_test, n_outputs)andsamplescontains 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:
- Returns:
Dictionary containing percentile summaries and stacked prediction samples under
predictionswith shape(n_iters * n_trees, n_test, n_outputs).- Return type:
- calibrate(X, y)[source]
Store the prediction errors on held-out data.
predict_interval()uses them to set the interval width.Xandymust 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 bybayesian_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 fortraining_epochsmore epochs, the checkpoints are saved in place, and the updated networks are used bypredict()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_rateisNone,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, andseedare still accepted but will be removed in 2.0. Set them in the constructor, or usetrain()andsave().
- 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(), orcontinue_training().- Parameters:
json_path (str or pathlib.Path) – Path to the
.jsonfile written bytrain().- Returns:
Restored model instance.
- Return type:
- 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:
- Raises:
Exception – If a decision tree cannot be built from the data.
- Returns:
Dictionary with keys
batch_size,learning_rate, andepochs.- Return type:
- get_params(deep=True)
Get parameters for this estimator.
- load_model(model_name, model_path)
Reload PyTorch checkpoints for a saved model.
Restores each tree’s
.ptcheckpoint from disk usingneural_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()withn_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 acoveragefraction of the calibration points fall within. If new data comes from the same distribution as the calibration data, at leastcoverageof the true values will be inside. The width is the same for every input. Callcalibrate()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
coverageis 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 withsave_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 replacemodel_pathwhen it already exists. Defaults toFalse, which raises instead of silently deleting an existing directory.
- Returns:
Saved model directory path.
- Return type:
- Raises:
RuntimeError – If there are no trained or loaded models to save.
FileExistsError – If
model_pathalready exists andoverwriteisFalse.
- 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), wheren_samples_fittedis 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:
Notes
The \(R^2\) score used when calling
scoreon a regressor usesmultioutput='uniform_average'from version 0.23 to keep consistent with default value ofr2_score(). This influences thescoremethod of all the multioutput regressors (except forMultiOutputRegressor).
- 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 usingneural_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_modelisTrue.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_everyepochs.
- 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 inbayesian_predict(), where no output scaling is applied andnp.argmaxconverts 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 - 1hidden layers.dropout_keep_prob (float, optional) – Probability of keeping a neuron in dropout layers.
epochs (int or None, optional) – Training epochs used by
fit().Nonepicks them automatically whenlearning_rateis alsoNone, otherwise uses 1000.learning_rate (float or None, optional) – Learning rate used by
fit().Nonerunsget_hyperparameters()to choose it.batch_size (int or None, optional) – Minibatch size used by
fit().Noneuses 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,)
- models_
Trained networks, keyed by tree index.
- Type:
- xscale_
Scaler fit to the training inputs.
- feature_names_in_
Names of the features seen during fit. Only set when
Xhas feature names that are all strings.- Type:
ndarray of str
- nninfo_
Details from the last training run, including the loss per epoch in
train_costandvalid_cost. Not set on loaded models.- Type:
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_iterstimes (with dropout active) to build a predictive distribution over class probabilities, then returns theargmaxof the 25th, 50th, and 75th percentiles as class labels alongside the raw sample dictionary.- Parameters:
- Returns:
If
n_itersisNone, 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 andsamplescontains 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:
- Returns:
Dictionary containing percentile summaries and stacked prediction samples under
predictionswith shape(n_iters * n_trees, n_test, n_outputs).- Return type:
- 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 bybayesian_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 fortraining_epochsmore epochs, the checkpoints are saved in place, and the updated networks are used bypredict()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_rateisNone,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, andseedare still accepted but will be removed in 2.0. Set them in the constructor, or usetrain()andsave().
- 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(), orcontinue_training().- Parameters:
json_path (str or pathlib.Path) – Path to the
.jsonfile written bytrain().- Returns:
Restored model instance.
- Return type:
- 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:
- Raises:
Exception – If a decision tree cannot be built from the data.
- Returns:
Dictionary with keys
batch_size,learning_rate, andepochs.- Return type:
- get_params(deep=True)
Get parameters for this estimator.
- load_model(model_name, model_path)
Reload PyTorch checkpoints for a saved model.
Restores each tree’s
.ptcheckpoint from disk usingneural_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()withn_iters=None(single deterministic forward pass per network) and returns theargmaxclass 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 asclasses_.- 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 withsave_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 replacemodel_pathwhen it already exists. Defaults toFalse, which raises instead of silently deleting an existing directory.
- Returns:
Saved model directory path.
- Return type:
- Raises:
RuntimeError – If there are no trained or loaded models to save.
FileExistsError – If
model_pathalready exists andoverwriteisFalse.
- 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:
- 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 usingneural_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_modelisTrue.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_everyepochs.
- 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:
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:
- 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:
- 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, andmax_depth_feature.- Return type:
- 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:
- Returns:
Updated layer weight matrices.
- Return type:
- djinn.random_forest.connect_output_layer(djinn_weights, neurons_layer, num_layers)[source]
Connect active hidden neurons to the output layer.
- 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:
- 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:
- 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_weightsin 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
yscalewhen True.
- Returns:
Fitted
(xscale, yscale).yscaleisNonefor 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:
- 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:
- djinn.random_forest.map_single_tree_to_network(tree, nin, nout)[source]
Map one fitted tree into DJINN architecture and initial weights.
- Parameters:
- Returns:
Tuple
(djinn_arch, djinn_weights).- Return type:
- 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:
- 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:
- 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
Xbefore fitting.yscale (MinMaxScaler or None) – Fitted output scaler used to transform
Ybefore fitting. PassNonefor 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:
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
DataLoaderwith aRandomSampler(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:
- 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.
- 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(L2weight_decayadded 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.
- 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_idxso 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 byh1..hNandout.- Return type:
- djinn.neural_network.draw_rows(n, n_samples, generator)[source]
Draw
n_samplesrow indices fromrange(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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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_*.ptcheckpoint.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:
- 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_sizefull 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:
- djinn.neural_network.resolve_device(device)[source]
Return
deviceas atorch.device."auto"(orNone) 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
yfor 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:
- 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:
weights_list (list[dict]) – Per-network weights and biases from
build_tree_weights_and_biases().biases_list (list[dict]) – Per-network weights and biases from
build_tree_weights_and_biases().device (torch.device) – Device for the stacked tensors.
- 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.xhas shape(n_nets, n_rows, n_features). Dropout is applied after the second and later hidden layers whendropout_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, andseed.
- Returns:
Trained network information including initial/final weights and biases, input/output min-max values, and train/validation loss history.
- Return type:
- 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:
- 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:
- 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:
- 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]