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;
相关推荐
2401_892070986 小时前
【Linux C++ 日志系统实战】LogFile 日志文件管理核心:滚动策略、线程安全与方法全解析
linux·c++·日志系统·日志滚动
yuzhuanhei6 小时前
Visual Studio 配置C++opencv
c++·学习·visual studio
Csvn6 小时前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch89187 小时前
Python主流框架全解析
开发语言·python
不爱吃炸鸡柳7 小时前
C++ STL list 超详细解析:从接口使用到模拟实现
开发语言·c++·list
十五年专注C++开发7 小时前
RTTR: 一款MIT 协议开源的 C++ 运行时反射库
开发语言·c++·反射
sg_knight7 小时前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财7 小时前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
‎ദ്ദിᵔ.˛.ᵔ₎7 小时前
STL 栈 队列
开发语言·c++
龙文浩_7 小时前
AI中NLP的文本张量表示方法在自然语言处理中的演进与应用
人工智能·pytorch·深度学习·神经网络·自然语言处理