受本篇启发:

Treelite:树模型部署加速工具(支持XGBoost、LightGBM和Sklearn)

Coggle,公众号:Coggle数据科学Treelite:树模型部署加速工具(支持XGBoost、LightGBM和Sklearn)

项目链接:https://treelite.readthedocs.io/

项目论文:https://mlsys.org/Conferences/doc/2018/196.pdf

支持模型:XGB、LGB、SKlearn树模型

还有一个特性:在树模型运行的每台计算机上安装机器学习包(例如 XGBoost、LightGBM、scikit-learning 等)非常麻烦。

这种情况不再如此:Treelite 将导出模型作为独立预测库,以便无需安装任何机器学习包即可进行预测。


1 安装

python3 -m pip install --user treelite treelite_runtime

2 Treelite介绍与原理

Treelite能够树模型编译优化为单独库,可以很方便的用于模型部署。经过优化后可以将XGBoost模型的预测速度提高2-6倍。

如上图,黑色曲线为XGBoost在不同batch size下的吞吐量,红色曲线为XGBoost经过TreeLite编译后的吞吐量。

Treelite支持众多的树模型,特别是随机森林和GBDT。同时Treelite可以很好的支持XGBoost, LightGBM和 scikit-learn,也可以将自定义模型根据要求完成编译。

2.1 逻辑分支

对于树模型而言,节点的分类本质使用if语句完成,而CPU在执行if语句时会等待条件逻辑的计算。

if ( [conditional expression] ) {foo();
} else {bar();
}

如果在构建树模型时候,提前计算好每个分支下面样本的个数,则可以提前预知哪一个叶子节点被执行的可能性更大,进而可以提前执行子节点逻辑。

借助于编译命令,可以完成逻辑计算加速。

/* expected to be false */
if( __builtin_expect([condition],0)){...
} else {...
}

2.2 逻辑比较

原始的分支比较可能会有浮点数比较逻辑,可以量化为数值比较逻辑。

if (data[3].fvalue < 1.5) {
/* floating-point comparison */...
}
if (data[3].qvalue < 3) {
/* integer comparison */...
}

3 快速入门

将树组合模型导入树精简:

import treelite
model = treelite.Model.load('my_model.model', model_format='xgboost')

部署源存档:

# Produce a zipped source directory, containing all model information
# Run `make` on the target machine
model.export_srcpkg(platform='unix', toolchain='gcc',pkgpath='./mymodel.zip', libname='mymodel.so',verbose=True)

部署共享库:

# Like export_srcpkg, but generates a shared library immediately
# Use this only when the host and target machines are compatible
model.export_lib(toolchain='gcc', libpath='./mymodel.so', verbose=True)

对目标机器进行预测:

import treelite_runtime
predictor = treelite_runtime.Predictor('./mymodel.so', verbose=True)
batch = treelite_runtime.Batch.from_npy2d(X)
out_pred = predictor.predict(batch)

4 快速load几类数据模型:XGB、LGB、SKlearn

4.1 XGB

  • 从xgboost.Booster加载XGBoost模型

# bst = an object of type xgboost.Booster
model = Model.from_xgboost(bst)
  • 从binary 二进制格式加载XGBoost模型

# model had been saved to a file named my_model.model
# notice the second argument model_format='xgboost'
model = Model.load('my_model.model', model_format='xgboost')

4.2 LGB

Microsoft/LightGBM的LightGBM 可以使用load(),可以指定参数:model_format='lightgbm'

# model had been saved to a file named my_model.txt
# notice the second argument model_format='lightgbm'
model = Model.load('my_model.txt', model_format='lightgbm')

4.3 scikit-learn模型

可以加载以下几种:

  • sklearn.ensemble.RandomForestRegressor

  • sklearn.ensemble.RandomForestClassifier

  • sklearn.ensemble.GradientBoostingRegressor

  • sklearn.ensemble.GradientBoostingClassifier

# clf is the model object generated by scikit-learn
import treelite.sklearn
model = treelite.sklearn.import_model(clf)

5 java版本:Treelite4J

Treelite4J 是Java使用的依赖,在本地文件系统中找到编译的模型(dll / so / dylib)。我们通过创建Predictor对象来加载已编译的模型:

import ml.dmlc.treelite4j.Predictor;Predictor predictor = new Predictor("path/to/compiled_model.so", -1, true, true);

加载编译的模型后,我们可以对其进行查询:

// Get the input dimension, i.e. the number of feature values in the input vector
int num_feature = predictor.GetNumFeature();// Get the number of classes.
// This number is 1 for tasks other than multi-class classification.
// For multi-class classification task, the number is equal to the number of classes.
int num_class = predictor.GetNumClass();

为了使用单个输入进行预测,我们创建了一个Entry对象数组,设置了它们的值,并调用了预测函数。

// Create an array of feature values for the input
int num_feature = predictor.GetNumFeature();
Entry[] inst = new Entry[num_feature];// Initialize all feature values as missing
for (int i = 0; i < num_feature; ++i) {inst[i] = new Entry();inst[i].setMissing();
}// Set feature values that are not missing
// In this example, we set feature 1, 3, and 7
inst[1].setFValue(-0.5);
inst[3].setFValue(3.2);
inst[7].setFValue(-1.7);// Now run prediction
// (Put false in the second argument to get probability outputs)
float[] result = predictor.predict(inst, false);
// The result is either class probabilities (for multi-class classification)
// or a single number (for all other tasks, such as regression)

python+Treelite:Sklearn树模型训练迁移到c、java部署相关推荐

  1. 【Python】Sklearn线性回归模型预测波士顿房价并绘图

    波士顿房价 这是 sklearn.datasets 里的一种 Toy Dataset ,包含503个美国波士顿房价的观测值,是内置的小数据集,也是研究回归算法的优秀数据集. Python编程实现 im ...

  2. Python训练了个模型,怎么交给Java用呢?

    最近碰到几个人问,如何实现 java 调用他们写好的 Python 应用(模型),这里我就把几种常见的办法做下汇总整理.喜欢本文记得收藏.关注.点赞. [注]文末提供技术交流群 推荐文章 李宏毅< ...

  3. 【机器学习】树模型遇上类别型特征(Python)

    在数据挖掘项目的数据中,数据类型可以分为两种:有序的连续数值 和 无序的类别型特征. 对于xgboost.GBDT等boosting树模型,基学习通常是cart回归树,而cart树的输入通常只支持连续 ...

  4. 树模型对类别变量的 7 种处理方法(Python代码)

    在数据挖掘项目的数据中,数据类型可以分为两种:有序的连续数值 和 无序的类别型特征. 对于xgboost.GBDT等boosting树模型,基学习通常是cart回归树,而cart树的输入通常只支持连续 ...

  5. 【Python】实训6:基于wine和wine_quality数据集练习sklearn构建模型方法(预处理、聚类、分类、回归)

    题目来源: <Python数据分析与应用>第6章 使用 scikit-learn 构建模型 实训部分 [ 黄红梅.张良均主编 中国工信出版集团和人民邮电出版社] 本博客题目文字主要来自: ...

  6. 树模型与线性模型的融合模型(Python实现)

    目录 一.树模型与线性模型的融合模型 二.Python sklearn实现GBDT+LR融合模型 一.树模型与线性模型的融合模型 树模型GBDT原理:https://blog.csdn.net/won ...

  7. python使用sklearn中的make_classification函数生成分类模型(classification)需要的仿真数据、使用pandas查看生成数据的特征数据、目标数据

    python使用sklearn中的make_classification函数生成分类模型(classification)需要的仿真数据.使用pandas查看生成数据的特征数据(features).目标 ...

  8. Python使用sklearn和statsmodels构建多元线性回归模型(Multiple Linear Regression)并解读

    Python使用sklearn和statsmodels构建多元线性回归模型(Multiple Linear Regression)并解读 #仿真数据集(预测股票指数) 这里的目标是根据两个宏观经济变量 ...

  9. Python使用sklearn构建lasso回归模型并指定样本权重:即构建带样本权重(sample_weight)的回归模型

    Python使用sklearn构建lasso回归模型并指定样本权重:即构建带样本权重(sample_weight)的回归模型 目录

最新文章

  1. Djando 的 cmd命令
  2. python写入文件-Python写入文件(write和writelines)详解
  3. Flask项目常见面试问题
  4. day_work_02
  5. [渝粤教育] 广东-国家-开放大学 互联网营销概论
  6. android 百分数与进度显示
  7. IntelliJ Idea 常用12款插件(提高开发效率),附优秀主题插件
  8. set是无序集合,放入set中的元素通过iterator输出时候是无序的
  9. python docx 替换文字_查找并替换.docx文件中的文本 - Python
  10. ELK收集日志到mysql
  11. 获取httpservletrequest所有参数的名称和值
  12. 线程安全问题和Synchronized的使用
  13. hermite插值matlab代码,hermite插值matlab
  14. 2018---2019 数学四班张子琪 C语言设计总结
  15. 内存池(memory pool)
  16. python appium连接安卓真机测试
  17. 混合动力simulink模型 转卖新能源混动车型模式转换说明,包含HCU模式转换simulink框图及说明文档
  18. android 输入法,里面还集成语音输入
  19. 【Excel】数据透视表—数据透视表布局(显示)
  20. B站尚硅谷React入门教程

热门文章

  1. 学习笔记: ES7(ES2016)新功能
  2. JAVA日期时间相关库
  3. 第五篇:你“ 看不见 ” 的隐式转换
  4. RAS、AES、DES加密
  5. 让.net 2.0支持并行计算
  6. [JOYOI] 自然数拆分Lunatic版
  7. Python的Base64编码图片(转载)
  8. I.MX6 2G DDR3 16G eMMC
  9. 【Gson】【1】Gson使用简介
  10. 增强环路现象!? 为你揭示云计算魔力!