sklearn-porter

Repository: https://github.com/nok/sklearn-porter

GaussianNB

Documentation: sklearn.naive_bayes.GaussianNB


In [1]:
import sys
sys.path.append('../../../../..')

Load data


In [2]:
from sklearn.datasets import load_iris

iris_data = load_iris()

X = iris_data.data
y = iris_data.target

print(X.shape, y.shape)


((150, 4), (150,))

Train classifier


In [3]:
from sklearn.naive_bayes import GaussianNB

clf = GaussianNB()
clf.fit(X, y)


Out[3]:
GaussianNB(priors=None, var_smoothing=1e-09)

Transpile classifier


In [4]:
from sklearn_porter import Porter

porter = Porter(clf, language='js')
output = porter.export()

print(output)


var GaussianNB = function(priors, sigmas, thetas) {

    this.priors = priors;
    this.sigmas = sigmas;
    this.thetas = thetas;

    this.predict = function(features) {
        var likelihoods = new Array(this.sigmas.length);
    
        for (var i = 0, il = this.sigmas.length; i < il; i++) {
            var sum = 0.;
            for (var j = 0, jl = this.sigmas[0].length; j < jl; j++) {
                sum += Math.log(2. * Math.PI * this.sigmas[i][j]);
            }
            var nij = -0.5 * sum;
            sum = 0.;
            for (var j = 0, jl = this.sigmas[0].length; j < jl; j++) {
                sum += Math.pow(features[j] - this.thetas[i][j], 2.) / this.sigmas[i][j];
            }
            nij -= 0.5 * sum;
            likelihoods[i] = Math.log(this.priors[i]) + nij;
        }
    
        var classIdx = 0;
        for (var i = 0, l = likelihoods.length; i < l; i++) {
            classIdx = likelihoods[i] > likelihoods[classIdx] ? i : classIdx;
        }
        return classIdx;
    };

};

if (typeof process !== 'undefined' && typeof process.argv !== 'undefined') {
    if (process.argv.length - 2 === 4) {

        // Features:
        var features = process.argv.slice(2);

        // Parameters:
        var priors = [0.3333333333333333, 0.3333333333333333, 0.3333333333333333];
        var sigmas = [[0.12176400309550259, 0.14081600309550263, 0.029556003095502676, 0.010884003095502673], [0.2611040030955028, 0.09650000309550268, 0.21640000309550278, 0.03832400309550265], [0.39625600309550263, 0.10192400309550273, 0.2984960030955029, 0.07392400309550265]];
        var thetas = [[5.005999999999999, 3.428000000000001, 1.4620000000000002, 0.2459999999999999], [5.936, 2.7700000000000005, 4.26, 1.3259999999999998], [6.587999999999998, 2.9739999999999998, 5.552, 2.026]];

        // Estimator:
        var clf = new GaussianNB(priors, sigmas, thetas);
        var prediction = clf.predict(features);
        console.log(prediction);

    }
}

Run classification in JavaScript


In [5]:
# Save classifier:
# with open('GaussianNB.js', 'w') as f:
#     f.write(output)

# Run classification:
# if hash node 2/dev/null; then
#     node GaussianNB.js 1 2 3 4
# fi