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;
相关推荐
ShineWinsu几秒前
对于Linux:自定义协议(基于TCP)实现网络计算器的解析
linux·网络·c++·网络协议·tcp/ip·面试·网络计算器
郝学胜-神的一滴7 分钟前
中级OpenGL教程 026:Assimp库从编译到实战全攻略
c++·unity·游戏引擎·图形渲染·unreal engine·opengl
今夜有雨.13 分钟前
C++JSON 解析器
c++·笔记·后端·学习·json
程序喵大人31 分钟前
【C++进阶】STL容器与迭代器 - 04 list 和 forward_list 用节点换稳定位置
开发语言·c++·list
phltxy34 分钟前
LangChain_Agent中间件实战
人工智能·python·深度学习·语言模型·中间件·langchain
axinawang42 分钟前
第14课:查找、统计、分割字符串
python
倒流时光三十年1 小时前
第一阶段 02 · Mapping 与数据类型(text vs keyword 是重点)
后端·python·django
小大宇1 小时前
python蓝图、拦截器、异常处理、redis队列、线程池、控制台及日志文件输出
python
喝茶与编码1 小时前
真实业务场景:高并发 Upsert 死锁频发?InnoDB 锁机制与重试机制深度解析
数据库·python
倒流时光三十年1 小时前
第一阶段 05 · Java 客户端查询类详解(Query / SearchCriteria / Response 与复杂拼接)
java·开发语言·python