libtorch (pytorch c++) 教程(三)

这篇教程详细介绍了使用libtorch进行C++深度学习模型开发,涵盖MLP、CNN和LSTM的基本模块搭建,包括张量操作、模型构建、数据加载和各类模型的训练与预测。
摘要由CSDN通过智能技术生成

本教程分多个章节:

基本模块搭建

模块化编程的思想非常重要,通过模块化编程可以大幅减少重复的敲代码过程,同时代码可读性也会增加。本章将讲述如何使用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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值