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;
相关推荐
230万光年的思念16 分钟前
分子动力学模拟参考文献
python
HongXu_CaiYi1 小时前
0103-python相关-函数、文件
python
加油码1 小时前
动静态库的链接底层原理(进阶版)
linux·c++
一木 之林1 小时前
三、内存管理、指针与堆栈
c语言·jvm·c++
vortex52 小时前
从Conda到UV:Python项目依赖管理的现代演进
python·conda·uv
何以解忧,唯有..2 小时前
Python time 模块详解:时间处理与日期操作指南
开发语言·python
梅雅达编程笔记2 小时前
Day 18 · 综合实战 B:AI 客服 Agent(专栏收官)
python·智能客服·ai agent·意图识别·ai客服·大模型应用·ai办公自动化
初夏睡觉2 小时前
原创题目 - 空壳恋爱
c++·算法·dp·oi·信息学·原创题目·值得挑战的题目
间歇性努力持续性发呆的野生快乐选手3 小时前
stl容器使用和算法简介
数据结构·c++
测试老哥3 小时前
Pytest自动化测试框架tep环境变量、fixtures、用例三者之间的关系
自动化测试·软件测试·python·测试工具·测试用例·pytest·职场发展