linux下c++集成已训练LightGBM模型进行预测
0 原理
通过下载lightGBM源码,使用cmake3.18版本对源码进行编译,生成lib_lightgbm.so文件。在c++文件中,通过链接已经编译好的lgb库,实现在c++中调用已经训练好的lgb模型。
1 相关材料
1.1 安装包
(1)lightGBM源码 提取码:qab2
(2)cmake 提取码:3sdn
(3)环境:centos7
1.2 前提准备
操作系统已经按照g++和gcc编译工具,可使用命令进行安装
yum install gcc
yum install gcc-c++
2 过程
本次操作目录均在/root/test,如下图所示:
2.1 解压安装cmake
(1) 输入命令:tar -zxvf cmake-3.18.4.tar.gz 解压cmake.tar.gz
(2) 进入cmake-3.18.4文件夹并执行./configure命令
按照过程中如果报了“Could not find OpenSSL. Install an OpenSSL development package or”,需要先执行yum instal openssl和yum install openssl-devel再执行./configure命令
(3) 执行命令gmake
(4) 执行命令确认cmake的版本,确认cmake是否成功安装
2.2 解压编译lightGBM
2.3 lightGBM模型生成
2.3.1 c++生成lgb模型
2.3.2 python生成lgb模型
2.4 c++集成lightGBM预测
#include <LightGBM/c_api.h>
#include <iostream>
#include <vector>
void predict(std::vector<float> &row)
{
std::string pred_result = "";
int temp;
int p = 1;
BoosterHandle handle;
temp = LGBM_BoosterCreateFromModelfile("models/3_300_gbm.txt", &p, &handle);
std::cout << "load result value is " << temp << std::endl;
// std::vector<float> row = {0.07946399999999999, 0.9537260000000001, 0.9621209999999999, 0.976303, 7.0, 3.0};
for (auto value : row)
std::cout << value << ",";
std::cout << std::endl;
void *in_p = static_cast<void *>(row.data());
std::vector<double> out(1, 0);
double *out_result = static_cast<double *>(out.data());
int64_t out_len;
int res = LGBM_BoosterPredictForMat(handle, in_p, C_API_DTYPE_FLOAT32, 1, 6, 1, C_API_PREDICT_NORMAL, 0, -1, "None", &out_len, out_result);
std::cout << "file predict result is:" << res << std::endl;
std::cout << "row predict result size is " << out.size() << " value is " << out[0] << std::endl;
}
int main()
{
std::vector<float> row = {0.07946399999999999, 0.9537260000000001, 0.9621209999999999, 0.976303, 7.0, 3.0};
predict(row);
std::cout << std::endl;
std::vector<float> row1 = {0.910457, 0.692459, 0.8338110000000001, 0.78886, 14.0, 10.0};
predict(row1);
std::cout << "Ok complete!" << std::endl;
return 0;
}
// g++ -g -Wall -std=c++11 test.cpp -l_lightgbm -Wl,-R /usr/local/lib -o test
// g++ -g -Wall -std=c++11 test.cpp -l_lightgbm -Wl,-R /root/moead/models -L/ydq/moead/models -I/root/moead/models/include -o test
3 参考
1 源码安装CMake3.18.4
2 如何在C++程序中调用lightgbm (How to use lightgbm in C++ program)
3 Lightgbm C++接口使用
本文地址:https://blog.csdn.net/guazhi8853/article/details/109544552
上一篇: 世界上最炎热的地方有哪些?
下一篇: 国内有哪些低碳路线的风景区呢?