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;
相关推荐
MediaTea14 小时前
Python:模块 __dict__ 详解
开发语言·前端·数据库·python
jarreyer14 小时前
python,numpy,pandas和matplotlib版本对应关系
python·numpy·pandas
代码or搬砖15 小时前
HashMap源码
开发语言·python·哈希算法
星轨初途15 小时前
郑州轻工业大学2025天梯赛解题
c++·经验分享·笔记·算法·链表·剪枝
点云SLAM16 小时前
C++ 引用折叠(Reference Collapsing)和示例讲解说明
数据结构·c++·标准算法·完美转发·代码性能优化·c++ 引用折叠·typedef / using
chenyuhao202416 小时前
Linux网络编程:HTTP协议
linux·服务器·网络·c++·后端·http·https
顽强卖力16 小时前
第二章:什么是数据分析师?
笔记·python·职场和发展·学习方法
Minecraft红客16 小时前
ai_dialogue_framework项目1.0(纯原创)
c++·测试工具·电脑
站大爷IP17 小时前
Python实现Excel数据自动化处理:从繁琐操作到智能流程的蜕变
python
BBB努力学习程序设计17 小时前
Python 进阶知识点精讲:上下文管理器(Context Manager)的原理与实战
python·pycharm