資源簡介
圖片分類,圖像識別,目標檢測的resnet50,python實現。
代碼片段和文件信息
import?torch.nn?as?nn
import?math
import?torch.utils.model_zoo?as?model_zoo
class?Bottleneck(nn.Module):???????????#預定義網絡架構并定義前向傳播
expansion?=?4??????#expansion是指殘差塊輸出維度是輸入維度的多少倍。在ResNet類中的_make_layer函數中會用到
def?__init__(selfin_planesplanesstride=1downsample=None):??#初始化并繼承nn.Module中的一些屬性。in_planes指輸入的通道數,planes指輸出的通道數,步長默認為1,下采樣函數默認為空(即默認不需要下采樣)
super(Bottleneckself).__init__()??#定義nn.Module的子類Bottleneck。并在下面給出新的屬性
self.conv1?=?nn.Conv2d(in_planesplaneskernel_size=1bias=False)
self.bn1?=?nn.BatchNorm2d(planes)??#歸一化處理
self.conv2?=?nn.Conv2d(in_planesplaneskernel_size=3stride=stridepadding=1bias=False)??#stride默認為1,但可更改
self.bn2?=?nn.BatchNorm2d(planes)
self.conv3?=?nn.Conv2d(in_planesplanes*4kernel_size=1bias=False)??#第三次卷積輸出緯度為上一層的四倍
self.bn3?=?nn.BatchNorm(planes*4)
self.relu?=?nn.ReLU(inplace=True)
self.downsample?=?downsample
self.stride=stride
def?forwar(selfx): ?#前向傳播
residual?=?x?????????
? out?=?self.conv1(x)
out?=?self.bn1(out)
out?=?self.conv2(out)
out?=?self.bn2(out)
out?=?self.conv3(out)
out?=?self.bn3(out)
if?self.downsample?is?not?None:???# 用來處理H(x)?=?F(x)?+?x中?F(x)和x維度(高、寬、通道數)不匹配的問題
self.downsample?=?downsample(x)
? out?+=?residual
? out?=?self.relu(out)
return?out
class?ResNet(nn.Module):
def?__init__(selfblocklayersnum_classes=1000):??#block即為Bottleneck模型,layers可控制傳入的Bottleneck
selfinplanes?=?64???#初始輸入通道數為64
super(ResNetself).__init__()???#可見ResNet也是nn.Module的子類
self.conv1?=?nn.Conv2d(364kernel_size?=?7stride?=?2padding?=?3bias?=?False)
self.bn1?=?nn.BatchNorm2d(64)
self.relu?=?nn.ReLU(inplace?=?True)
self.maxpool?=?nn.MaxPool2d(kernel_size?=?3stride?=?2padding?=?1)
self.layer1?=?self._make_layer(block64layers[0])???# 四層殘差塊64為這一層輸入的通道數layer[0]表示有幾個殘差塊
self.layer2?=?self._make_layer(block128layers[1]stride?=?2)???
self.layer3?=?self._make_layer(block256layers[2]stride?=?2)
self.layer4?=?self._make_layer(block512layers[3]
評論
共有 條評論