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;
相关推荐
爱装代码的小瓶子3 分钟前
【C++与Linux进阶】详解信号的捕获:内核态和用户态的转换
linux·开发语言·c++
adore.9683 分钟前
3.09 复试学习
c++·学习·算法
小白学大数据16 分钟前
对比分析:Python爬虫模拟登录的3种主流实现方式
开发语言·爬虫·python·数据分析
与虾牵手16 分钟前
用 Python 从零搭一个能用的 AI Agent,踩完坑我总结了这套模板
python·aigc·ai编程
FriendshipT31 分钟前
YOLOs-CPP:一个免费开源的YOLO全系列C++推理库(以YOLO26为例)
c++·人工智能·yolo·目标检测·分类·开源
不想看见40432 分钟前
Shuffle an Array随机与取样--力扣101算法题解笔记
开发语言·c++·算法
一碗姜汤33 分钟前
torch.autograd.Function的apply()方法作用
人工智能·pytorch·深度学习
bu_shuo34 分钟前
Microsoft Visual C++的相关文件.sln
开发语言·c++·vc2010
AsDuang35 分钟前
Python 3.12 MagicMethods - 38 - __ifloordiv__
开发语言·python