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;
相关推荐
测试19982 分钟前
如何用appium搭建Android自动化测试框架?
自动化测试·软件测试·python·测试工具·职场和发展·appium·测试用例
程序员大雄学编程7 分钟前
微积分46. 无穷级数四大核心性质:从理论到实践的全方位解析
python·学习·微积分·学习工具
数字化转型分享点滴35 分钟前
## 工厂数字化管理系统的价值体现:构建制造全流程数据闭环
python
2301_800074211 小时前
map,list简单方法
windows·python·list
DeepVisionary2 小时前
30B 参数打平 1 万亿参数:Meta 开源 Muse Glimmer,跑分 35 对 36
python·自动化
Jialu.2 小时前
中文 BERT 多任务分类项目:从模型结构到训练细节
人工智能·pytorch·分类·微软·nlp·bert
吴声子夜歌3 小时前
Guava——基本工具(二)
windows·python·guava
码匠许师傅3 小时前
【设计模式精讲】14.外观模式(Facade)
c++·设计模式·uml·外观模式
用户8356290780514 小时前
使用 Python 管理 PDF 属性和元数据
后端·python
猎嘤一号4 小时前
【2026 最新】Windows 11 右键菜单还原为 Windows 10 经典样式:一条命令、原理、回退与新版说明
windows·python