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

前提文章目录

【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



程序中的基本使用:

python 复制代码
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步长设置:

用程序计算表示:

python 复制代码
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填充设置:

程序计算:

python 复制代码
# padding为1
output3 = F.conv2d(input, kernel, stride=1, padding=1)
print(output3)

输出结果:

可以看到输出结果的尺寸变大。

相关推荐
飞哥数智坊32 分钟前
五一必备:手把手教你“即梦”APP轻松生成精美海报
人工智能
OpenLoong 开源社区1 小时前
技术视界 | 从自然中获取智慧: 仿生机器人如何学会“像动物一样思考和行动”
人工智能
HHONGQI1231 小时前
嵌入式人工智能应用-第三章 opencv操作8 图像特征之 Haar 特征
人工智能·opencv·计算机视觉
Ai多利1 小时前
顶会招牌idea:机器学习+组合优化 优秀论文合集
人工智能·机器学习·组合优化
jerwey1 小时前
Stable Diffusion:Diffusion Model
人工智能·stable diffusion
尼罗河女娲1 小时前
深度剖析RLHF:语言模型“类人输出”的训练核心机制
人工智能·深度学习·语言模型
吴佳浩2 小时前
Python入门指南(四)-项目初始化
人工智能·后端·python
万事可爱^2 小时前
TensorFlow 安装全攻略
人工智能·python·深度学习·机器学习·tensorflow·tensorflow安装
yc_232 小时前
KAG:通过知识增强生成提升专业领域的大型语言模型(二)
人工智能·语言模型·自然语言处理