【PyTorch】神经网络的基本骨架-nn.Module的使用以及convolution-layers卷积层介绍

11 篇文章 0 订阅
6 篇文章 0 订阅

前提文章目录

【PyTorch】深度学习PyTorch环境配置及安装【详细清晰】
【PyTorch】深度学习PyTorch加载数据
【PyTorch】关于Tensorboard的简单使用
【PyTorch】关于Transforms的简单使用
【PyTorch】关于torchvision中的数据集以及dataloader的使用


nn.Module的使用

nn:Neural network 神经网络
官网链接:https://pytorch.org/docs/1.8.1/nn.html
在这里插入图片描述
Containers骨架Module链接:https://pytorch.org/docs/1.8.1/generated/torch.nn.Module.html#torch.nn.Module
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
程序中的基本使用:
在这里插入图片描述

import torch
from torch import nn


# 创建神经网络模板   debug不会进行执行 除非调用它才会进行执行
class testModel(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, input):
        output = input + 1  # 给一个输入直接将其输出
        return output


# 创建神经网络
testModel = testModel()   #进行debug 这是程序的开始
x = torch.tensor(1.0)
output = testModel(x)
print(output)

在这里插入图片描述

convolution-layers卷积层

convolution-layers链接:https://pytorch.org/docs/1.8.1/nn.html#convolution-layers
在这里插入图片描述

Conv2d

链接:https://pytorch.org/docs/1.8.1/nn.functional.html#conv2d
在这里插入图片描述

参数介绍:

  • input:输入
  • weight:权重。卷积核
  • bias:偏置
  • stride:卷积核移动的步长。可以是一个数字或一个元组(sH、sW)。默认值:1 。 sH、sW :控制横向的移动和控制纵向的移动
  • padding:填充
  • dilation:扩张 。内核元素之间的间距
  • groups:组别

卷积后的输出计算:
Stride步长设置:
在这里插入图片描述
用程序计算表示:

import torch
import torch.nn.functional as F

# 输入数据是二维图像(2维矩阵)  看连续的([[)中括号数,有几个就是几维矩阵
input = torch.tensor([[1, 2, 0, 3, 1],  # 输入图像的第一行
                      [0, 1, 2, 3, 1],
                      [1, 2, 1, 0, 0],
                      [5, 2, 3, 1, 1],
                      [2, 1, 0, 1, 1]])

kernel = torch.tensor([[1, 2, 1],
                       [0, 1, 0],
                       [2, 1, 0]])

# print(input.shape)  # torch.Size([5, 5])   只有高和宽
# print(kernel.shape)  # torch.Size([3, 3])

# 因为文档的输入是需要四个参数  所以这里用torch提供的尺寸变换
# 要求的是一个输入,所以放入input
# (1,1,5,5):需要变换成的样子   batch_size为1:只取一个样本; channel为1:二维灰度图  5,5: 是5x5的图像输入
input = torch.reshape(input, (1, 1, 5, 5))
kernel = torch.reshape(kernel, (1, 1, 3, 3))

print(input.shape)  # torch.Size([1, 1, 5, 5])
print(kernel.shape)  # torch.Size([1, 1, 3, 3])

output = F.conv2d(input, kernel, stride=1)
print(output)

# 步长(步径)为2
output2 = F.conv2d(input, kernel, stride=2)
print(output2)

运行结果:
在这里插入图片描述
解释说明:
灰度图用2维矩阵表示,通道数channel为1。彩色图用3维矩阵表示,通道数为2。
在这里插入图片描述
padding填充设置:
在这里插入图片描述
程序计算:

# padding为1
output3 = F.conv2d(input, kernel, stride=1, padding=1)
print(output3)

输出结果:
在这里插入图片描述
可以看到输出结果的尺寸变大。

  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@¥文竹¥

你的鼓励是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值