文章目录
上课笔记
可以设置padding=‘same’ 使输入输出大小一致
10.1GoogleNet(Inception 层)
说明:Inception Moudel
1、卷积核超参数选择困难(提供四条变换路线输出要保证宽高一致,把结果concatenate到一起,效率高的权重大),自动找到卷积的最佳组合。
2、1x1卷积核,不同通道的信息融合。使用1x1卷积核虽然参数量增加了,但是能够显著的降低计算量(operations)
3、Inception Moudel由4个分支组成,要分清哪些是在Init里定义,哪些是在forward里调用。4个分支在dim=1(channels)上进行concatenate。24+16+24+24 = 88
4、GoogleNet的Inception(Pytorch实现)
下面是1*1卷积核计算过程
在5 *5 的卷积之前先进行一个1 * 1的卷积能有效降低运算量
比如:192 * 28 * 28经过一个5 * 5的卷积得到 32 * 28 * 28的输出运算为:
5^2 * 28 ^2 * 192 * 32=120422400
而中间先经过一个1 * 1的卷积再经过一个5 * 5的卷积得到 32 * 28 * 28的输出运算为:1^2 * 28^2 * 192 * 16 + 5^2 + 28^2 * 16 * 32 = 12433648
少了十倍
1*1卷积的主要作用有以下几点:
1、降维。比如,一张500 * 500且厚度depth为100 的图片在20个filter上做11的卷积,那么结果的大小为500500*20。
2、加入非线性。卷积层之后经过激励层,1*1的卷积在前一层的学习表示上添加了非线性激励,提升网络的表达能力;
3、增加模型深度。可以减少网络模型参数,增加网络层深度,一定程度上提升模型的表征能力。
self.branch1x1 = nn.Conv2d(in_channels, 16, kernel_size=1) self.branch5x5_1 = nn.Conv2d(in_channels, 16, kernel_size=1) self.branch5x5_2 = nn.Conv2d(16, 24, kernel_size=5, padding=2) self.branch3x3_1 = nn.Conv2d(in_channels, 16, kernel_size=1) self.branch3x3_2 = nn.Conv2d(16, 24, kernel_size=3, padding=1) self.branch3x3_3 = nn.Conv2d(24, 24, kernel_size=3, padding=1) self.branch_pool = nn.Conv2d(in_channels, 24, kernel_size=1)
把上面四个卷积出的通道聚合(Concatenate),输出
outputs = [branch1*1, branch5*5, branch3*3, branch_pool]` return torch.cat(outputs, dim=1)#沿着通道c拼接起来 维度=1
张量的维度是(b, c, h, w) batch, channel, width, height
代码实现
import torch import torch.nn as nn from torchvision import transforms from torchvision import datasets from torch.utils.data import DataLoader import torch.nn.functional as F import torch.optim as optim # prepare dataset batch_size = 64 transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) # 归一化,均值和方差 train_dataset = datasets.MNIST(root='../dataset/mnist/', train=True, download=True, transform=transform) train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size) test_dataset = datasets.MNIST(root='../dataset/mnist/', train=False, download=True, transform=transform) test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size) # design model using class class InceptionA(nn.Module): def __init__(self, in_channels): super(InceptionA, self).__init__() self.branch1x1 = nn.Conv2d(in_channels, 16, kernel_size=1) self.branch5x5_1 = nn.Conv2d(in_channels, 16, kernel_size=1) self.branch5x5_2 = nn.Conv2d(16, 24, kernel_size=5, padding=2) self.branch3x3_1 = nn.Conv2d(in_channels, 16, kernel_size=1) self.branch3x3_2 = nn.Conv2d(16, 24, kernel_size=3, padding=1) self.branch3x3_3 = nn.Conv2d(24, 24, kernel_size=3, padding=1) self.branch_pool = nn.Conv2d(in_channels, 24, kernel_size=1) def forward(self, x): branch1x1 = self.branch1x1(x) branch5x5 = self.branch5x5_1(x) branch5x5 = self.branch5x5_2(branch5x5) branch3x3 = self.branch3x3_1(x) branch3x3 = self.branch3x3_2(branch3x3) branch3x3 = self.branch3x3_3(branch3x3) branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) branch_pool = self.branch_pool(branch_pool) outputs = [branch1x1, branch5x5, branch3x3, branch_pool] return torch.cat(outputs, dim=1) # b,c,w,h c对应的是dim=1 class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(88, 20, kernel_size=5) # 88 = 24x3 + 16 self.incep1 = InceptionA(in_channels=10) # 与conv1 中的10对应 self.incep2 = InceptionA(in_channels=20) # 与conv2 中的20对应 self.mp = nn.MaxPool2d(2) self.fc = nn.Linear(1408, 10) def forward(self, x): in_size = x.size(0) x = F.relu(self.mp(self.conv1(x))) x = self.incep1(x) x = F.relu(self.mp(self.conv2(x))) x = self.incep2(x) x = x.view(in_size, -1) x = self.fc(x) return x model = Net() # construct loss and optimizer criterion = torch.nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5) # training cycle forward, backward, update def train(epoch): running_loss = 0.0 for batch_idx, data in enumerate(train_loader, 0): inputs, target = data optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, target) loss.backward() optimizer.step() running_loss += loss.item() if batch_idx % 300 == 299: print('[%d, %5d] loss: %.3f' % (epoch + 1, batch_idx + 1, running_loss / 300)) running_loss = 0.0 def test(): correct = 0 total = 0 with torch.no_grad(): for data in test_loader: images, labels = data outputs = model(images) _, predicted = torch.max(outputs.data, dim=1) total += labels.size(0) correct += (predicted == labels).sum().item() print('accuracy on test set: %。3f %% ' % (100 * correct / total)) if __name__ == '__main__': for epoch in range(10): train(epoch) test()
10.2 Residual Net
知识点:残差层定义
问题描述:卷积核层数不是越深越好,可能存在梯度消失
主要思路:引入残差连接,拼接后再激活,计算梯度的时候就能有所保留,要求输入输出大小相同
代码实现:定义残差块类,指定输入通道数,跳转拼接后再激活。模型构建时再定义相关层
跳连接:将H(x)的输入再加一个x,求导的时候x`=1,那么就算梯度很小也是将近于1,多个这样的数相乘梯度还是不为0,能解决梯度消失的情况,其中F(x)和x应该尺寸相同。
class ResidualBlock(torch.nn.Module): def __init__(self, channels): super(ResidualBlock,self).__init__() self.channels = channels # 过残差连接输入输出通道不变 self.conv1 = torch.nn.Conv2d(channels, channels, 3,padding=1)#padding=1使得F(x)和x应该尺寸相同 self.conv2 = torch.nn.Conv2d(channels, channels, 3,padding=1) def forward(self, x): y = F.relu(self.conv1(x)) y = self.conv2(y) return F.relu(x + y) # 先求和再激活
1.看一些深度学习理论方面的书比如花书
2.阅读pytorch文档,至少通读一遍
3.复现经典工作:先读代码,训练架构,测试架构,数据读取架构,损失函数怎么构建的,根据论文讲的东西自己去写
4.选一个特定领域阅读大量论文,看一下大家在设计网络的时候都用了什么技巧,想创新点
代码实现
import torch from torchvision import datasets from torch.utils.data import DataLoader from torchvision import transforms import torch.nn.functional as F # 1.数据集准备 batch_size = 64 transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) train_dataset = datasets.MNIST(root='../dataset/minist', train = True, download=True, transform=transform) train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=2) test_dataset = datasets.MNIST(root='../dataset/minist', train = False, download=True, transform=transform) test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size, num_workers=2) # 2.模型构建 class ResidualBlock(torch.nn.Module): def __init__(self, channels): super(ResidualBlock,self).__init__() self.channels = channels # 过残差连接输入输出通道不变 self.conv1 = torch.nn.Conv2d(channels, channels, 3,padding=1) self.conv2 = torch.nn.Conv2d(channels, channels, 3,padding=1) def forward(self, x): y = F.relu(self.conv1(x)) y = self.conv2(y) return F.relu(x + y) # 先求和再激活 class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() self.c1 = torch.nn.Conv2d(1, 16, 5) self.c2 = torch.nn.Conv2d(16, 32, 5) self.rblock1 = ResidualBlock(16) # 与conv1 中的16对应 self.rblock2 = ResidualBlock(32) # 与conv2 中的32对应 self.mp = torch.nn.MaxPool2d(2) # 图像缩小一半 12 (不要改步长啊) self.l = torch.nn.Linear(512, 10) def forward(self, x): batch = x.size(0) x = torch.relu(self.mp(self.c1(x))) # b*10*12*12 x = self.rblock1(x) x = torch.relu(self.mp(self.c2(x))) # b*20*4*4 x = self.rblock2(x) x = x.view(batch, -1) # print(x.shape) return self.l(x) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = Net().to(device) # # 创建一个示例图像查看模型输出shape(好给全连接层赋值)----->输出:torch.Size([1, 1408]) # sample_image = torch.randn(1, 1, 28, 28) # 1张图像,1个通道,28x28大小的图像 # output = model(sample_image) # 3.损失函数和优化器 criterion = torch.nn.CrossEntropyLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # 4.训练 def train(epoch): running_loss = 0.0 for batch_idex, (x, y) in enumerate(train_loader): x, y = x.to(device), y.to(device) y_pred = model(x) optimizer.zero_grad() loss = criterion(y_pred, y) running_loss += loss.item() loss.backward() optimizer.step() if batch_idex % 300 == 299: print(f'epoch{epoch+1}--------batch{batch_idex+1}-------loss={round(running_loss/300, 3)}') running_loss = 0.0 def test(): total = 0 acc = 0 with torch.no_grad(): for (x, y) in test_loader: x, y = x.to(device), y.to(device) y_pred = model(x) total += y_pred.size(0) _, predicted = torch.max(y_pred, dim=1) acc += (predicted == y).sum().item() print('test= %.3f %%' % (100 * acc/total)) if __name__ == '__main__': for epoch in range(10): train(epoch) test()
练习:阅读Identity Mappings in Deep Residual Networks,Densely Connected Convolutional Networks,实现相关网络用minist数据集测试