Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

libsvm in Typescript for machinelearn.js

License

NotificationsYou must be signed in to change notification settings

machinelearnjs/libsvm-ts

Repository files navigation

Build StatusNPM versionnpm download

Port of libsvm v3.22 usingemscripten and it targets browser or nodejs using asm and WebAssembly.

What is libsvm?libsvm is ac++ library developped by Chih-Chung Chang and Chih-Jen Lin that allows to do support vector machine (aka SVM) classification and regression.

Resources about libsvm:

Usage

Install using npm

npm install libsvm-ts

Install using yarn

yarn add libsvm-ts

Load in nodejs

The main entry point loads the WebAssembly build and is asynchronous.

import{SVM}from'libsvm-ts';constsvm=newSVM();// ...

Load in the browser

The npm package contains a bundle for the browser that works with AMD and browser globals. There is one bundle for the asm build and another for the web assembly build. They are located in thedist/browser directory of the package. You can load them into your web page with ascript tag. For the web assembly module, make sure that the libsvm.wasm file is served from the same relative path as the js file.

Basic usage

This example illustrates how to use the library to train and use an SVM classifier.

import{SVM}from'libsvm-ts';constsvm=newSVM({type:'C_SVC',kernel:'RBF',gamma:1,cost:1});// This is the xor problem//  1  0//  0  1constsamples=[[0,0],[1,1],[1,0],[0,1]];constlabels=[0,0,1,1];svm.loadWASM().then((loadedSVM)=>{// Also you can loadASM() instead of loadWASM()loadedSVM.train({ samples, labels});constpredictedLabel=loadedSVM.predictOne({sample:[0.7,0.8]});console.log(predictedLabel)// 0});

Development

We welcome new contributors of all level of experience. The development guide will be added to assist new contributors to easily join the project.

  • You want to participate in a Machine Learning project, which will boost your Machine Learning skills and knowledge
  • Looking to be part of a growing community
  • You want to learn Machine Learning
  • You like Typescript ❤️ Machine Learning

CheckoutCONTRIBUTIONS.md for more information

Benchmarks

You can compare the performance of the library in various environments. Runnpm run benchmark to run the benchmarks with native c/c++ code and with the compiled code with your local version of node.js. For browser performance, go to theweb benchmark page.

Speed is mainly affected by the javascript engine that compiles it. Since WebAssembly has been stabilized and is an optimization phase, more recent engines are almost always faster.

Speed is also affected by the version of emscripten that generated the build or the options used in the build. I will try to keep up with any improvement that might significantly impact the performance.

Cross-validation benchmark

I report the results here for the cross-validation benchmark on the iris dataset to get a feeling for how performance compares on different platforms. There are other benchmarks that can be run from the terminal in node.js or in the browser. The performance results are given relative to how they run natively (with compiled c++ code). The benchmarks only consider runtime performance, not load and parse performance.

PlatformRel asm perfRel wasm perf
Native100%100%
Node.js 8.1.234.2%52.6%
Node.js v7.10.014.4%N/A
Chrome 59.0.3071.11536.2%51.3%
Firefox 54.035.5%70.4%

What are asm and WebAssembly ?

Fromasmjs.org

asm is an optimizable subset of javascript.

Fromwebassembly.org

WebAssembly or wasm is a new portable, size- and load-time-efficient format suitable for compilation to the web

Should I use asm or WebAssembly ?

Both. You should try to use WebAssembly first and fall back to asm in order to support all browsers.

WebAssembly is currently supported in the latest stable versions of Chrome, Firefox and on preview versions of Safari and Edge.

API Documentation

SVM

Kind: global class

new SVM(options)

ParamTypeDefaultDescription
optionsobject
[options.type]numberSVM_TYPES.C_SVCType of SVM to perform,
[options.kernel]numberKERNEL_TYPES.RBFKernel function,
[options.degree]number3Degree of polynomial, for polynomial kernel
[options.gamma]numberGamma parameter of the RBF, Polynomial and Sigmoid kernels. Default value is 1/num_features
[options.coef0]number0coef0 parameter for Polynomial and Sigmoid kernels
[options.cost]number1Cost parameter, for C SVC, Epsilon SVR and NU SVR
[options.nu]number0.5For NU SVC and NU SVR
[options.epsilon]number0.1For epsilon SVR
[options.cacheSize]number100Cache size in MB
[options.tolerance]number0.001Tolerance
[options.shrinking]booleantrueUse shrinking euristics (faster),
[options.probabilityEstimates]booleanfalseweather to train SVC/SVR model for probability estimates,
[options.weight]objectSet weight for each possible class
[options.quiet]booleantruePrint info during training if false

svM.train(samples, labels)

Trains the SVM model.

Kind: instance method ofSVM
Throws:

  • if SVM instance was instantiated from SVM.load.
ParamTypeDescription
samplesArray.<Array.<number>>The training samples. First level of array are the samples, second level are the individual features
labelsArray.<number>The training labels. It should have the same size as the samples. If you are training a classification model, the labels should be distinct integers for each class. If you are training a regression model, each label should be the value of the predicted variable.

svM.crossValidation(samples, labels, kFold) ⇒Array.<number>

Performs k-fold cross-validation (KF-CV). KF-CV separates the data-set into kFold random equally sized partitions,and uses each as a validation set, with all other partitions used in the training set. Observations left overfrom if kFold does not divide the number of observations are left out of the cross-validation process. IfkFold is one, this is equivalent to a leave-on-out cross-validation

Kind: instance method ofSVM
Returns:Array.<number> - The array of predicted labels produced by the cross validation. Has a size equal tothe number of samples provided as input.
Throws:

  • if SVM instance was instantiated from SVM.loadWASM() or SVM.loadASK().
ParamTypeDescription
samplesArray.<Array.<number>>The training samples.
labelsArray.<number>The training labels.
kFoldnumberNumber of datasets into which to split the training set.

svM.free()

Free the memory allocated for the model. Since this memory is stored in the memory model of emscripten, it isallocated within an ArrayBuffer and WILL NOT BE GARBARGE COLLECTED, you have to explicitly free it. Sonot calling this will result in memory leaks. As of today in the browser, there is no way to hook thegarbage collection of the SVM object to free it automatically.Free the memory that was created by the compiled libsvm library to.store the model. This model is reused every time the predict method is called.

Kind: instance method ofSVM

svM.predictOne(sample) ⇒number

Predict the label of one sample.

Kind: instance method ofSVM
Returns:number - - The predicted label.

ParamTypeDescription
sampleArray.<number>The sample to predict.

svM.predict(samples) ⇒Array.<number>

Predict the label of many samples.

Kind: instance method ofSVM
Returns:Array.<number> - - The predicted labels.

ParamTypeDescription
samplesArray.<Array.<number>>The samples to predict.

svM.predictProbability(samples) ⇒Array.<object>

Predict the label with probability estimate of many samples.

Kind: instance method ofSVM
Returns:Array.<object> - - An array of objects containing the prediction label and the probability estimates for each label

ParamTypeDescription
samplesArray.<Array.<number>>The samples to predict.

svM.predictOneProbability(sample) ⇒object

Predict the label with probability estimate.

Kind: instance method ofSVM
Returns:object - - An object containing the prediction label and the probability estimates for each label

ParamType
sampleArray.<number>

svM.predictOneInterval(sample, confidence) ⇒object

Predict a regression value with a confidence interval

Kind: instance method ofSVM
Returns:object - - An object containing the prediction value and the lower and upper bounds of the confidence interval

ParamTypeDescription
sampleArray.<number>
confidencenumberA value between 0 and 1. For example, a value 0.95 will give you the 95% confidence interval of the predicted value.

svM.predictInterval(samples, confidence) ⇒Array.<object>

Predict regression values with confidence intervals

Kind: instance method ofSVM
Returns:Array.<object> - - An array of objects each containing the prediction label and the probability estimates for each label

ParamTypeDescription
samplesArray.<Array.<number>>An array of samples.
confidencenumberA value between 0 and 1. For example, a value 0.95 will give you the 95% confidence interval of the predicted value.

svM.getLabels() ⇒Array.<number>

Get the array of labels from the model. Useful when creating an SVM instance with SVM.load

Kind: instance method ofSVM
Returns:Array.<number> - - The list of labels.

svM.getSVIndices() ⇒Array.<number>

Get the indices of the support vectors from the training set passed to the train method.

Kind: instance method ofSVM
Returns:Array.<number> - - The list of indices from the training samples.

svM.serializeModel() ⇒string

Uses libsvm's serialization method of the model.

Kind: instance method ofSVM
Returns:string - The serialization string.

SVM.SVM_TYPES :Object

SVM classification and regression types

Kind: static property ofSVM
Properties

NameDescription
C_SVCThe C support vector classifier type
NU_SVCThe nu support vector classifier type
ONE_CLASSThe one-class support vector classifier type
EPSILON_SVRThe epsilon support vector regression type
NU_SVRThe nu support vector regression type

SVM.KERNEL_TYPES :Object

SVM kernel types

Kind: static property ofSVM
Properties

NameDescription
LINEARLinear kernel
POLYNOMIALPolynomial kernel
RBFRadial basis function (gaussian) kernel
SIGMOIDSigmoid kernel

SVM.loadASM() ⇒SVM

Create a SVM instance using ASM.

Kind: a member method ofSVM
Returns:SVM - - SVM instance that contains the model.

ParamTypeDescription
serializedModelstringThe serialized model.

SVM.loadWASM() ⇒SVM

Create a SVM instance using WASM.

Kind: a member method ofSVM
Returns:SVM - - SVM instance that contains the model.

ParamTypeDescription
serializedModelstringThe serialized model.

LICENSE

BSD-3-Clause

About

libsvm in Typescript for machinelearn.js

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors3

  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp