模块Module
为所有神经网络提供基本类
继承nn.Module类
1.初始化函数
2.前向传播函数(x先进性一个卷积1,在进行relu激活函数非线性处理。再进行一个卷积一个非线性处理)
搭建神经网络
#神经网络的搭建
import torch
from torch import nn
class Tudui(nn.Module): #创建类(继承)
def __init__(self): #重写两个方法
super(Tudui,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))
def forward(self,input): #举例简单的forward函数
output = input + 1
return output
tudui =Tudui()
x = torch,tensor(1.0)
output = tudui(x)
print(output)
#卷积层convolution layers
#nn.conv2d 二维的(图片)
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]])
#调整尺寸
input = torch.reshape(input,(1,1,5,5)) #bitch_size =1,1通道。5×5
kernel = torch.reshape(kernel,(1,1,3,3))
print(input.shape) #输入是5x5,卷积核是3x3
print(kernel.shape) #改变尺寸前不满足要求(要求四个数字的尺寸)
#输出
#torch.Size([1, 1, 5, 5])
#torch.Size([1, 1, 3, 3])
output = F.conv2d(input,kernel,stride = 1)
print(output)
输出:
torch.Size([1, 1, 5, 5]) torch.Size([1, 1, 3, 3]) tensor([[[[10, 12, 12],
[18, 16, 16], [13, 9, 3]]]])
改变步长为2