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;
相关推荐
FriendshipT几秒前
Ultralytics:解读CBLinear模块
人工智能·pytorch·python·深度学习·目标检测
AI开发发烧友24 分钟前
LangGraph多Agent协作实战:以物流售前场景为例的5 Agent工作流设计
python
码云骑士28 分钟前
70-多Agent协作-CrewAI-AutoGen-角色分工与信息传递协议
python
郝学胜-神的一滴1 小时前
中级OpenGL教程 022:探秘三维世界的血脉传承——物体父子关系与矩阵递归奥义
c++·线性代数·unity·矩阵·游戏引擎·unreal engine·opengl
Hachi被抢先注册了1 小时前
Skills总结
python
用户0332126663671 小时前
使用 Python 在 PowerPoint 中创建折线图和条形图
python
benchmark_cc1 小时前
如何用 Python 进行多周期 K 线合成与时区对齐?基于 QuantDash 与 Pandas 的量化数据清洗实战(附 GitHub 源码)
开发语言·python·github·盯盘·pandas·quantdash·量化数据
不如语冰1 小时前
AI大模型入门-参数的传递
数据结构·人工智能·pytorch·python
用户6760840656171 小时前
GraphBLAS_01_图的稀疏表示
python
m沐沐1 小时前
【深度学习】深入理解长短期记忆网络 LSTM
人工智能·pytorch·深度学习·神经网络·lstm