编程基础很弱,需要机器学习,学习记录,按自己理解写的,希望以后能学懂吧,要是有大神看到还请赐教。
神经网络的基本骨架-nn.Module的使用
关于神经网络的一些工具在Pytorch官网帮助文档中torch.nn里面。
Containers:对神经网络定义了一些结构,在结构中添加一些内容就可以组成神经网络。
Containers包含六个模块:
Module,所有神经网络的一个基本类,为所有神经网络提供一个基本骨架,定义的神经网络都要从这个类中继承,小案例代码如下:
import torch.nn as nn
import torch.nn.functional as F
# 定义了一个神经网络名叫Model,它继承了Module这个类。
# 继承了一个类,相当于Model是Module的一个fu类。
# 相当于Module给所有神经网络提供了一个模板,我们继承它就是拿这个模板用来用,并对其中一些部分进行修改。
class Model(nn.Module):
# Module相当于买的玩具,Model相当于改装的玩具。
# 两个def相当于进行的改装。
def __init__(self):
super(Model, self).__init__()
self.conv1 = nn.Conv2d(1, 20, 5)
self.conv2 = nn.Conv2d(20, 20, 5)
def forward(self, x):
x = F.relu(self.conv1(x))
return F.relu(self.conv2(x))
写个例子看一下:
import torch
from torch import nn
# 定义一个神经网络名为Tudui继承于Module
class Tudui(nn.Module):
# 重写例子中的两个方法
# 方式1
def __init__(self):
super(Tudui, self).__init__()
# 方式2,借助Pycharm中的一些工具
# 说我没有打开要Copy的文件,这里就先手动挡。
def forward(self, input): # forward方法中要有一个input
output = input + 1 # input+1
return output # return出outpu
# 定义完神经网络模板,接下来创建神经网络
tudui = Tudui()
# 先定义一个输入x
x = torch.tensor(1.0)
# 将x输入到神经网络中
output = tudui(x)
print(output)
将断点打在tudui=Tudui()这一行,发现运行顺序:
首先跳到类的初始化,然后给x赋值,接着跳到forward中给x加1,然后return出来。
土堆说卷积操作(可选)
# 卷积操作
import torch
import torch.nn.functional as F
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)
print(kernel.shape)
# 尺寸变换
input = torch.reshape(input, (1, 1, 5, 5)) # 1batch,1通道,5*5
kernel = torch.reshape(kernel, (1, 1, 3, 3)) # 1batch,1通道,5*5
print(input.shape)
print(kernel.shape)
# 二维卷积输入要求(B,C,H,D)=(batch_size,channel,高度,宽度)
#不同stride效果
output = F.conv2d(input, kernel, stride=1)
print(output)
output2 = F.conv2d(input, kernel, stride=2)
print(output2)
#padding为填充
output3 = F.conv2d(input,kernel,stride=1,padding=1)
print(output3)
输出: