提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
如果对卷积层和卷积不是很了解的可以去看博主之前的文章:
卷积到底卷了个啥?五千字详细介绍数学卷积、图像卷积和卷积神经网络的卷积
#导包
import torch.nn as nn
import torch.nn.functional as F
# 创类
class Model(nn.Module):
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))
2维卷积
conv2d(input: Tensor,
weight: Tensor,
bias: Tensor | None = None,
stride: int | Size | list[int] | tuple[int, …] = 1,
padding: str = “valid”,
dilation: int | Size | list[int] | tuple[int, …] = 1,
groups: int = 1) -> Tensor)
#导包
import torch.nn.functional as F
import torch
#设置输入矩阵
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))
kernel = torch.reshape(kernel,(1,1,3,3))
#调用函数
output = F.conv2d(input,kernel,stride=1)
print(output)
'''
tensor([[[[10, 12, 12],
[18, 16, 16],
[13, 9, 3]]]])
'''
import torchvision
import torch
from torch import nn
from torch.nn import Conv2d
from torch.utils.data import DataLoader
# 从官网下载数据
dataset = torchvision.datasets.CIFAR10('./dataset/CIFAR10',transform=torchvision.transforms.ToTensor(),download=True)
# 加载数据
dataloader = DataLoader(dataset,batch_size=64)
# 构建网络
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv1 = Conv2d(in_channels=3,out_channels=6,kernel_size=3,stride=1,padding=0)
# 向前传播
def forward(self,x):
x = self.conv1(x)
return x
# 实例化网络
model = Model()
#对数据进行卷积
for data in dataloader:
img,target = data
output = model(img)
print(output.shape)