讲解视频
https://www.bilibili.com/video/BV1z7411f7za?spm_id_from=333.999.0.0
关键代码
import torch.nn as nn
import torch
class AlexNet(nn.Module):
def __init__(self, num_classes=1000, init_weights=False):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 48, kernel_size=11, stride=4, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(48, 128, kernel_size=5, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(128, 192, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(192, 192, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(192, 128, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
)
self.classifier = nn.Sequential(
nn.Dropout(p=0.5),
nn.Linear(128 * 6 * 6, 2048),
nn.ReLU(inplace=True),
nn.Dropout(p=0.5),
nn.Linear(2048, 2048),
nn.ReLU(inplace=True),
nn.Linear(2048, num_classes),
)
if init_weights:
self._initialize_weights()
def forward(self, x):
outputs = []
for name, module in self.features.named_children():
x = module(x)
if name in ["0", "3", "6"]:
outputs.append(x)
return outputs
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
nn.init.constant_(m.bias, 0)
"""
@File : 123.py
@Time : 2021-12-08 21:18
@Author : XD
@Email : gudianpai@qq.com
@Software: PyCharm
"""
import torch
import torch.nn as nn
class TestModule(nn.Module):
def __init__(self):
super(TestModule, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(16, 32, 3, 1),
nn.ReLU(inplace=True)
)
self.layer2 = nn.Sequential(
nn.Linear(32, 10)
)
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
model = TestModule()
for name, module in model.layer1.named_children():
print('children module:', name)
print('module:', module)
children module: 0
module: Conv2d(16, 32, kernel_size=(3, 3), stride=(1, 1))
children module: 1
module: ReLU(inplace=True)
|