m2cgen 简介
m2cgen(Model 2 Code Generator)-是一个轻量级库,它提供了一种将经过训练的统计模型转换为本机代码(Python、C、Java、Go、JavaScript、Visual Basic、C#、PowerShell、R、PHP、Dart、Haskell、Ruby、F#、Rust)的简便方法。
简而言之,它可以将python scikit-learn 等训练的机器学习模型转成C,JAVA等能够直接运行的代码,从而在无需依赖库的情况下直接运行
m2cgen 安装
注意python 版本需要在3.6以上
pip install m2cgen
示例代码
from sklearn.datasets import load_iris
from xgboost.sklearn import XGBClassifier
from xgboost import plot_importance
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import m2cgen as m2c
# 记载样本数据集
iris = load_iris()
x,y = iris.data,iris.target
# 数据集分割
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=123457)
clf = XGBClassifier(
booster = 'gbtree',
objective = 'multi:softmax',
num_class = 3,
gamma = 0.1,
max_depth = 6,
reg_lambda = 2,
subsample = 0.7,
colsample_bytree = 0.7,
min_child_weight = 3,
eta = 0.1,
seed = 1000,
nthread = 4,
)
#训练模型
clf.fit(x_train,y_train,eval_metric='auc')
#模型转为c代码
code = m2c.export_to_c(clf)
print(code)
转化结果是一段很长的c代码,这里只粘贴部分内容
void score(double * input, double * output) {
double var0;
if ((input[f2]) >= (2.6)) {
var0 = -0.06913044;
} else {
var0 = 0.13098592;
}
double var1;
if ((input[f3]) >= (0.8)) {
var1 = -0.06719698;
} else {
var1 = 0.11539519;
}
double var2;
if ((input[f3]) >= (0.8)) {
var2 = -0.06486788;
} else {
var2 = 0.104500055;
}
版权声明:本文为flyconley原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。