本教程分多个章节:
- 第一章:开发环境搭建:VS+libtorch和Qt+libtorch
- 第二章:张量的常规操作
- 第三章:简单的CNN, MLP, LSTM模型搭建
- 第四章:数据加载模块使用
- 第五章:分类模型搭建,训练和预测
- 第六章:分割模型搭建,训练和预测
- 第七章:目标检测模型搭建,训练和预测
- 第八章:总结和展望
基本模块搭建
模块化编程的思想非常重要,通过模块化编程可以大幅减少重复的敲代码过程,同时代码可读性也会增加。本章将讲述如何使用libtorch搭建一些MLP和CNN的基本模块。
MLP基本单元
首先是线性层的声明和定义,包括初始化和前向传播函数。代码如下:
class LinearBnReluImpl : public torch::nn::Module{
public:
LinearBnReluImpl(int intput_features, int output_features);
torch::Tensor forward(torch::Tensor x);
private:
//layers
torch::nn::Linear ln{
nullptr};
torch::nn::BatchNorm1d bn{
nullptr};
};
TORCH_MODULE(LinearBnRelu);
LinearBnReluImpl::LinearBnReluImpl(int in_features, int out_features){
ln = register_module("ln", torch::nn::Linear(torch::nn::LinearOptions(in_features, out_features)));
bn = register_module("bn", torch::nn::BatchNorm1d(out_features));
}
torch::Tensor LinearBnReluImpl::forward(torch::Tensor x){
x = torch::relu(ln->forward(x));
x = bn(x);
return x;
}
在MLP的构造线性层模块类时,我们继承了torch::nn::Module类,将初始化和前向传播模块作为public,可以给对象使用,而里面的线性层torch::nn::Linear和归一化层torch::nn::BatchNorm1d被隐藏作为私有变量。
定义初始化函数时,需要将原本的指针对象ln和bn进行赋值,同时将两者的名称也确定。前向传播函数就和pytorch中的forward类似。
CNN基本单元
CNN的基本单元构建和MLP的构建类似,但是又稍有不同,首先需要定义的时卷积超参数确定函数。
inline torch::nn::Conv2dOptions conv_options(int64_t in_planes, int64_t out_planes, int64_t kerner_size,
int64_t stride = 1, int64_t padding = 0, bool with_bias = false) {
torch::nn::Conv2dOptions conv_options = torch::nn::Conv2dOptions(in_planes, out_planes, kerner_size);
conv_options.stride(stride);
conv_options.padding(padding);
conv_options.bias(with_bias);
return