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;
相关推荐
吴梓穆13 小时前
Python 基础 正则表达式
python
盐焗鹌鹑蛋13 小时前
【C++】C++11:列表初始化、声明、STL升级
c++
巧克力男孩dd13 小时前
Python超典型练习题(第一次作业)
开发语言·python·算法
闲猫14 小时前
LangChain / Core components / Models
开发语言·python·langchain
ComputerInBook14 小时前
c 和 c++ 中的宏块(macro)
c语言·c++··宏块·宏指令
AA陈超15 小时前
004 T02 - 俯视角摄像机系统 设计文档
网络·c++·ue5·虚幻引擎
bu_shuo15 小时前
c与cpp中的argc和argv
c语言·c++·算法
蓝创精英团队15 小时前
VCPKG 跨平台C++ 库管理器
c++·vcpkg
cui_ruicheng16 小时前
Python从入门到实战(十三):模块、包与环境管理
开发语言·python
Jayden_Ruan17 小时前
C++组合的输出
c++·算法·深度优先