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;
相关推荐
ahead~17 分钟前
【大模型入门】访问GPT_API实战案例
人工智能·python·gpt·大语言模型llm
眠りたいです23 分钟前
Mysql常用内置函数,复合查询及内外连接
linux·数据库·c++·mysql
笑鸿的学习笔记1 小时前
qt-C++语法笔记之Stretch与Spacer的关系分析
c++·笔记·qt
大模型真好玩1 小时前
准确率飙升!GraphRAG如何利用知识图谱提升RAG答案质量(额外篇)——大规模文本数据下GraphRAG实战
人工智能·python·mcp
19891 小时前
【零基础学AI】第30讲:生成对抗网络(GAN)实战 - 手写数字生成
人工智能·python·深度学习·神经网络·机器学习·生成对抗网络·近邻算法
hardStudy_h1 小时前
C++——内联函数与Lambda表达式
开发语言·jvm·c++
applebomb1 小时前
没合适的组合wheel包,就自行编译flash_attn吧
python·ubuntu·attention·flash
Chasing__Dreams2 小时前
python--杂识--18.1--pandas数据插入sqlite并进行查询
python·sqlite·pandas
ZZZS05162 小时前
stack栈练习
c++·笔记·学习·算法·动态规划
位东风2 小时前
【c++学习记录】状态模式,实现一个登陆功能
c++·学习·状态模式