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;
相关推荐
weixin_307779133 分钟前
C++代码实现MATLAB中的pade函数功能
开发语言·c++·算法·matlab
数字融合4 分钟前
透明化数字孪生智慧养老平台运维服务项目
人工智能·python·virtualenv
smj2302_796826525 分钟前
解决leetcode第4064题至多一次取反能被k整除的最长子数组II
python·算法·leetcode
神仙别闹27 分钟前
基于C++实现的(控制台)学校开课查询系统
开发语言·c++
Dylan的码园1 小时前
A+B问题 进制处理【逻辑控制 运算符】
c++·算法
happylifetree1 小时前
Python01-08:练习
python
空奈qwq1 小时前
ANN 全连接神经网络入门指南:从神经元到深度学习的第一步
人工智能·python·深度学习·神经网络·算法·机器学习
CAE虚拟与现实1 小时前
PyTorch和scikit-learn的区别
人工智能·pytorch·scikit-learn
hetao17338371 小时前
2026-09-27~28 hetao1733837 的刷题记录
c++·算法
2601_962218611 小时前
C++的几种编译器的实现
开发语言·c++