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;
相关推荐
憧憬成为原神糕手14 分钟前
c++_list
开发语言·c++
zyh2005043015 分钟前
c++的decltype关键字
c++·decltype
测试老哥16 分钟前
功能测试干了三年,快要废了。。。
自动化测试·软件测试·python·功能测试·面试·职场和发展·压力测试
爱吃油淋鸡的莫何16 分钟前
Conda新建python虚拟环境问题
开发语言·python·conda
闲人编程24 分钟前
Python实现日志采集功能
开发语言·python·fluentd·filebeat·日志采集
2401_8628867833 分钟前
蓝禾,汤臣倍健,三七互娱,得物,顺丰,快手,游卡,oppo,康冠科技,途游游戏,埃科光电25秋招内推
前端·c++·python·算法·游戏
luthane35 分钟前
python 实现armstrong numbers阿姆斯壮数算法
python·算法
昕er1 小时前
Python 中自动打开网页并点击[自动化脚本],Selenium
python·selenium·自动化
风控牛1 小时前
【chromedriver编译-绕过selenium机器人检测】
java·python·selenium·测试工具·安全·机器人·行为验证