惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
IT之家
IT之家
Blog — PlanetScale
Blog — PlanetScale
罗磊的独立博客
V
V2EX
Vercel News
Vercel News
Apple Machine Learning Research
Apple Machine Learning Research
J
Java Code Geeks
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Tailwind CSS Blog
I
InfoQ
Engineering at Meta
Engineering at Meta
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
H
Help Net Security
腾讯CDC
D
Docker
P
Proofpoint News Feed
GbyAI
GbyAI
博客园 - 三生石上(FineUI控件)
aimingoo的专栏
aimingoo的专栏

StudyingLover's Blog

Diffusion Policy笔记 rwkv笔记 act笔记 nanovllm-block_manager opencode多智能体 nanobot-pre-train nanobot-rl nanobot-sft nanobot-checkpoint_manager nanobot-gpt nanobot-mid-train Vision Mamba (Vim)笔记 BPE演示 最后一遍学习Transformer YOLOv5 目标检测笔记 下载根服务器解析记录 Dynaseal A Backend-Controlled LLM API Key Distribution Scheme with Constrained Invocation Parameters 判断链表有环 王道25数据结构勘误 关于perplexity的open-sourcing-r1-1776 AI为什么不像人类一样进行多轮对话 新博客改造日记和功能测试 linuxqq只显示登陆背景图 数字设计和计算机体系结构(机械工业出版社)勘误(自制) Dynaseal:面向未来端侧llm agent的llm api key分发机制 A Definitive Guide to Markdown Style This post is using MDX, Where you can embed JSX and Astro components RT-Patch学习 pydantic实现的LLM ReAct fastapi 和 uvicorn 设置监听 ipv6
使用xgboost的c接口推理模型
About the Author StudyingLover · 2023-09-11 · via StudyingLover's Blog

使用xgboost的c接口推理模型

官方c api tutorial文档,非常恶心的一点是,tutorial和文档问题很多。

也参考了不少开源项目,主要有xgboost-c-cplusplus,xgboostpp.

首先导入头文件#include "xgboost/c_api.h" ,接下来xgboost的绝大多数接口都包含在了这个头文件中。

然后我们需要一个宏,来用它获取xgboost函数使用的情况.在每次调用xgboost函数时都应该调用这个宏。

#define safe_xgboost(call) {  \
  int err = (call); \
  if (err != 0) { \
    fprintf(stderr, "%s:%d: error in %s: %s\n", __FILE__, __LINE__, #call, XGBGetLastError());  \
    exit(1); \
  } \
}

我们使用的模型文件为xgboost_model.bin ,训练数据的输入是 11 个元素。

首先我们声明一个boost模型的句柄BoosterHandle booster; 接着用XGBoosterCreate 函数创建一个模型 。

BoosterHandle booster;
safe_xgboost(XGBoosterCreate(NULL, 0, &booster));

设置一个字符串作为模型路径const char *model_path = "../xgboost_model.bin";(../是因为编译出来的可执行文件在build目录下) , 通过句柄使用XGBoosterLoadModel函数加载模型。

const char *model_path = "../xgboost_model.bin";
XGBoosterLoadModel(booster, model_path)

设置一组数据作为推理测试,这里我选的数据标签是1.接着将输入数据转为xgboost的DMatrix格式。

float a[11]= {14.0,2.0,1.0,12.0,19010.0,120.0,14.0,0.0,0.0,0.0,0.0};
DMatrixHandle h_test;
safe_xgboost(XGDMatrixCreateFromMat(a, 1, 11, -1, &h_test));

下面就可以进行模型推理了,out_len 代表输出的长度(实际上是一个整型变量),f的模型推理的结果。

bst_ulong out_len;
const float *f;
safe_xgboost(XGBoosterPredict(booster, h_test, 0, 0, 1, &out_len, &f));

我们可以打印输出查看结果

printf("Value of the variable: %f\n", f[0]);

最后记得释放内存

XGDMatrixFree(h_test);
XGBoosterFree(booster);

完整的代码

#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "xgboost/c_api.h"

#define safe_xgboost(call) {  \
  int err = (call); \
  if (err != 0) { \
    fprintf(stderr, "%s:%d: error in %s: %s\n", __FILE__, __LINE__, #call, XGBGetLastError());  \
    exit(1); \
  } \
}

int main(int argc, char const *argv[]) {
    const char *model_path = "../xgboost_model.bin";

    // create booster handle first
    BoosterHandle booster;
    safe_xgboost(XGBoosterCreate(NULL, 0, &booster));
    // load model
    safe_xgboost(XGBoosterLoadModel(booster, model_path));

    //generate random data of a a[11],every nuber from 0 to 2
    // float a[11]= {1.0,12.0,1.0,1.0,16134.0,20600.0,0.0,1.0,0.0,0.0,0.0}; // label: 0.0
    float a[11]= {14.0,2.0,1.0,12.0,19010.0,120.0,14.0,0.0,0.0,0.0,0.0}; // label: 1.0

    for (int i = 0; i < 11; i++) {
        printf("%f, ", a[i]);
        if (i == 10) {
            printf("\n");
        }
    }
    // convert to DMatrix
    DMatrixHandle h_test;
    safe_xgboost(XGDMatrixCreateFromMat(a, 1, 11, -1, &h_test));
    // predict
    bst_ulong out_len;
    const float *f;
    safe_xgboost(XGBoosterPredict(booster, h_test, 0, 0, 1, &out_len, &f));
    printf("Value of the variable: %f\n", f[0]);

    XGDMatrixFree(h_test);
    XGBoosterFree(booster);
    return 0;
}

使用cmake编译

cmake_minimum_required(VERSION 3.18)
project(project_name LANGUAGES C CXX VERSION 0.1)
set(xgboost_DIR "/usr/include/xgboost")

include_directories(${xgboost_DIR})
link_directories(${xgboost_DIR})

add_executable(project_name test.c)
target_link_libraries(project_name xgboost)
mkdir build
cd ./build
cmake ..
make .
./project_name