pytorch 从python 转 c++涉及到的数据保存加载问题
1. torch.nn.Module 保存 state_dict 无法被 c++访问,只能转化为 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++代码
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;
}
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代码文章来源:https://www.toymoban.com/news/detail-645854.html
data = torch.ones(3, 4)
torch.save(data, "data.pkl")
c++代码文章来源地址https://www.toymoban.com/news/detail-645854.html
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;
到了这里,关于pytorch从python转 c++涉及到的数据保存加载问题;libtorch的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!