- 环境请参考上一篇
- cmakelists.txt
- TIPS
第一节:linux 开发AI算法以及libtorch部署算法详细教程-环境搭建
cmakelists.txtcmake_minimum_required (VERSION 3.8)
project(SOLDIER)
set(Torch_DIR "/libtorch/share/cmake/Torch")
set(PYTHON_EXECUTABLE "/usr/bin/python3")
find_package(Torch REQUIRED)
find_package(OpenCV REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
set(CMAKE_BUILD_TYPE Debug)
include_directories(${OpenCV_INCLUDE_DIRS})
add_executable(run main.cpp)
target_link_libraries(run "${OpenCV_LIBS}" "${TORCH_LIBRARIES}")
set_property(TARGET run PROPERTY CXX_STANDARD 14)
TIPS
#include#include #include #include #include // 选择GPU或CPU void chooseDevice() { torch::manual_seed(1); torch::DeviceType device_type; if (torch::cuda::is_available()) { std::cout << "CUDA available! Training on GPU." << std::endl; device_type = torch::kCUDA; } else { std::cout << "Training on CPU." << std::endl; device_type = torch::kCPU; } torch::Device device(device_type); } // 网络的定义 struct Net : torch::nn::Module { Net() : conv1(torch::nn::Conv2dOptions(1, 10, 5)), conv2(torch::nn::Conv2dOptions(10, 20, 5)), fc1(320, 50), fc2(50, 10) { register_module("conv1", conv1); register_module("conv2", conv2); register_module("conv2_drop", conv2_drop); register_module("fc1", fc1); register_module("fc2", fc2); } torch::Tensor forward(torch::Tensor x) { x = torch::relu(torch::max_pool2d(conv1->forward(x), 2)); x = torch::relu( torch::max_pool2d(conv2_drop->forward(conv2->forward(x)), 2)); x = x.view({-1, 320}); x = torch::relu(fc1->forward(x)); x = torch::dropout(x, 0.5, is_training()); x = fc2->forward(x); return torch::log_softmax(x, 1); } torch::nn::Conv2d conv1; torch::nn::Conv2d conv2; torch::nn::Dropout2d conv2_drop; torch::nn::Linear fc1; torch::nn::Linear fc2; }; int main() { chooseDevice(); Net model; // model.to(device); return 0; }



