sklearn-porter

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

LinearSVC

Documentation: sklearn.svm.LinearSVC


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 import svm

clf = svm.LinearSVC(C=1., random_state=0)
clf.fit(X, y)


/opt/miniconda/envs/sklearn-porter/lib/python2.7/site-packages/sklearn/svm/base.py:922: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.
  "the number of iterations.", ConvergenceWarning)
Out[3]:
LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True,
     intercept_scaling=1, loss='squared_hinge', max_iter=1000,
     multi_class='ovr', penalty='l2', random_state=0, tol=0.0001,
     verbose=0)

Transpile classifier


In [4]:
from sklearn_porter import Porter

porter = Porter(clf, language='java')
output = porter.export(export_data=True)

print(output)


import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import com.google.gson.Gson;


class LinearSVC {

    private class Classifier {
        private double[][] coefficients;
        private double[] intercepts;
    }

    private Classifier clf;

    public LinearSVC(String file) throws FileNotFoundException {
        String jsonStr = new Scanner(new File(file)).useDelimiter("\\Z").next();
        this.clf = new Gson().fromJson(jsonStr, Classifier.class);
    }

    public int predict(double[] features) {
        int classIdx = 0;
        double classVal = Double.NEGATIVE_INFINITY;
        for (int i = 0, il = this.clf.intercepts.length; i < il; i++) {
            double prob = 0.;
            for (int j = 0, jl = this.clf.coefficients[0].length; j < jl; j++) {
                prob += this.clf.coefficients[i][j] * features[j];
            }
            if (prob + this.clf.intercepts[i] > classVal) {
                classVal = prob + this.clf.intercepts[i];
                classIdx = i;
            }
        }
        return classIdx;
    }

    public static void main(String[] args) throws FileNotFoundException {
        if (args.length > 0 && args[0].endsWith(".json")) {

            // Features:
            double[] features = new double[args.length-1];
            for (int i = 1, l = args.length; i < l; i++) {
                features[i - 1] = Double.parseDouble(args[i]);
            }

            // Parameters:
            String modelData = args[0];

            // Estimators:
            LinearSVC clf = new LinearSVC(modelData);

            // Prediction:
            int prediction = clf.predict(features);
            System.out.println(prediction);

        }
    }
}

Run classification in Java


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

# Check model data:
# $ cat data.json

# Download dependencies:
# $ wget -O gson.jar http://central.maven.org/maven2/com/google/code/gson/gson/2.8.5/gson-2.8.5.jar

# Compile model:
# $ javac -cp .:gson.jar LinearSVC.java

# Run classification:
# $ java -cp .:gson.jar LinearSVC data.json 1 2 3 4