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;
相关推荐
用户019027581618 分钟前
用 Polars 快速分析 A 股 K 线:比 pandas 更快的列式处理
python
用户03321266636716 分钟前
使用 Python 轻松加密或解密 Excel 文档
python·excel
沫璃染墨28 分钟前
从零入门计算机网络系列(十八):TCP连接管理详解——从三次握手与四次挥手到TIME_WAIT机制
运维·服务器·网络·c++·网络协议·tcp/ip·tcp
CyrusYiVPP1 小时前
手写 MCP Server:给问答机器人接上本地文件工具,Python 实战第 13 期
人工智能·python
特立独行的猫A2 小时前
cj-tauri:用仓颉写桌面与鸿蒙 PC 应用
java·后端·python
自信150413057592 小时前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
ShineWinsu5 小时前
对于Qt:QDial常见属性以及信号的解析
开发语言·c++·qt·gui·客户端·旋钮·qdial
qq_1588954111110 小时前
AI 音乐生成完成后,音频 URL 为什么会过期?一套可恢复的交付方案
python·api·ai音乐
Warson_L12 小时前
高性能架构设计
python·go
科技苑13 小时前
C++ CAS与ABA问题详解,无锁编程的经典陷阱怎么解决?
c++·人工智能