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;
相关推荐
知然17 分钟前
鸿蒙 Native API 的封装库 h2lib_arkbinder
c++·arkts·鸿蒙
Roc-xb25 分钟前
/etc/profile.d/conda.sh: No such file or directory : numeric argument required
python·ubuntu·conda
十五年专注C++开发42 分钟前
Qt .pro配置gcc相关命令(三):-W1、-L、-rpath和-rpath-link
linux·运维·c++·qt·cmake·跨平台编译
KENYCHEN奉孝1 小时前
PyTorch 实现 MNIST 手写数字识别
人工智能·pytorch·深度学习
Cai junhao1 小时前
【Qt】Qt控件
开发语言·c++·笔记·qt
uyeonashi1 小时前
【QT系统相关】QT网络
开发语言·网络·c++·qt
世由心生1 小时前
[从0到1]环境准备--anaconda与pycharm的安装
ide·python·pycharm
苏苏susuus2 小时前
深度学习:PyTorch自动微分模块
人工智能·pytorch·深度学习
猛犸MAMMOTH2 小时前
Python打卡第54天
pytorch·python·深度学习
梓羽玩Python3 小时前
12K+ Star的离线语音神器!50MB模型秒杀云端API,隐私零成本,20+语种支持!
人工智能·python·github