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

推荐订阅源

Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Engineering at Meta
Engineering at Meta
博客园 - 三生石上(FineUI控件)
The GitHub Blog
The GitHub Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
Schneier on Security
Vercel News
Vercel News
A
Arctic Wolf
G
Google Developers Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
雷峰网
雷峰网
AWS News Blog
AWS News Blog
V
Visual Studio Blog
Cyberwarzone
Cyberwarzone
爱范儿
爱范儿
博客园 - 司徒正美
NISL@THU
NISL@THU
N
News | PayPal Newsroom
N
News and Events Feed by Topic
Scott Helme
Scott Helme
I
InfoQ
Project Zero
Project Zero
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
Tenable Blog
Help Net Security
Help Net Security
D
Docker
IT之家
IT之家
人人都是产品经理
人人都是产品经理
C
Cisco Blogs
Cisco Talos Blog
Cisco Talos Blog
PCI Perspectives
PCI Perspectives
aimingoo的专栏
aimingoo的专栏
博客园 - Franky
G
GRAHAM CLULEY
阮一峰的网络日志
阮一峰的网络日志
T
The Exploit Database - CXSecurity.com
Recent Announcements
Recent Announcements
博客园 - 【当耐特】
L
LINUX DO - 热门话题
J
Java Code Geeks
C
Cyber Attacks, Cyber Crime and Cyber Security
GbyAI
GbyAI
Google DeepMind News
Google DeepMind News
The Hacker News
The Hacker News
H
Hacker News: Front Page
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
SecWiki News
SecWiki News
T
Tailwind CSS Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
罗磊的独立博客

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 pydantic+openai+json 控制大模型输出的最佳范式 解决 Matplotlib Scatter 不支持 Marker 列表的问题:mscatter 实现 roofline model zhipuAI接口兼容openai 在docker部署fastapi宝塔里使用nginx反代套上cloudflare获取请求的真实ip clion搭建libbpf-bootstrap开发环境 coze+coze-discord-proxy+ChatNextWebUI实现AI自由 安卓内核时间使用的是UTC时间 colab运行google最新开源模型Gemma Sora技术报告 视频生成模型作为世界模拟器 笔记 archlinux flutter开发踩坑 fastapi集成google auth登录 linux下NTFS磁盘报错输入输出错误 Venn-Abers 预测器 基于Venn-Abers预测器的系统日志异常检测方法_顾兆军 手机平板远程访问kvm虚拟机的windows phi-2弱智吧测评 poe的gemini pro或是百度开发 google gemini api使用 google gemini api申请 构建用于复杂数据处理的高效UDP服务器和客户端 matplotlib中文字体渲染 TruFor笔记和代码复现 深入分析:GitHub Trending 项目 "multipleWindow3dScene" pua大模型 ggml教程|mnist手写体识别量化推理 xgboost2.0最佳实践 xgboost使用GPU最佳实践 马踏棋盘 cloudlflare推理llama2 docker搭建elasticsearch并使用python连接 FreeU-文字生成图片的免费午餐笔记 Archlinux使用CMake调用xgboost的c接口 m2cgen生成机器学习c语言推理代码 xgboost模型序列化存储并推理 speculative-sampling笔记 prompt2model笔记 RoboTAP笔记 自建obsidian同步服务 MediaPipe即将推出图像生成服务 Dual-Stream Diffusion Net for Text-to-Video Generation笔记 ViT在DDPM取代UNet(DiT) arch4edu搞崩了我的flutter LISA(推理分割)笔记 在终端绘制GPU显存使用曲线 GPTBot介绍 arch蓝牙无法连接 GPU部署llama-cpp-python(llama.cpp通用) 花式求GCD 使用llama构建一个蜜罐(前端) 使用llama构建一个蜜罐(后端) llama-cpp-python快速上手 快速上手llama2.c(更新版) Paper Gestalt笔记 DINO-v2笔记 快速上手llama2.c AnyDoor笔记 Archlinux安装scrcpy加载共享库出错 error while loading shared libraries:libusb-1.0.so.0:wrong ELF class:ELFCLASS32 npc_gzip笔记 python调用c++函数 Filesystem type ntfs3,ntfs not configured in kernel open_clip编码图像和文本 PicGo配置CloudflareR2图片储存 ArchlinuxGnome快捷键打开终端 clip-interrogator代码解析 GroundingDINO安装报错解决 2023华为鲲鹏畅想日暨西安高新国际会议中心零食午饭测评 RoboMaster开源仓库汇总(长期更新) 没有手都可以在腾讯云创建镜像 I3D笔记
使用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