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;
相关推荐
Lucis__1 天前
STL设计模式探秘:容器适配器&仿函数
c++·容器·stl·仿函数
百锦再1 天前
第15章 并发编程
android·java·开发语言·python·rust·django·go
laufing1 天前
pyinstaller 介绍
python·构建打包
无敌最俊朗@1 天前
C++ 对象布局之padding(填充字节)
开发语言·c++
小龙报1 天前
《DevC++支持C++11等与其软件分辨率低的解决办法》
c语言·c++·windows·蓝桥杯·pat考试·学习方法·dvc++
谅望者1 天前
数据分析笔记09:Python条件语循环
笔记·python·数据分析
大佬,救命!!!1 天前
C++函数式策略模式中配置修改
c++·学习笔记·迭代加深·企业级·函数式策略模式·多文件编译环境·json环境配置修改
Chiang木1 天前
C++进阶:coroutine 协程
开发语言·c++·协程
Auspemak-Derafru1 天前
从U盘损坏中恢复视频文件并修复修改日期的完整解决方案
python
蕓晨1 天前
数据结构 图 的邻接表建立
数据结构·c++