Documentation
¶
Overview ¶
Package treeboost provides a general-purpose, high-performance Gradient Boosted Decision Trees (GBDT) and multi-algorithm ensemble regression library in pure Go with AVX2 SIMD acceleration.
Theoretical Background & Inspiration: The GBDT algorithms and ensemble architectures in this package are inspired by and follow the mathematical formulations detailed in:
- Gradient Boosting: https://en.wikipedia.org/wiki/Gradient_boosting
- Symmetric Decision Trees (CatBoost): https://en.wikipedia.org/wiki/CatBoost
- Leaf-wise Decision Trees (LightGBM): https://en.wikipedia.org/wiki/LightGBM
- Extremely Randomized Trees (ExtraTrees): https://en.wikipedia.org/wiki/Random_forest#ExtraTrees
Index ¶
- Constants
- Variables
- func BuildHistogram(bins []uint8, fOffset int, weights []float64, targets []float64, indices []int, ...)
- func BuildHistogramSlice(bins []uint8, fOffset int, weights []float64, targets []float64, ...)
- func ChronologicalCV(X []FeatureVector, Y []float64, timestamps []time.Time, config EnsembleConfig, ...) (HorizonOffsets, CVMetrics, error)
- func ChronologicalCVWithOptions(X []FeatureVector, Y []float64, timestamps []time.Time, config EnsembleConfig, ...) (HorizonOffsets, CVMetrics, error)
- func ComputeSampleWeights(Y []float64) []float64
- func ComputeSampleWeightsWithConfig(Y []float64, cfg WeightConfig) []float64
- func EvaluateTree(nodes []Node, x FeatureVector) float64
- func EvaluateTreeColumnar(nodes []Node, data ColumnarDataset, sampleIdx int) float64
- func FindBestHistogramSplit(hist *FeatureHistogram, boundaries []float64, totalW, totalWY float64) (float64, float64, bool)
- func FindBestHistogramSplitWithCounts(hist *FeatureHistogram, boundaries []float64, totalW, totalWY float64, ...) (splitVal float64, score float64, leftW float64, leftWY float64, rightW float64, ...)
- func HorizonBinForLeadTime(leadHours float64) int
- func HorizonBinForLeadTimeWithBins(leadHours float64, bins []string) int
- func PinballLoss(yTrue, yPred, weights []float64, q float64) float64
- func ScaleTreeLeavesInPlace(tree *Tree, factor float64)
- func WeightedQuantile(values []float64, weights []float64, q float64) float64
- type BinnedDataset
- type CVMetrics
- type CatBoostParams
- type ChronologicalCVOptions
- type ColumnarDataset
- type Dataset
- type EnsembleConfig
- type ExtraTreesParams
- type FeatureHistogram
- type FeatureVector
- type HorizonOffsets
- type LightGBMParams
- type Model
- func LoadModel(path string) (*Model, error)
- func TrainEnsemble(X []FeatureVector, Y []float64, config EnsembleConfig) *Model
- func TrainEnsembleWithWeights(X []FeatureVector, Y []float64, W []float64, config EnsembleConfig) *Model
- func TrainQuantileEnsemble(X []FeatureVector, Y []float64, quantile float64, config EnsembleConfig) *Model
- func TrainQuantileEnsembleWithWeights(X []FeatureVector, Y []float64, W []float64, quantile float64, ...) *Model
- func (m *Model) ComputeMetrics(X []FeatureVector, Y []float64)
- func (m *Model) Predict(features []float64) float64
- func (m *Model) PredictBatch(features []float64, nSamples int) []float64
- func (m *Model) PredictBatchInterval(flatFeatures []float64, leadHours []float64) (p10, p50, p90 []float64)
- func (m *Model) PredictInterval(features []float64, leadHours float64) (p10, p50, p90 float64)
- func (m *Model) SaveModel(path string) error
- func (m *Model) Validate() error
- type Node
- type Regressor
- type TrainWorkspace
- type Tree
- func ScaleTreeLeaves(tree Tree, factor float64) Tree
- func TrainExtraTrees(X []FeatureVector, Y []float64, W []float64, params ExtraTreesParams) []Tree
- func TrainExtraTreesColumnar(data ColumnarDataset, params ExtraTreesParams) []Tree
- func TrainLeafwiseGBDT(X []FeatureVector, Y []float64, W []float64, params LightGBMParams) ([]Tree, float64)
- func TrainLeafwiseGBDTColumnar(data ColumnarDataset, params LightGBMParams) ([]Tree, float64)
- func TrainSymmetricGBDT(X []FeatureVector, Y []float64, W []float64, params CatBoostParams) ([]Tree, float64)
- func TrainSymmetricGBDTColumnar(data ColumnarDataset, params CatBoostParams) ([]Tree, float64)
- type WeightConfig
Constants ¶
const ( LossMSE = "mse" LossPinball = "pinball" )
Supported loss function identifier constants.
const DefaultMaxLeafValue = 1e4
DefaultMaxLeafValue defines the default ceiling on individual tree leaf predictions (1e4).
const DefaultMaxValidPrediction = 1e6
DefaultMaxValidPrediction defines the default ceiling on valid out-of-fold predictions (1e6).
Variables ¶
var DefaultHorizonBins = []string{"0-6h", "6-12h", "12-24h", "24-36h", "36-48h", ">48h"}
Standard 6 horizon bin names
var ExtendedHorizonBins = []string{"0-6h", "6-12h", "12-24h", "24-36h", "36-48h", "48-96h", "96-168h", ">168h"}
Extended 8 horizon bin names for medium-term / multi-week forecasts
Functions ¶
func BuildHistogram ¶
func BuildHistogram(bins []uint8, fOffset int, weights []float64, targets []float64, indices []int, hist *FeatureHistogram)
BuildHistogram accumulates sample weights and targets into a FeatureHistogram.
func BuildHistogramSlice ¶
func BuildHistogramSlice(bins []uint8, fOffset int, weights []float64, targets []float64, sampleIdxs []int, start, end int, hist *FeatureHistogram)
BuildHistogramSlice accumulates sample weights and targets over sampleIdxs[start:end] without slice allocations.
func ChronologicalCV ¶ added in v0.2.0
func ChronologicalCV( X []FeatureVector, Y []float64, timestamps []time.Time, config EnsembleConfig, numFolds int, leadTimeFeatureIndex int, ) (HorizonOffsets, CVMetrics, error)
ChronologicalCV performs numFolds forward-chaining rolling-origin cross-validation on chronological data. In split k, it trains on folds 0..k-1 and validates on fold k using simulated forecast origin (timestamps[trainEnd-1]). It extracts empirical 10th and 90th percentile residuals per horizon bin, enforces monotonic expansion (uncertainty band widens as horizon increases), and returns the offsets and overall CV metrics.
func ChronologicalCVWithOptions ¶ added in v0.3.0
func ChronologicalCVWithOptions( X []FeatureVector, Y []float64, timestamps []time.Time, config EnsembleConfig, opts ChronologicalCVOptions, ) (HorizonOffsets, CVMetrics, error)
ChronologicalCVWithOptions performs forward-chaining rolling-origin cross-validation with custom options.
func ComputeSampleWeights ¶
ComputeSampleWeights calculates weights for observations using default log-distance from target mean, emphasizing and penalizing extreme spikes/troughs.
func ComputeSampleWeightsWithConfig ¶ added in v0.2.0
func ComputeSampleWeightsWithConfig(Y []float64, cfg WeightConfig) []float64
ComputeSampleWeightsWithConfig calculates weights for observations using a log-distance from the target mean according to the provided WeightConfig. If y < 0, the weight is scaled by cfg.NegativeMultiplier.
func EvaluateTree ¶
func EvaluateTree(nodes []Node, x FeatureVector) float64
EvaluateTree traverses a slice of decision tree nodes from root (node index 0) down to a leaf node for the given feature vector x, returning the leaf's prediction value.
func EvaluateTreeColumnar ¶
func EvaluateTreeColumnar(nodes []Node, data ColumnarDataset, sampleIdx int) float64
EvaluateTreeColumnar evaluates a tree on sampleIdx within ColumnarDataset without allocations.
func FindBestHistogramSplit ¶
func FindBestHistogramSplit(hist *FeatureHistogram, boundaries []float64, totalW, totalWY float64) (float64, float64, bool)
FindBestHistogramSplit scans accumulated feature histogram bins to find the split threshold minimizing variance (maximizing gain).
func FindBestHistogramSplitWithCounts ¶
func FindBestHistogramSplitWithCounts(hist *FeatureHistogram, boundaries []float64, totalW, totalWY float64, totalCount int, minChildSamples int) (splitVal float64, score float64, leftW float64, leftWY float64, rightW float64, rightWY float64, found bool)
FindBestHistogramSplitWithCounts evaluates the optimal split threshold and partition metrics directly from histogram bins.
func HorizonBinForLeadTime ¶ added in v0.2.0
HorizonBinForLeadTime returns the 0-indexed bin (0 to 5) for a given lead time in hours. Boundaries: [0, 6), [6, 12), [12, 24), [24, 36), [36, 48), [48, inf).
func HorizonBinForLeadTimeWithBins ¶ added in v0.3.0
HorizonBinForLeadTimeWithBins returns the 0-indexed bin for a given lead time in hours according to the supplied slice of horizon bin names. If bins is nil or empty, DefaultHorizonBins is used.
func PinballLoss ¶ added in v0.5.0
PinballLoss evaluates the weighted mean pinball (quantile/check) loss:
L_q(y, y_hat) = w * max(q * (y - y_hat), (q - 1) * (y - y_hat))
Returns 0.0 if datasets are empty, length mismatched, or total valid weight is non-positive.
func ScaleTreeLeavesInPlace ¶
ScaleTreeLeavesInPlace scales tree leaf values in place without allocating a new slice.
func WeightedQuantile ¶ added in v0.5.0
WeightedQuantile computes the weighted q-quantile of values with corresponding sample weights. If weights is nil or empty, all weights default to 1.0 (uniform weighting). Target quantile q is clamped to [0.0, 1.0]. If q is NaN, it returns 0.0. Non-finite values (NaN, +/-Inf) and non-positive or non-finite weights are safely filtered out.
Types ¶
type BinnedDataset ¶
type BinnedDataset struct {
NumSamples int
NumFeatures int
MaxBins int
Bins []uint8 // Size (NumFeatures * NumSamples)
BinBoundaries [][]float64 // Bin upper bound thresholds per feature [NumFeatures][]float64
BinCounts []int // Actual number of bins created per feature [NumFeatures]int
}
BinnedDataset represents a tabular dataset whose continuous features are quantized into discrete 8-bit bin IDs (0..maxBins-1) for fast histogram-based GBDT tree building.
func QuantizeDataset ¶
func QuantizeDataset(data ColumnarDataset, maxBins int) BinnedDataset
QuantizeDataset builds a BinnedDataset from a ColumnarDataset using equal-frequency quantile binning.
type CVMetrics ¶ added in v0.2.0
type CVMetrics struct {
ValidationMAE float64 `json:"validation_mae"`
ValidationRMSE float64 `json:"validation_rmse"`
RSquared float64 `json:"r_squared"`
ValidationSamples int `json:"validation_samples,omitempty"`
}
CVMetrics holds aggregated out-of-fold cross-validation performance metrics.
type CatBoostParams ¶
type CatBoostParams struct {
Depth int `json:"depth"`
Iterations int `json:"iterations"`
LearningRate float64 `json:"learning_rate"`
L2LeafReg float64 `json:"l2_leaf_reg"`
MaxLeafValue float64 `json:"max_leaf_value,omitempty"`
LossFunction string `json:"loss_function,omitempty"`
Quantile float64 `json:"quantile,omitempty"`
}
CatBoostParams holds hyperparameters for Symmetric GBDT (obliviated trees). Reference: https://en.wikipedia.org/wiki/CatBoost
type ChronologicalCVOptions ¶ added in v0.3.0
type ChronologicalCVOptions struct {
NumFolds int
LeadTimeFeatureIndex int // Feature index where (slotTime - originTime)/24h is injected, or -1 to skip
MaxLeadHours float64 // Max forward horizon in hours to evaluate (<= 0.0 means unlimited)
InferenceOverrides map[int]float64 // Map of feature index -> constant value to override at validation time
HorizonBins []string // Optional custom horizon bin names (defaults to DefaultHorizonBins if nil/empty)
SampleWeightsConfig *WeightConfig // Optional sample weight config for fold training (nil uses DefaultWeightConfig)
MaxValidPrediction float64 // Max valid prediction value (defaults to 1e6 when unset or <= 0.0)
}
ChronologicalCVOptions configures chronological rolling-origin cross-validation.
type ColumnarDataset ¶
type ColumnarDataset struct {
NumSamples int
NumFeatures int
Features []float64 // Size (NumFeatures * NumSamples)
Targets []float64 // Size NumSamples
Weights []float64 // Size NumSamples
Binned BinnedDataset
}
ColumnarDataset holds dataset features in a flattened Structure of Arrays (SoA) layout. Feature f for sample i is accessed at index f * NumSamples + i.
func ToColumnar ¶
func ToColumnar(X []FeatureVector, Y []float64, W []float64) ColumnarDataset
ToColumnar converts legacy AoS feature vectors ([]FeatureVector) into flattened SoA ColumnarDataset.
type Dataset ¶
type Dataset struct {
X []FeatureVector
Y []float64
W []float64
}
Dataset represents a tabular dataset of feature vectors, target regression values, and optional sample weights.
type EnsembleConfig ¶
type EnsembleConfig struct {
MaxLeafValue float64 `json:"max_leaf_value,omitempty"`
CatBoostWeight float64 `json:"catboost_weight"`
LightGBMWeight float64 `json:"lightgbm_weight"`
ExtraTreesWeight float64 `json:"extratrees_weight"`
LossFunction string `json:"loss_function,omitempty"`
Quantile float64 `json:"quantile,omitempty"`
CatBoost CatBoostParams `json:"catboost"`
LightGBM LightGBMParams `json:"lightgbm"`
ExtraTrees ExtraTreesParams `json:"extratrees"`
}
EnsembleConfig specifies individual algorithm parameters and weighted contribution ratios.
func DefaultEnsembleConfig ¶
func DefaultEnsembleConfig() EnsembleConfig
DefaultEnsembleConfig returns a balanced, standard default configuration combining Symmetric GBDT, Leaf-wise GBDT, and ExtraTrees into an equal-weight ensemble.
func DefaultQuantileEnsembleConfig ¶ added in v0.5.0
func DefaultQuantileEnsembleConfig(quantile float64) EnsembleConfig
DefaultQuantileEnsembleConfig returns an ensemble configuration optimized for quantile regression, setting CatBoostWeight: 0.5, LightGBMWeight: 0.5, ExtraTreesWeight: 0.0, and ExtraTrees.Estimators: 0.
type ExtraTreesParams ¶
type ExtraTreesParams struct {
Estimators int `json:"estimators"`
MinSamplesLeaf int `json:"min_samples_leaf"`
MaxFeatures float64 `json:"max_features"`
MaxLeafValue float64 `json:"max_leaf_value,omitempty"`
LossFunction string `json:"loss_function,omitempty"`
Quantile float64 `json:"quantile,omitempty"`
}
ExtraTreesParams holds hyperparameters for Extremely Randomized Trees. Reference: https://en.wikipedia.org/wiki/Random_forest#ExtraTrees
type FeatureHistogram ¶
FeatureHistogram holds accumulated count, weight, and weighted target sums across 256 discrete bins.
func (*FeatureHistogram) Reset ¶
func (h *FeatureHistogram) Reset()
Reset zeroes out histogram accumulators.
type FeatureVector ¶
type FeatureVector struct {
Values []float64
}
FeatureVector represents an n-dimensional sample observation vector of floating-point features.
type HorizonOffsets ¶ added in v0.2.0
HorizonOffsets holds empirical residual quantiles partitioned across horizon bins.
type LightGBMParams ¶
type LightGBMParams struct {
MaxDepth int `json:"max_depth"`
MaxLeaves int `json:"max_leaves"`
MinChildSamples int `json:"min_child_samples"`
Estimators int `json:"estimators"`
LearningRate float64 `json:"learning_rate"`
L2LeafReg float64 `json:"l2_leaf_reg"` // L2 leaf regularization parameter (lambda >= 0.0)
MaxLeafValue float64 `json:"max_leaf_value,omitempty"`
LossFunction string `json:"loss_function,omitempty"`
Quantile float64 `json:"quantile,omitempty"`
}
LightGBMParams holds hyperparameters for Leaf-wise GBDT (best-first tree growth). Reference: https://en.wikipedia.org/wiki/LightGBM
type Model ¶
type Model struct {
ID int `json:"-"`
TrainedAt time.Time `json:"trained_at"`
TrainingStart time.Time `json:"training_start"`
TrainingEnd time.Time `json:"training_end"`
BaseValue float64 `json:"base_value"`
Trees []Tree `json:"trees"`
LearningRate float64 `json:"learning_rate"`
MAE float64 `json:"mae"`
RMSE float64 `json:"rmse"`
RSquared float64 `json:"r_squared"`
HorizonBins []string `json:"horizon_bins,omitempty"`
P10Offsets []float64 `json:"p10_offsets,omitempty"`
P90Offsets []float64 `json:"p90_offsets,omitempty"`
LossFunction string `json:"loss_function,omitempty"`
Quantile float64 `json:"quantile,omitempty"`
PinballLoss float64 `json:"pinball_loss,omitempty"`
DiagnosticsJSON string `json:"diagnostics_json,omitempty"`
}
Model represents a trained ensemble model comprising decision trees, a base initial prediction value, learning rate, and evaluation / diagnostic metadata.
func LoadModel ¶
LoadModel loads a serialized GBDT model from a JSON file and validates its integrity.
func TrainEnsemble ¶
func TrainEnsemble(X []FeatureVector, Y []float64, config EnsembleConfig) *Model
TrainEnsemble trains a multi-algorithm tree ensemble combining CatBoost, LightGBM, and ExtraTrees models.
func TrainEnsembleWithWeights ¶ added in v0.2.0
func TrainEnsembleWithWeights(X []FeatureVector, Y []float64, W []float64, config EnsembleConfig) *Model
TrainEnsembleWithWeights trains a multi-algorithm tree ensemble (CatBoost, LightGBM, ExtraTrees) using explicit sample weights W.
func TrainQuantileEnsemble ¶ added in v0.5.0
func TrainQuantileEnsemble(X []FeatureVector, Y []float64, quantile float64, config EnsembleConfig) *Model
TrainQuantileEnsemble trains a multi-algorithm quantile regression ensemble for target quantile defaulting to uniform sample weights (w_i = 1.0).
func TrainQuantileEnsembleWithWeights ¶ added in v0.5.0
func TrainQuantileEnsembleWithWeights(X []FeatureVector, Y []float64, W []float64, quantile float64, config EnsembleConfig) *Model
TrainQuantileEnsembleWithWeights trains a multi-algorithm quantile regression ensemble for target quantile using explicit sample weights W.
func (*Model) ComputeMetrics ¶
func (m *Model) ComputeMetrics(X []FeatureVector, Y []float64)
ComputeMetrics evaluates MAE, RMSE, and R^2 of the Model on feature vectors X and targets Y, updating the model's MAE, RMSE, and RSquared fields.
func (*Model) Predict ¶
Predict evaluates the GBDT model on a slice of feature values and returns the predicted scalar result. It initializes with the BaseValue and adds the weighted leaf prediction from each decision tree in the ensemble.
func (*Model) PredictBatch ¶
PredictBatch evaluates the GBDT model on a batch of nSamples feature vectors. features is a flattened slice of length (nSamples * nFeatures) in row-major layout (where sample i feature f is at index i*nFeatures + f). Returns a slice of predicted values of length nSamples.
func (*Model) PredictBatchInterval ¶ added in v0.2.0
func (m *Model) PredictBatchInterval(flatFeatures []float64, leadHours []float64) (p10, p50, p90 []float64)
PredictBatchInterval evaluates batch feature vectors with corresponding lead times.
func (*Model) PredictInterval ¶ added in v0.2.0
PredictInterval evaluates the model and applies empirical horizon residual offsets, returning (P10, P50, P90). Unconditionally guarantees P10 <= P50 <= P90 under all conditions (including negative targets) by clamping raw offsets.
type Node ¶
type Node struct {
NodeID int `json:"node_id"`
SplitFeature int `json:"split_feature"` // -1 if leaf node; feature index 0..N-1 otherwise
SplitValue float64 `json:"split_value"`
LeafValue float64 `json:"leaf_value"`
LeftChild int `json:"left_child"`
RightChild int `json:"right_child"`
}
Node represents a single decision node or leaf node within a decision tree.
type Regressor ¶
Regressor defines the common interface for models capable of generating continuous scalar predictions.
type TrainWorkspace ¶
type TrainWorkspace struct {
SampleIdxs []int
PermBuf []int
SplitBuf []float64
Ranges []nodeRange
Hist FeatureHistogram
QuantileScratch []int
}
TrainWorkspace holds reusable slice buffers to eliminate heap allocations during tree construction.
type Tree ¶
type Tree struct {
Nodes []Node `json:"nodes"`
}
Tree represents a single decision tree composed of ordered nodes.
func ScaleTreeLeaves ¶
ScaleTreeLeaves returns a deep copy of tree with all leaf node values multiplied by factor.
func TrainExtraTrees ¶
func TrainExtraTrees(X []FeatureVector, Y []float64, W []float64, params ExtraTreesParams) []Tree
TrainExtraTrees fits an Extremely Randomized Trees (ExtraTrees) regression ensemble.
func TrainExtraTreesColumnar ¶
func TrainExtraTreesColumnar(data ColumnarDataset, params ExtraTreesParams) []Tree
TrainExtraTreesColumnar fits an ExtraTrees regression ensemble on ColumnarDataset without per-iteration conversions.
func TrainLeafwiseGBDT ¶
func TrainLeafwiseGBDT(X []FeatureVector, Y []float64, W []float64, params LightGBMParams) ([]Tree, float64)
TrainLeafwiseGBDT fits a leaf-wise (LightGBM-style) gradient boosted decision tree ensemble.
func TrainLeafwiseGBDTColumnar ¶
func TrainLeafwiseGBDTColumnar(data ColumnarDataset, params LightGBMParams) ([]Tree, float64)
TrainLeafwiseGBDTColumnar fits a leaf-wise GBDT on ColumnarDataset without per-iteration conversions.
func TrainSymmetricGBDT ¶
func TrainSymmetricGBDT(X []FeatureVector, Y []float64, W []float64, params CatBoostParams) ([]Tree, float64)
TrainSymmetricGBDT fits a symmetric (CatBoost-style) gradient boosted decision tree ensemble.
func TrainSymmetricGBDTColumnar ¶
func TrainSymmetricGBDTColumnar(data ColumnarDataset, params CatBoostParams) ([]Tree, float64)
TrainSymmetricGBDTColumnar fits a CatBoost-style GBDT on ColumnarDataset without per-iteration conversions.
type WeightConfig ¶ added in v0.2.0
type WeightConfig struct {
Multiplier float64 // default: 5.0
Offset float64 // default: 10.0
Subtrahend float64 // default: 4.0
MinWeight float64 // default: 1.0
NegativeMultiplier float64 // default: 1.0 (e.g., set to 1.5 for 1.5x plunge penalty on y < 0)
}
WeightConfig specifies parameters for sample weight computation.
func DefaultWeightConfig ¶ added in v0.2.0
func DefaultWeightConfig() WeightConfig
DefaultWeightConfig returns the default weighting parameters.