random-forest
v0.0.7
Published
Random Forest with WebAssembly and WebWorkers
Downloads
31
Maintainers
Readme
random-forest
Random forest method. Ported to JavaScript with WebAssembly. Async computation and multithreading implemented with WebWorkers (for browsers).
No tests yet. See examples in the example folder.
- Fast
- Sync/async modes
- Threads support
- CommonJS module
Install
npm install -S random-forestSync mode
Init
const { RandomForestClassifier, RandomForestRegressor } = require('random-forest')
const rf = new RandomForestClassifier({
nEstimators: 100,
maxDepth: 10,
maxFeatures: 'auto',
minSamplesLeaf: 5,
minInfoGain: 0,
})Training, Predicting
rf.train(Xtrain, ytrain)
const ypred = rf.predict(Xtest)Saving, Loading models
const model = rf.save()
fs.writeFileSync('example.model', model)
const modelLoaded = new Uint8Array(fs.readFileSync('example.model'))
rf.load(modelLoaded)
const ypred = rf.predict(Xtest)Some browsers doesn't allow running WebAssembly in a sync mode. In such case, you can try async mode described below.
Async mode
const { RandomForestClassifier, RandomForestRegressor } = require('random-forest/async')
// ! Don't miss /async part in require('random-forest/async') !
;(async function f () {
const rf = new RandomForestClassifier({
nEstimators: 100,
maxDepth: 10,
maxFeatures: 'auto',
minSamplesLeaf: 5,
minInfoGain: 0,
nJobs: 4 // Control the number of threads (workers) with this param
})
await rf.init()
await rf.train(Xtrain, ytrain)
const ypred = await rf.predict(Xtest)
console.log(ypred, ytest)
})()Currently the async mode doesn't support loading/saving models.
Development
Contributions are very welcomed. Some insights on how everything works:
Building steps:
- The native code is loaded from the native-forest repo, a fork from RandomForests, a C++ implementation of random forests
- Custom C++ interfaces are in
src/api.cppandsrc/api.h. - Emscripten compiles the
native-forestcode with defined interfaces intonative/native.jsandnative/native.wasm. Compilation settings located inMakefile - To load WebAssembly in sync mode,
prepare-wasm.jsscript converts the wasm file into a Uint8 array and stores it in thewrappersfolder - Then
src/base.jsloadswrapper/native.bin.jsas a regular CommonJS module, initializes it using thenative/native.jsmodule utils and then inititalizes native functions withcwrap - That's all what needed for the sync mode to work. Now prepare
asyncversion. To make it easier loading and bundling the module, a WebWorker script is bundled, rather than uses importScript. It's also loaded not as a separate file, but Blob. To generate the Blob we need the worker to be compiled first, then loaded as a string - Bundle
src/worker.jsintodist/worker.js - Use
prepare-worker.jsto read code ofdist/worker.jsand save it as a module inwrapper/worker.code.js - Load wrapped code in
src/async.js, init Blob, the URL, and WebWorkers - In async mode results are aggregates
