当前位置: 首页 > news >正文

打印网络内的层名称与特征图大小

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)

相关文章:

  • 数据操作语言
  • 初探:OutSystems的运行原理是什么?
  • R语言赋能气象水文科研:从多维数据处理到学术级可视化
  • Python爬虫HTTP代理使用教程:突破反爬的实战指南
  • 隐私计算的崛起:数据安全的未来守护者
  • ollama+open-webui本地部署自己的模型到d盘+两种open-webui部署方式(详细步骤+大量贴图)
  • obj.name 和 obj[name]的区别?【前端】
  • 【Yonyou-BIP】平台档案删除时报自建应用实体错误
  • Bash判断命令是否存在
  • androd的XML页面 跳转 Compose Activity 卡顿问题
  • 009_抽象类和接口
  • 计算机视觉五大技术——深度学习在图像处理中的应用
  • Spring、Spring Boot和 Spring Cloud 的关系
  • 网络安全·第一天·IP协议安全分析
  • Python高级爬虫之JS逆向+安卓逆向1.2节: 变量与对象
  • 科普:GBDT与XGBoost比较
  • MySQL的左连接、右连接、内连接、外连接
  • 【CPP】内存泄漏详解
  • Git 使用说明和配置
  • Logo语言的在线课程学习
  • 北方今年首场高温过程开启,西北华北黄淮多地最高或达40℃
  • 墨海军训练舰在纽约撞桥,墨总统:对遇难者表示悲痛,将跟进调查
  • 中国田径巡回赛西安站完赛:男子跳远石雨豪夺冠
  • 出走的苏敏阿姨一路走到了戛纳,这块红毯因她而多元
  • 澎湃与七猫联合启动百万奖金征文,赋能非虚构与现实题材创作
  • 张家界一铁路致17人身亡,又有15岁女孩殒命,已开始加装护栏