Conversion of a logistic regression into C

Simple example which shows how to predict with a logistic regression using a code implemented in C. This configuration is significantly faster in case of one-off prediction. It usually happens when the machine learned model is embedded in a service.

Train a logistic regression

from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data[:, :2]
y = iris.target
y[y == 2] = 1
lr = LogisticRegression()
lr.fit(X, y)

Out:

LogisticRegression()

Conversion into a graph.

from mlprodict.grammar_sklearn import sklearn2graph
gr = sklearn2graph(lr, output_names=['Prediction', 'Score'])

Conversion into C

ccode = gr.export(lang='c')
print(ccode['code'])

Out:

int LogisticRegression (float* pred, float* Features)
{
    // 140044918869072-LogisticRegression - children
    // 140044918868848-concat - children
    // 140044918868792-sign - children
    // 140044918868736-+ - children
    // 140044918868680-adot - children
    float pred0c0c00c0[2] = {(float)3.3882975578308105, (float)-3.164527654647827};
    float* pred0c0c00c1 = Features;
    // 140044918868680-adot - itself
    float pred0c0c00;
    adot_float_float(&pred0c0c00, pred0c0c00c0, pred0c0c00c1, 2);
    // 140044918868680-adot - done
    float pred0c0c01 = (float)-8.323304176330566;
    // 140044918868736-+ - itself
    float pred0c0c0 = pred0c0c00 + pred0c0c01;
    // 140044918868736-+ - done
    // 140044918868792-sign - itself
    float pred0c0;
    sign_float(&pred0c0, pred0c0c0);
    // 140044918868792-sign - done
    // 140044918868848-concat - itself
    float pred0[2];
    concat_float_float(pred0, pred0c0, pred0c0c0);
    // 140044918868848-concat - done
    memcpy(pred, pred0, 2*sizeof(float));
    // 140044918869072-LogisticRegression - itself
    return 0;
    // 140044918869072-LogisticRegression - done
}

Total running time of the script: ( 0 minutes 0.018 seconds)

Gallery generated by Sphinx-Gallery