Logo

0x3d.Site

is designed for aggregating information.
Welcome
check repository here

m2cgen

GitHub Actions Status Coverage Status License: MIT Python Versions PyPI Version Downloads

m2cgen (Model 2 Code Generator) - is a lightweight library which provides an easy way to transpile trained statistical models into a native code (Python, C, Java, Go, JavaScript, Visual Basic, C#, PowerShell, R, PHP, Dart, Haskell, Ruby, F#, Rust, Elixir).

Installation

Supported Python version is >= 3.7.

pip install m2cgen

Development

Make sure the following command runs successfully before submitting a PR:

make pre-pr

Alternatively you can run the Docker version of the same command:

make docker-build docker-pre-pr

Supported Languages

  • C
  • C#
  • Dart
  • F#
  • Go
  • Haskell
  • Java
  • JavaScript
  • PHP
  • PowerShell
  • Python
  • R
  • Ruby
  • Rust
  • Visual Basic (VBA-compatible)
  • Elixir

Supported Models

ClassificationRegression
Linear
  • scikit-learn
    • LogisticRegression
    • LogisticRegressionCV
    • PassiveAggressiveClassifier
    • Perceptron
    • RidgeClassifier
    • RidgeClassifierCV
    • SGDClassifier
  • lightning
    • AdaGradClassifier
    • CDClassifier
    • FistaClassifier
    • SAGAClassifier
    • SAGClassifier
    • SDCAClassifier
    • SGDClassifier
  • scikit-learn
    • ARDRegression
    • BayesianRidge
    • ElasticNet
    • ElasticNetCV
    • GammaRegressor
    • HuberRegressor
    • Lars
    • LarsCV
    • Lasso
    • LassoCV
    • LassoLars
    • LassoLarsCV
    • LassoLarsIC
    • LinearRegression
    • OrthogonalMatchingPursuit
    • OrthogonalMatchingPursuitCV
    • PassiveAggressiveRegressor
    • PoissonRegressor
    • RANSACRegressor(only supported regression estimators can be used as a base estimator)
    • Ridge
    • RidgeCV
    • SGDRegressor
    • TheilSenRegressor
    • TweedieRegressor
  • StatsModels
    • Generalized Least Squares (GLS)
    • Generalized Least Squares with AR Errors (GLSAR)
    • Generalized Linear Models (GLM)
    • Ordinary Least Squares (OLS)
    • [Gaussian] Process Regression Using Maximum Likelihood-based Estimation (ProcessMLE)
    • Quantile Regression (QuantReg)
    • Weighted Least Squares (WLS)
  • lightning
    • AdaGradRegressor
    • CDRegressor
    • FistaRegressor
    • SAGARegressor
    • SAGRegressor
    • SDCARegressor
    • SGDRegressor
SVM
  • scikit-learn
    • LinearSVC
    • NuSVC
    • OneClassSVM
    • SVC
  • lightning
    • KernelSVC
    • LinearSVC
  • scikit-learn
    • LinearSVR
    • NuSVR
    • SVR
  • lightning
    • LinearSVR
Tree
  • DecisionTreeClassifier
  • ExtraTreeClassifier
  • DecisionTreeRegressor
  • ExtraTreeRegressor
Random Forest
  • ExtraTreesClassifier
  • LGBMClassifier(rf booster only)
  • RandomForestClassifier
  • XGBRFClassifier
  • ExtraTreesRegressor
  • LGBMRegressor(rf booster only)
  • RandomForestRegressor
  • XGBRFRegressor
Boosting
  • LGBMClassifier(gbdt/dart/goss booster only)
  • XGBClassifier(gbtree(including boosted forests)/gblinear booster only)
    • LGBMRegressor(gbdt/dart/goss booster only)
    • XGBRegressor(gbtree(including boosted forests)/gblinear booster only)

    You can find versions of packages with which compatibility is guaranteed by CI tests here. Other versions can also be supported but they are untested.

    Classification Output

    Linear / Linear SVM / Kernel SVM

    Binary

    Scalar value; signed distance of the sample to the hyperplane for the second class.

    Multiclass

    Vector value; signed distance of the sample to the hyperplane per each class.

    Comment

    The output is consistent with the output of LinearClassifierMixin.decision_function.

    SVM

    Outlier detection

    Scalar value; signed distance of the sample to the separating hyperplane: positive for an inlier and negative for an outlier.

    Binary

    Scalar value; signed distance of the sample to the hyperplane for the second class.

    Multiclass

    Vector value; one-vs-one score for each class, shape (n_samples, n_classes * (n_classes-1) / 2).

    Comment

    The output is consistent with the output of BaseSVC.decision_function when the decision_function_shape is set to ovo.

    Tree / Random Forest / Boosting

    Binary

    Vector value; class probabilities.

    Multiclass

    Vector value; class probabilities.

    Comment

    The output is consistent with the output of the predict_proba method of DecisionTreeClassifier / ExtraTreeClassifier / ExtraTreesClassifier / RandomForestClassifier / XGBRFClassifier / XGBClassifier / LGBMClassifier.

    Usage

    Here's a simple example of how a linear model trained in Python environment can be represented in Java code:

    from sklearn.datasets import load_diabetes
    from sklearn import linear_model
    import m2cgen as m2c
    
    X, y = load_diabetes(return_X_y=True)
    
    estimator = linear_model.LinearRegression()
    estimator.fit(X, y)
    
    code = m2c.export_to_java(estimator)
    

    Generated Java code:

    public class Model {
        public static double score(double[] input) {
            return ((((((((((152.1334841628965) + ((input[0]) * (-10.012197817470472))) + ((input[1]) * (-239.81908936565458))) + ((input[2]) * (519.8397867901342))) + ((input[3]) * (324.39042768937657))) + ((input[4]) * (-792.1841616283054))) + ((input[5]) * (476.74583782366153))) + ((input[6]) * (101.04457032134408))) + ((input[7]) * (177.06417623225025))) + ((input[8]) * (751.2793210873945))) + ((input[9]) * (67.62538639104406));
        }
    }
    

    You can find more examples of generated code for different models/languages here.

    CLI

    m2cgen can be used as a CLI tool to generate code using serialized model objects (pickle protocol):

    $ m2cgen <pickle_file> --language <language> [--indent <indent>] [--function_name <function_name>]
             [--class_name <class_name>] [--module_name <module_name>] [--package_name <package_name>]
             [--namespace <namespace>] [--recursion-limit <recursion_limit>]
    

    Don't forget that for unpickling serialized model objects their classes must be defined in the top level of an importable module in the unpickling environment.

    Piping is also supported:

    $ cat <pickle_file> | m2cgen --language <language>
    

    FAQ

    Q: Generation fails with RecursionError: maximum recursion depth exceeded error.

    A: If this error occurs while generating code using an ensemble model, try to reduce the number of trained estimators within that model. Alternatively you can increase the maximum recursion depth with sys.setrecursionlimit(<new_depth>).

    Q: Generation fails with ImportError: No module named <module_name_here> error while transpiling model from a serialized model object.

    A: This error indicates that pickle protocol cannot deserialize model object. For unpickling serialized model objects, it is required that their classes must be defined in the top level of an importable module in the unpickling environment. So installation of package which provided model's class definition should solve the problem.

    Q: Generated by m2cgen code provides different results for some inputs compared to original Python model from which the code were obtained.

    A: Some models force input data to be particular type during prediction phase in their native Python libraries. Currently, m2cgen works only with float64 (double) data type. You can try to cast your input data to another type manually and check results again. Also, some small differences can happen due to specific implementation of floating-point arithmetic in a target language.

    JavaScript
    JavaScript
    JavaScript is a dynamic scripting language used to create interactive web experiences. It's an essential tool for front-end development, enabling features like dynamic content, animations, and event handling. JavaScript is supported by all major browsers.
    GitHub - dalekjs/dalek: [unmaintained] DalekJS Base framework
    GitHub - dalekjs/dalek: [unmaintained] DalekJS Base framework
    Tabulator - Interactive JavaScript Tables
    Tabulator - Interactive JavaScript Tables
    GitHub - totorojs/totoro: A simple and stable cross-browser testing tool. 简单稳定的跨浏览器测试工具。
    GitHub - totorojs/totoro: A simple and stable cross-browser testing tool. 简单稳定的跨浏览器测试工具。
    GitHub - duojs/duo: A next-generation package manager for the front-end
    GitHub - duojs/duo: A next-generation package manager for the front-end
    GitHub - hakimel/reveal.js: The HTML Presentation Framework
    GitHub - hakimel/reveal.js: The HTML Presentation Framework
    PixiJS | The HTML5 Creation Engine | PixiJS
    PixiJS | The HTML5 Creation Engine | PixiJS
    GitHub - adonisjs/core: AdonisJS is a TypeScript-first web framework for building web apps and API servers. It comes with support for testing, modern tooling, an ecosystem of official packages, and more.
    GitHub - adonisjs/core: AdonisJS is a TypeScript-first web framework for building web apps and API servers. It comes with support for testing, modern tooling, an ecosystem of official packages, and more.
    GitHub - os-js/OS.js: OS.js - JavaScript Web Desktop Platform
    GitHub - os-js/OS.js: OS.js - JavaScript Web Desktop Platform
    GitHub - alpinejs/alpine: A rugged, minimal framework for composing JavaScript behavior in your markup.
    GitHub - alpinejs/alpine: A rugged, minimal framework for composing JavaScript behavior in your markup.
    Phaser - A fast, fun and free open source HTML5 game framework
    Phaser - A fast, fun and free open source HTML5 game framework
    GitHub - chaijs/chai: BDD / TDD assertion framework for node.js and the browser that can be paired with any testing framework.
    GitHub - chaijs/chai: BDD / TDD assertion framework for node.js and the browser that can be paired with any testing framework.
    GitHub - simplegeo/polymaps: Polymaps is a free JavaScript library for making dynamic, interactive maps in modern web browsers.
    GitHub - simplegeo/polymaps: Polymaps is a free JavaScript library for making dynamic, interactive maps in modern web browsers.
    List.js
    List.js
    GitHub - pchen66/panolens.js: Javascript panorama viewer based on Three.js
    GitHub - pchen66/panolens.js: Javascript panorama viewer based on Three.js
    GitHub - Fooidge/PleaseJS: JavaScript Library for creating random pleasing colors and color schemes
    GitHub - Fooidge/PleaseJS: JavaScript Library for creating random pleasing colors and color schemes
    GitHub - canjs/canjs: Build CRUD apps in fewer lines of code.
    GitHub - canjs/canjs: Build CRUD apps in fewer lines of code.
    GitHub - blueimp/jQuery-File-Upload: File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.
    GitHub - blueimp/jQuery-File-Upload: File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.
    GitHub - peachananr/onepage-scroll: Create an Apple-like one page scroller website (iPhone 5S website) with One Page Scroll plugin
    GitHub - peachananr/onepage-scroll: Create an Apple-like one page scroller website (iPhone 5S website) with One Page Scroll plugin
    FoalTS
    FoalTS
    GitHub - whatsup/whatsup: A frontend framework for chillout-mode development 🥤 JSX components on generators*, fast mobx-like state management and exclusive cssx style system
    GitHub - whatsup/whatsup: A frontend framework for chillout-mode development 🥤 JSX components on generators*, fast mobx-like state management and exclusive cssx style system
    GitHub - gka/chroma.js: JavaScript library for all kinds of color manipulations
    GitHub - gka/chroma.js: JavaScript library for all kinds of color manipulations
    Matter.js
    Matter.js
    GitHub - guillaumepotier/Parsley.js: Validate your forms, frontend, without writing a single line of javascript
    GitHub - guillaumepotier/Parsley.js: Validate your forms, frontend, without writing a single line of javascript
    GitHub - pegjs/pegjs: PEG.js: Parser generator for JavaScript
    GitHub - pegjs/pegjs: PEG.js: Parser generator for JavaScript
    GitHub - qTip2/qTip2: qTip2 - Pretty powerful tooltips
    GitHub - qTip2/qTip2: qTip2 - Pretty powerful tooltips
    GitHub - nightwatchjs/nightwatch: Integrated end-to-end testing framework written in Node.js and using W3C Webdriver API. Developed at @browserstack
    GitHub - nightwatchjs/nightwatch: Integrated end-to-end testing framework written in Node.js and using W3C Webdriver API. Developed at @browserstack
    GitHub - chartjs/Chart.js: Simple HTML5 Charts using the <canvas> tag
    GitHub - chartjs/Chart.js: Simple HTML5 Charts using the <canvas> tag
    GitHub - ariya/phantomjs: Scriptable Headless Browser
    GitHub - ariya/phantomjs: Scriptable Headless Browser
    GitHub - keystonejs/keystone: The superpowered headless CMS for Node.js — built with GraphQL and React
    GitHub - keystonejs/keystone: The superpowered headless CMS for Node.js — built with GraphQL and React
    AnyChart is a lightweight and robust JavaScript charting library
    AnyChart is a lightweight and robust JavaScript charting library
    JavaScript
    More on JavaScript

    Programming Tips & Tricks

    Code smarter, not harder—insider tips and tricks for developers.

    Error Solutions

    Turn frustration into progress—fix errors faster than ever.

    Shortcuts

    The art of speed—shortcuts to supercharge your workflow.
    1. Collections 😎
    2. Frequently Asked Question's 🤯

    Tools

    available to use.

    Made with ❤️

    to provide resources in various ares.