pytorch从python转 c++涉及到的数据保存加载问题;libtorch

pytorch 从python 转 c++涉及到的数据保存加载问题

1. torch.nn.Module 保存 state_dict 无法被 c++访问,只能转化为 python字典

python代码

python 复制代码
model = ThreeLayer_FCNN_Net()
model.load_state_dict(ret_load)
w = {k: v for k, v in model.state_dict().items()}
torch.save(w, "data.pkl")

c++代码

cpp 复制代码
std::vector<char> get_the_bytes(std::string filename) {
    std::ifstream input(filename, std::ios::binary);
    std::vector<char> bytes(
        (std::istreambuf_iterator<char>(input)),
        (std::istreambuf_iterator<char>()));
    input.close();
    return bytes;
}
cpp 复制代码
std::vector<char> f = get_the_bytes("../48_channal_guozi_2.pkl");
torch::IValue x = torch::pickle_load(f);
auto dict = x.toGenericDict();
std::cout << "dict: " << dict << std::endl;

2. 保存 Tensor张量,C++加载 Tensor张量

python代码

python 复制代码
data = torch.ones(3, 4)
torch.save(data, "data.pkl")

c++代码

cpp 复制代码
std::vector<char> f = get_the_bytes("../48_channal_guozi_2.pkl");
torch::IValue x = torch::pickle_load(f);
auto my_tensor = x.toTensor();
std::cout << "my_tensor: " << my_tensor << std::endl;
相关推荐
luj_17684 分钟前
随机性在算法与占卜中的共通原理
c语言·开发语言·c++·经验分享·算法
这就是佬们吗7 分钟前
企业Agent落地为什么需要RAG?
人工智能·python·fastapi
Lazionr11 分钟前
vector初识——从动态数组到STL核心容器
开发语言·c++
AI视觉网奇13 分钟前
glb读取颜色
开发语言·python
yyds_yyd_1008616 分钟前
3731. 找出缺失的元素(2026.08.04)
c++·leetcode
呱呱巨基31 分钟前
CMake基础
linux·c++·笔记·学习
半兽先生36 分钟前
2026年RAG系统主流开源文档解析工具选型指南:PaddleOCR、MinerU、LiteParse、HunyuanOCR、Apache Tika 全面对比
人工智能·python·机器学习·ai·开源
郝学胜-神的一滴3 小时前
Python 高级编程 026:内置数据结构之骈文纵论
开发语言·数据结构·python·程序人生·软件工程
DLYSB_9 小时前
存储运维实战:基于 Ceph Event 监听与 Python 适配器的分布式存储健康度物理声光响应架构
运维·ceph·python·报警灯
阿童木写作9 小时前
跨境图片翻译工具多合一,批量图片视频字幕翻译加智能抠图
人工智能·python·音视频·语音识别