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;
相关推荐
hansang_IR12 小时前
【题解】[COCI 2024/2025 #2] 流明 / Blistavost
c++·算法·动态规划·dp
卷无止境12 小时前
Python 装饰器:给函数穿件"外套",到底难在哪?
后端·python
程序喵大人12 小时前
【C++进阶】STL算法与函数对象 - 01 让算法去处理一段迭代器范围
开发语言·c++·算法·函数对象
大地之灯12 小时前
从零做一个自己的 CLI
python·agent
gugucoding12 小时前
34.【Java】I/O流(下):NIO与文件操作
java·python·nio
cui_ruicheng13 小时前
Python数据分析(十三):Seaborn 统计可视化
开发语言·python·信息可视化·数据分析
如此这般英俊13 小时前
手搓Claude Code-第十章 system_prompt
数据结构·人工智能·python·语言模型·自然语言处理·prompt
高洁0113 小时前
VLA:驱动具身智能迈向通用的关键引擎
人工智能·python·深度学习·transformer·知识图谱
糖炒栗子032613 小时前
RF-DETR + DeepSpeed 双节点集群训练环境搭建操作记录
python
今天AI了吗13 小时前
【AI智能体】Hermes Agent 从部署到项目实战操作详解
java·人工智能·python·milvus