@dheuv/xgboost-wasm
v1.0.1
Published
XGBoost WebAssembly library for Node.js and Browser
Readme
@dheuv/xgboost-wasm
XGBoost WebAssembly library for Node.js and the Browser.
Features
- Full XGBoost Support: Train and predict using the state-of-the-art Gradient Boosting framework.
- Cross-Platform: Runs in modern browsers and Node.js environments.
- High Performance: Compiled with Emscripten with
-O3optimizations. - TypeScript First: Full Type definitions included.
Installation
npm install @dheuv/xgboost-wasmQuick Start (XOR Example)
import { XGBoost } from '@dheuv/xgboost-wasm';
async function run() {
// Initialize the WASM module
const xgboost = await XGBoost.create();
// Prepare data (Input features and target labels)
const data = new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]);
const labels = new Float32Array([0, 1, 1, 0]);
// Create a DMatrix
const dtrain = xgboost.createDMatrix(data, 4, 2, NaN, labels);
// Set training parameters
const params = {
'objective': 'binary:logistic',
'eval_metric': 'logloss',
'max_depth': '3',
'eta': '0.1',
'min_child_weight': '0',
'num_feature': '2' // Required in WASM raw interface
};
// Train the model
const booster = await xgboost.train(dtrain, params, 50);
// Make predictions
const dtest = xgboost.createDMatrix(data, 4, 2);
const predictions = JSON.parse(booster.predict(dtest));
console.log('Predictions:', predictions);
}
run();API Reference
XGBoost
The main entry point for the library.
static async create(overrides?: any): Promise<XGBoost>: Initializes and returns an instance of the XGBoost class.createDMatrix(data: Float32Array, nrow: number, ncol: number, missing?: number, labels?: Float32Array): DMatrix: Creates a DMatrix from a Float32Array.async train(dtrain: DMatrix, params: Record<string, string>, nround: number): Promise<Booster>: Trains a booster with the given parameters.version(): string: Returns the XGBoost version.
Booster
A trained XGBoost model.
predict(dmat: DMatrix, option?: number, ntree_limit?: number): string: Makes predictions on a DMatrix. Returns a JSON string of results.saveModel(path: string): void: Saves the model to a path (Node.js only or virtual FS).loadModel(path: string): void: Loads a model from a path.
DMatrix
Data matrix used by XGBoost.
getNumRow(): number: Returns the number of rows.getNumCol(): number: Returns the number of columns.
Build Instructions
If you want to build the library from source:
- Install Emscripten.
- Run the build script:
npm run buildLimitations
- Memory: Default initial memory is 64MB, grows automatically. Max memory is constrained by WASM limits.
- Single Threaded: This WASM build currently runs in single-threaded mode (no OpenMP).
- Stack Size: Increased to 5MB to accommodate deep trees and complex training.
License
Apache-2.0
