1.对CIFAR10数据集进行分类
2.如何设置卷积的参数?
打开官方文档中对应的功能,
例如conv2d
将已知参数代入求未知参数。
3.网络的搭建
class Tudui(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, padding=2) # ?参数选取:参考公式
self.maxpool1 = nn.MaxPool2d(kernel_size=2)
self.conv2 = nn.Conv2d(32, 32, 5, padding=2)
self.maxpool2 = nn.MaxPool2d(2)
self.conv3 = nn.Conv2d(32, 64, 5, padding=2)
self.maxpool3 = nn.MaxPool2d(2)
self.flatten = nn.Flatten()
self.linear1 = nn.Linear(1024, 64) # ?如何查看展平后的数据个数
self.linear2 = nn.Linear(64, 10)
def forward(self, x):
x = self.conv1(x)
x = self.maxpool1(x)
x = self.conv2(x)
x = self.maxpool2(x)
x = self.conv3(x)
x = self.maxpool3(x)
x = self.flatten(x)
x = self.linear1(x)
x = self.linear2(x)
return x
4.检查网络结构是否正确
tudui = Tudui()
# 检查模型搭建的正确性
input = torch.ones((64, 3, 32, 32)) # 指定大小,64个图片,3通道,32*32像素大小
output = tudui(input)
print(output.shape)
输出
符合构造的结构
5.sequential的使用
作用:简化构造的过程,看起来更简洁
class Tudui(nn.Module):
def __init__(self):
super().__init__()
self.model = Sequential(
nn.Conv2d(3, 32, 5, padding=2),
nn.MaxPool2d(2),
nn.Conv2d(32, 32, 5, padding=2),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 5, padding=2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(1024, 64),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.model(x)
return x
6. 查看数据的处理过程
# 查看过程
writer = SummaryWriter('../Logs_seq')
writer.add_graph(tudui, input)
writer.close()
过程图