Ubuntu20.04+vscode的libtorch环境配置(跑起来测试demo)
初学,网上资料五花八门,又多又乱,查了很久资料才跑通,记录一下防止自己老年痴呆…
1.在pytorch官网找到libtorch,下载压缩文件,解压获得源码
官网下载
2.使用pytorch训练模型(前面可以都不看,就看模型怎么保存的)
if __name__ == '__main__':
model = torch.load('model/best_model.pth')
traced_script_module = torch.jit.trace(model, torch.rand(1, 10, 1))
traced_script_module.save('model/best_model.pt')
test()
3.准备好自己用pytorch训练好的模型,设置预先规定好的输入维度信息
#include <torch/script.h>
#include <iostream>
#include <memory>
int main() {
using torch::jit::script::Module;
Module module =
torch::jit::load("/home/coshe/PycharmProjects/LSTM_Test/model/best_model.pt");
std::cout << "ok\n";
std::vector<torch::jit::IValue> inputs;
inputs.push_back(torch::rand({1, 10, 1}));
std::cout << "inputs: " << std::endl;
std::cout << inputs << std::endl;
at::Tensor output = module.forward(inputs).toTensor();
std::cout << output << '\n';
}
如果有强迫症(比如我)受不了头文件<torch/script.h> 爆红,可以在vscode的c_cpp_properties.json 中手动写入头文件路径,什么?你找不到?快捷键Ctrl+ p,然后输入一个’>’,回车就是了,然后配置如下
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"/home/coshe/下载/libtorch/include"
],
"defines": [],
"compilerPath": "/usr/bin/clang",
"cStandard": "c11",
"cppStandard": "c++14",
"intelliSenseMode": "linux-clang-x64"
}
],
"version": 4
}
就把"includePath里面加一个libtorch的include路径就ok了"
4.CMakeLists.txt的编写
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(example)
set(Torch_DIR /home/coshe/下载/libtorch/share/cmake/Torch)
find_package(Torch REQUIRED)
add_executable(example example-app.cpp)
target_link_libraries(example ${TORCH_LIBRARIES})
set_property(TARGET example PROPERTY CXX_STANDARD 14)
然后就是
mkdir build && cd ./build
cmake ..
make -j8
./example
发现成功了,输出如下:
coshe@coshe-pc:~/文档/torch-cpp/libtorch_test/build$ ./example
ok
inputs:
(1,.,.) =
0.4012
0.3990
0.4569
0.0698
0.1218
0.2944
0.6884
0.9574
0.9151
0.4877
[ CPUFloatType{1,10,1} ]
0.9934
[ CPUFloatType{1,1} ]
进一步对api的学习移步大佬的博客
|