### CLI Usage: Show version Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Command to display the installed version of the m2cgen CLI. ```bash # Show version m2cgen --version ``` -------------------------------- ### Install m2cgen with pip Source: https://github.com/bayeswitnesses/m2cgen/blob/master/README.md Install the m2cgen library using pip. Ensure you have Python version 3.7 or higher. ```bash pip install m2cgen ``` -------------------------------- ### Run pre-PR checks with Docker Source: https://github.com/bayeswitnesses/m2cgen/blob/master/README.md Build and run pre-PR checks using Docker. This provides a consistent environment for development and testing. ```bash make docker-build docker-pre-pr ``` -------------------------------- ### Run pre-PR checks with make Source: https://github.com/bayeswitnesses/m2cgen/blob/master/README.md Execute the pre-PR checks for development. This command ensures code quality and compatibility before submitting a pull request. ```bash make pre-pr ``` -------------------------------- ### CLI Usage: Use joblib-serialized models Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Shows how to use m2cgen CLI with models serialized using joblib instead of pickle. ```bash # Step 6: Use joblib-serialized models m2cgen model.joblib --language python --pickle-lib joblib ``` -------------------------------- ### CLI Usage: Generate Java code from pickled model Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Demonstrates generating Java code from a pickled scikit-learn model using the m2cgen CLI. Requires a pre-trained and pickled model. ```bash # Step 1: Train and pickle a model python - <<'EOF' import pickle from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier X, y = load_iris(return_X_y=True) clf = RandomForestClassifier(n_estimators=10, random_state=42) clf.fit(X, y) with open("model.pkl", "wb") as f: pickle.dump(clf, f) EOF # Step 2: Generate Java code m2cgen model.pkl --language java --class_name IrisModel --package_name com.example > IrisModel.java ``` -------------------------------- ### Export LightGBM RF Booster to Rust Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates Rust code for a LightGBM Random Forest booster model. Requires LightGBM and m2cgen libraries. ```python import xgboost as xgb import lightgbm as lgb from sklearn.datasets import load_iris, load_boston import m2cgen as m2c import warnings; warnings.filterwarnings("ignore") # LightGBM RF booster (random forest mode) lgb_rf = lgb.LGBMRegressor(boosting_type="rf", n_estimators=10, subsample=0.8, subsample_freq=1) lgb_rf.fit(X, y) ust_code = m2c.export_to_rust(lgb_rf) ``` -------------------------------- ### CLI Usage: Pipe support for model serialization Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Demonstrates using m2cgen CLI with piped input for generating JavaScript code from a pickled model. ```bash # Step 5: Pipe support cat model.pkl | m2cgen --language javascript > model.js ``` -------------------------------- ### Export LightGBM Regressor to Go Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates Go code for a LightGBM regression model. Requires LightGBM and m2cgen libraries. ```python import xgboost as xgb import lightgbm as lgb from sklearn.datasets import load_iris, load_boston import m2cgen as m2c import warnings; warnings.filterwarnings("ignore") # LightGBM regression X, y = load_boston(return_X_y=True) lgb_reg = lgb.LGBMRegressor(n_estimators=10) lgb_reg.fit(X, y) go_code = m2c.export_to_go(lgb_reg, function_name="PredictPrice") ``` -------------------------------- ### CLI Usage: Generate C# code with namespace Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates C# code from a pickled model using the m2cgen CLI, including a specified namespace and class name. ```bash # Step 4: Generate C# code with namespace m2cgen model.pkl --language c_sharp --namespace MyApp.ML --class_name IrisClassifier > IrisClassifier.cs ``` -------------------------------- ### Export Model to Go Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generate an idiomatic Go function for use in Go microservices or CLI tools. The function accepts a float64 slice and returns a float64. ```python from sklearn.datasets import load_boston from sklearn import linear_model import m2cgen as m2c import warnings; warnings.filterwarnings("ignore") X, y = load_boston(return_X_y=True) estimator = linear_model.Ridge() estimator.fit(X, y) code = m2c.export_to_go(estimator, function_name="score") print(code) ``` -------------------------------- ### Export Linear Regression Model to Java Source: https://github.com/bayeswitnesses/m2cgen/blob/master/README.md Demonstrates how to export a trained scikit-learn LinearRegression model to Java code using m2cgen. Ensure the scikit-learn model is fitted before exporting. ```python 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) ``` ```java 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)); } } ``` -------------------------------- ### Export to C# Class Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates a C# class with a static method for ML inference. Configurable namespace, class name, and function name. ```python from sklearn.svm import SVC from sklearn.datasets import load_iris import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = SVC(kernel="rbf", random_state=0) clf.fit(X, y) code = m2c.export_to_c_sharp( clf, namespace="MyApp.ML", class_name="IrisClassifier", function_name="Predict" ) print(code) ``` -------------------------------- ### Export Model to Java Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Transpile a scikit-learn model into a Java class with a static score method. Supports custom package, class, and function names, as well as indentation. ```python 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, package_name="com.example.ml", class_name="DiabetesModel", function_name="predict", indent=4 ) print(code) ``` -------------------------------- ### export_to_java Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Transpiles a fitted scikit-learn / XGBoost / LightGBM model into a Java class with a static `score` method. Supports optional `package_name`, `class_name`, `function_name`, and `indent` parameters. ```APIDOC ## export_to_java ### Description Transpiles a fitted scikit-learn / XGBoost / LightGBM model into a Java class with a static `score` method. Supports optional `package_name`, `class_name`, `function_name`, and `indent` parameters. ### Method ```python export_to_java( estimator: object, package_name: str = None, class_name: str = "Model", function_name: str = "score", indent: int = 4 ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python 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, package_name="com.example.ml", class_name="DiabetesModel", function_name="predict", indent=4 ) print(code) ``` ### Response #### Success Response (200) Returns a string containing the generated Java code. #### Response Example ```java package com.example.ml; public class DiabetesModel { public static double predict(double[] input) { return ((((... + ((input[9]) * (67.62538639104406)); } } ``` ``` -------------------------------- ### export_to_go Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates an idiomatic Go function for use in Go microservices or CLI tools, accepting a `[]float64` slice. ```APIDOC ## export_to_go ### Description Generates an idiomatic Go function for use in Go microservices or CLI tools, accepting a `[]float64` slice. ### Method ```python export_to_go( estimator: object, function_name: str = "score" ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from sklearn.datasets import load_boston from sklearn import linear_model import m2cgen as m2c import warnings; warnings.filterwarnings("ignore") X, y = load_boston(return_X_y=True) estimator = linear_model.Ridge() estimator.fit(X, y) code = m2c.export_to_go(estimator, function_name="score") print(code) ``` ### Response #### Success Response (200) Returns a string containing the generated Go code. #### Response Example ```go func score(input []float64) float64 { return 36.367080746577244 + input[0] * -0.108... + input[12] * -0.542... } ``` ``` -------------------------------- ### Export to Rust Function Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates a Rust function returning f64 or Vec. No external crates are required, making it suitable for WebAssembly or native Rust services. ```python from sklearn.svm import SVC from sklearn.datasets import load_iris import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = SVC(kernel="rbf") clf.fit(X, y) code = m2c.export_to_rust(clf, function_name="score") print(code) ``` -------------------------------- ### m2cgen CLI Usage Source: https://github.com/bayeswitnesses/m2cgen/blob/master/README.md Command-line interface for m2cgen to generate code from serialized model objects. Supports specifying language, indentation, function name, class name, and more. Ensure model classes are defined in the unpickling environment. ```bash $ m2cgen --language [--indent ] [--function_name ] [--class_name ] [--module_name ] [--package_name ] [--namespace ] [--recursion-limit ] ``` ```bash $ cat | m2cgen --language ``` -------------------------------- ### Export Model to Python Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Transpile a model into a standalone Python function without external dependencies. The generated code can be saved to a file for use in any Python environment. ```python from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = RandomForestClassifier(n_estimators=10, random_state=42) clf.fit(X, y) code = m2c.export_to_python(clf, function_name="classify_iris") print(code) # Save and use in any Python environment with open("iris_model.py", "w") as f: f.write(code) ``` -------------------------------- ### Export to Visual Basic Module Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates a Visual Basic module compatible with VBA. Minor manual adjustments may be needed (remove first/last module lines). ```python from sklearn.datasets import load_iris from sklearn.linear_model import RidgeClassifier import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = RidgeClassifier() clf.fit(X, y) code = m2c.export_to_visual_basic( clf, module_name="IrisModel", function_name="Score" ) print(code) ``` -------------------------------- ### CLI Usage: Generate Go code with custom function name Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates Go code from a pickled model using the m2cgen CLI, specifying a custom function name for the generated code. ```bash # Step 3: Generate Go code with custom function name m2cgen model.pkl --language go --function_name Predict > model.go ``` -------------------------------- ### Export Model to C Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generate a C function that accepts a double pointer array, suitable for embedding in C extensions or native applications. The generated code can be saved to a .c file. ```python from sklearn.datasets import load_boston from sklearn.ensemble import RandomForestRegressor import m2cgen as m2c import warnings; warnings.filterwarnings("ignore") X, y = load_boston(return_X_y=True) model = RandomForestRegressor(n_estimators=2, random_state=0) model.fit(X, y) code = m2c.export_to_c(model, function_name="predict_price") print(code) with open("model.c", "w") as f: f.write(code) ``` -------------------------------- ### Export to Haskell Module Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates a Haskell module with a pure function. Configurable with module_name and function_name. ```python from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = DecisionTreeClassifier(max_depth=3) clf.fit(X, y) code = m2c.export_to_haskell(clf, module_name="IrisModel", function_name="score") print(code) ``` -------------------------------- ### export_to_c Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates a C function that accepts a `double*` array, suitable for embedding in embedded systems, C extensions, or native applications. ```APIDOC ## export_to_c ### Description Generates a C function that accepts a `double*` array, suitable for embedding in embedded systems, C extensions, or native applications. ### Method ```python export_to_c( estimator: object, function_name: str = "predict" ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from sklearn.datasets import load_boston from sklearn.ensemble import RandomForestRegressor import m2cgen as m2c import warnings; warnings.filterwarnings("ignore") X, y = load_boston(return_X_y=True) model = RandomForestRegressor(n_estimators=2, random_state=0) model.fit(X, y) code = m2c.export_to_c(model, function_name="predict_price") print(code) with open("model.c", "w") as f: f.write(code) ``` ### Response #### Success Response (200) Returns a string containing the generated C code. #### Response Example ```c double predict_price(double * input) { double var0; if (input[12] <= 9.845000267028809) { ... } double var1; ... return (var0 + var1) * 0.5; } ``` ``` -------------------------------- ### export_to_python Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Transpiles a fitted model into a standalone Python function that requires no external dependencies (no NumPy, no scikit-learn at inference time). ```APIDOC ## export_to_python ### Description Transpiles a fitted model into a standalone Python function that requires no external dependencies (no NumPy, no scikit-learn at inference time). ### Method ```python export_to_python( estimator: object, function_name: str = "predict" ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = RandomForestClassifier(n_estimators=10, random_state=42) clf.fit(X, y) code = m2c.export_to_python(clf, function_name="classify_iris") print(code) # Save and use in any Python environment with open("iris_model.py", "w") as f: f.write(code) ``` ### Response #### Success Response (200) Returns a string containing the generated Python code. #### Response Example ```python def classify_iris(input): var0 = [1.0, 0.0, 0.0] if input[3] <= 0.75 else ... ... return [x / 10.0 for x in [var0[i] + ... for i in range(3)]] ``` ``` -------------------------------- ### Export OLS model to Python Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates Python code for an Ordinary Least Squares (OLS) model from StatsModels. Requires statsmodels, numpy, and m2cgen. ```python import statsmodels.api as sm import m2cgen as m2c import numpy as np # Ordinary Least Squares np.random.seed(0) X = sm.add_constant(np.random.randn(100, 3)) y = X @ [1.5, 0.8, -0.6, 0.3] + np.random.randn(100) * 0.5 ols_model = sm.OLS(y, X).fit() python_code = m2c.export_to_python(ols_model, function_name="ols_predict") print(python_code) ``` -------------------------------- ### Export XGBoost Classifier to Java Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates Java code for an XGBoost classification model. Requires XGBoost and m2cgen libraries. ```python import xgboost as xgb import lightgbm as lgb from sklearn.datasets import load_iris, load_boston import m2cgen as m2c import warnings; warnings.filterwarnings("ignore") # XGBoost classification X, y = load_iris(return_X_y=True) xgb_clf = xgb.XGBClassifier(n_estimators=10, use_label_encoder=False, eval_metric="mlogloss") xgb_clf.fit(X, y) java_code = m2c.export_to_java(xgb_clf, class_name="XGBIrisModel") ``` -------------------------------- ### Export GLM (Poisson) model to R Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates R code for a Generalized Linear Model (GLM) with a Poisson family from StatsModels. Requires statsmodels, numpy, and m2cgen. ```python import statsmodels.api as sm import m2cgen as m2c import numpy as np # GLM (Poisson) glM_model = sm.GLM(np.abs(y.astype(int)), X, family=sm.families.Poisson()).fit() r_code = m2c.export_to_r(glm_model, function_name="glm_score") ``` -------------------------------- ### Export to PowerShell Function Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates a PowerShell function for ML inference in Windows automation scripts. ```python from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = LogisticRegression(max_iter=200) clf.fit(X, y) code = m2c.export_to_powershell(clf, function_name="Score") with open("model.ps1", "w") as f: f.write(code) ``` -------------------------------- ### Export DecisionTreeClassifier to F# Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates an F# function for a DecisionTreeClassifier model using pattern matching and infix power operators. Compatible with .NET and Fable. ```python from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = DecisionTreeClassifier(max_depth=3) clf.fit(X, y) code = m2c.export_to_f_sharp(clf, function_name="score") print(code) ``` -------------------------------- ### Export to PHP Function Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates a PHP function that returns a scalar or array, suitable for embedding ML inference directly in PHP web backends. ```python from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = LogisticRegression(max_iter=200) clf.fit(X, y) code = m2c.export_to_php(clf, function_name="score") print(code) ``` -------------------------------- ### Export ExtraTreesClassifier to Ruby Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates a Ruby method for an ExtraTreesClassifier model. The generated code accepts an array and returns a scalar or array. ```python from sklearn.datasets import load_iris from sklearn.ensemble import ExtraTreesClassifier import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = ExtraTreesClassifier(n_estimators=5, random_state=0) clf.fit(X, y) code = m2c.export_to_ruby(clf, function_name="score") print(code) ``` -------------------------------- ### Export to R Function Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates an R function for use in R scripts or Shiny applications. No additional packages are required at inference time. ```python from sklearn.datasets import load_boston import lightgbm as lgb import numpy as np import m2cgen as m2c import warnings; warnings.filterwarnings("ignore") X, y = load_boston(return_X_y=True) model = lgb.LGBMRegressor(n_estimators=2) model.fit(X, y) code = m2c.export_to_r(model, function_name="score") print(code) ``` -------------------------------- ### Export Model to JavaScript Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generate a JavaScript function for browser-side inference or Node.js services. The function returns a scalar or array depending on the model type and has no external dependencies. ```python from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = DecisionTreeClassifier(max_depth=4, random_state=0) clf.fit(X, y) code = m2c.export_to_javascript(clf, function_name="score") print(code) # Use directly in browser or Node.js — no dependencies ``` -------------------------------- ### Export LogisticRegression to Elixir Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates an Elixir module with a function clause-based implementation for a LogisticRegression model. Configurable with module_name. ```python from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = LogisticRegression(max_iter=200) clf.fit(X, y) code = m2c.export_to_elixir(clf, module_name="IrisModel", function_name="score") print(code) ``` -------------------------------- ### Handle Recursion Limit for Large Models Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Increases Python's recursion limit to prevent RecursionError when exporting large ensemble models like RandomForestClassifier with many estimators. ```python import sys from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import load_iris import m2cgen as m2c X, y = load_iris(return_X_y=True) # Large forest — may cause RecursionError without limit increase clf = RandomForestClassifier(n_estimators=500, max_depth=None, random_state=0) clf.fit(X, y) ``` -------------------------------- ### Export to Dart Function Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates a Dart function for use in Flutter applications or Dart CLI tools. ```python from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = RandomForestClassifier(n_estimators=5, random_state=42) clf.fit(X, y) code = m2c.export_to_dart(clf, function_name="score") print(code) ``` -------------------------------- ### Increase Recursion Limit for Model Export Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Before exporting a potentially large model, it's often necessary to increase Python's recursion limit to prevent RecursionError. If the error persists, consider reducing the model's complexity (e.g., n_estimators) or increasing the limit further. ```python import sys sys.setrecursionlimit(50000) try: code = m2c.export_to_java(clf, class_name="BigForest") print(f"Generated {len(code)} characters of Java code") except RecursionError: print("Still too deep — reduce n_estimators or increase limit further") ``` -------------------------------- ### export_to_javascript Source: https://context7.com/bayeswitnesses/m2cgen/llms.txt Generates a JavaScript function suitable for browser-side inference or Node.js services, returning a scalar or array depending on the model type. ```APIDOC ## export_to_javascript ### Description Generates a JavaScript function suitable for browser-side inference or Node.js services, returning a scalar or array depending on the model type. ### Method ```python export_to_javascript( estimator: object, function_name: str = "score" ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier import m2cgen as m2c X, y = load_iris(return_X_y=True) clf = DecisionTreeClassifier(max_depth=4, random_state=0) clf.fit(X, y) code = m2c.export_to_javascript(clf, function_name="score") print(code) # Use directly in browser or Node.js — no dependencies ``` ### Response #### Success Response (200) Returns a string containing the generated JavaScript code. #### Response Example ```javascript function score(input) { var var0; if (input[2] <= 2.449999988079071) { var0 = [1.0, 0.0, 0.0]; } else { ... } return var0; } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.