
ResNet解决了深度CNN模型难训练的问题。
ResNet-18,ResNet-34,ResNet-50都可以用做CV中的图片特征提取器。

原始ResNet块(1x1卷积是通道数变化的作用)
果然是Conv->BN->ReLU的顺序。

我们也可以尝试各种架构的残差块,具体看实验效果,也学效果可能都差不多

ResNet在PyTorch的官方代码中共有5种不同深度的结构,深度分别为18、34、50、101、152(各种网络的深度指的是“需要通过训练更新参数”的层数,如卷积层,全连接层等),和论文完全一致。

class BasicBlock(nn.Module):expansion: int = 1def __init__(self,inplanes: int,planes: int,stride: int = 1,downsample: Optional[nn.Module] = None,groups: int = 1,base_width: int = 64,dilation: int = 1,norm_layer: Optional[Callable[..., nn.Module]] = None,) -> None:super().__init__()if norm_layer is None:norm_layer = nn.BatchNorm2dif groups != 1 or base_width != 64:raise ValueError("BasicBlock only supports groups=1 and base_width=64")if dilation > 1:raise NotImplementedError("Dilation > 1 not supported in BasicBlock")# Both self.conv1 and self.downsample layers downsample the input when stride != 1self.conv1 = conv3x3(inplanes, planes, stride)self.bn1 = norm_layer(planes)self.relu = nn.ReLU(inplace=True)self.conv2 = conv3x3(planes, planes)self.bn2 = norm_layer(planes)self.downsample = downsampleself.stride = stridedef forward(self, x: Tensor) -> Tensor:identity = xout = self.conv1(x)out = self.bn1(out)out = self.relu(out)out = self.conv2(out)out = self.bn2(out)if self.downsample is not None:identity = self.downsample(x)out += identityout = self.relu(out)return
不是的,Transformer用的只是残差的思想,只是把输入加到输出。而ResNet是把多个ResNet块堆叠起来的CNN模型,是用在CV领域的图片特征提取器。
一句话:梯度反向传播时,加深网络时,改用乘法,而不是加法。
这样的好处:通常在靠近输入层的参数通常是比较难训练的,因为拿到的梯度比较小。引入ResNet后,因为加入了跳转或者说高速公路,所以在算梯度的时候,底层W的梯度可以直接让loss从高速公路反传过来,就不需要一定把中间很多卷积层走完。所以说在一开始的时候,我最下面的层也会拿到比较大的梯度,就是因为我加入了高速公路。。。同样地,倒数第二层也可以通过它上层的高速公路得到参数更新。 因此无论你模型有多深,我下面的层都能做参数的更新。

Conv(浅蓝)-> BN(白色) -> ReLU(深蓝)