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;
相关推荐
gz927cool16 分钟前
Python 全栈应用最佳实践完整指南
开发语言·python·ai
道尔柯南17 分钟前
C++ 内存管理详解:从 malloc/free 到 new/delete
c++·面试
東隅已逝,桑榆非晚22 分钟前
AVL数实现
c++·笔记·学习·算法
智购科技智能售货柜28 分钟前
顾客已经关门,视觉售货柜还在处理旧画面:延迟积压怎么查?~YH
python·单片机·嵌入式硬件·物联网·eclipse
梯度下降者35 分钟前
Python从0到100(三):Python中的变量介绍
python·作用域·变量·数据类型·计算机常识
思想觉悟38 分钟前
SEAndroid实战
android·linux·c++
AIFQuant39 分钟前
Python期货行情API接入:股指、黄金、原油多品种数据管道实战
开发语言·python·金融·区块链·量化开发
.YM.Z1 小时前
优选算法——【双指针算法2】C++实现
开发语言·c++·算法
思想觉悟1 小时前
Aosp开发磨刀石之ADB速查
android·c++
威哥爱编程1 小时前
Python 智能体开发实战 07:让它查课表它张口就编?给 Agent 接上真正能动手的工具
python·agent