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;
相关推荐
smj2302_796826522 分钟前
解决leetcode第3777题使子字符串变交替的最少删除次数
python·算法·leetcode
ULTRA??15 分钟前
Informed RRT*实现椭圆启发式采样
c++·算法
CoderCodingNo28 分钟前
【GESP】C++一级真题 luogu-B4410 [GESP202509 一级] 金字塔
开发语言·c++
超级大福宝28 分钟前
C++中1 << 31 - 1相当于INT_MAX吗?
c语言·c++
0思必得029 分钟前
[Web自动化] CSS基础概念和介绍
前端·css·python·自动化·html·web自动化
计算机徐师兄32 分钟前
Python基于Django的MOOC线上课程推荐数据分析与可视化系统(附源码,文档说明)
python·数据分析·django·慕课线上课程推荐·慕课线上课程推荐可视化系统·pytho线上课程推荐可视化·线上课程推荐数据分析可视化系统
free-elcmacom34 分钟前
Python实战项目<2>使用Graphviz绘制流程框图
开发语言·python·graphviz
ljuncong41 分钟前
python的装饰器怎么使用
开发语言·python
alibli42 分钟前
一文学会设计模式之结构型模式及最佳实现
c++·设计模式
A7bert77742 分钟前
【YOLOv5seg部署RK3588】模型训练→转换RKNN→开发板部署
linux·c++·人工智能·深度学习·yolo·目标检测