打印网络内的层名称与特征图大小
AlexNet 为例子
计算特征图大小的公式,池化与卷积都一样。
全连接的隐藏层数字设置的任意的。
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), # input[3, 224, 224] output[48, 55, 55] (224 - 11 + 2*2) / 4 +1 = 217 / 4 +1 = 55
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2), # output[48, 27, 27] (55 - 3) / 2 +1 = 52/2 +1 =26 +1
nn.Conv2d(48, 128, kernel_size=5, padding=2), # output[128, 27, 27]
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2), # output[128, 13, 13]
nn.Conv2d(128, 192, kernel_size=3, padding=1), # output[192, 13, 13]
nn.ReLU(inplace=True),
nn.Conv2d(192, 192, kernel_size=3, padding=1), # output[192, 13, 13]
nn.ReLU(inplace=True),
nn.Conv2d(192, 128, kernel_size=3, padding=1), # output[128, 13, 13]
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2), # output[128, 6, 6]
)
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):
# 运行使用 效率高
x = self.features(x)
x = torch.flatten(x, start_dim=1)
x = self.classifier(x)
# 调试使用 方便查看 效率低
# print("输入特征图大小:", x.shape)
# for i, layer in enumerate(self.features):
# x = layer(x)
# print(f"第 {i + 1} 个 features 层({layer.__class__.__name__})输出特征图大小:", x.shape)
# x = torch.flatten(x, start_dim=1)
# print("展平后特征图大小:", x.shape)
# for i, layer in enumerate(self.classifier):
# x = layer(x)
# print(f"第 {i + 1} 个 classifier 层({layer.__class__.__name__})输出特征图大小:", x.shape)
return x
# 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)
# 创建 AlexNet 模型实例
model = AlexNet()
# 生成随机输入数组,模拟输入图像数据
# 输入形状为 [batch_size, channels, height, width]
# 这里假设 batch_size 为 1,通道数为 3,图像大小为 224x224
input_tensor = torch.randn(1, 3, 224, 224)
# 进行前向传播
try:
output = model(input_tensor)
print("测试通过,网络未报错。")
print("输出形状:", output.shape)
except Exception as e:
print("测试失败,网络报错:", e)