VGG:重复的小滤波块
VGG
跟踪VGG16/19配置、计算感受野与参数成本,并运行完整窄版网络。
vgg先看一个实验
在明确的通道假设下,三个小滤波器可以观察到与一个大滤波器一样宽的区域,却使用更少权重。它们之间还能插入非线性,从而改变可表示的函数。VGG把这个想法组织成规则结构:重复小卷积,降低分辨率,再重复。
规则结构便于检查。在真正分配模型之前,就能跟踪每个空间尺寸、核算每个参数。下面程序对论文配置D和E完成这项工作,支持以较小通道宽度运行任一模式。小型前向使用随机权重,架构计数不是训练后的性能结果。
模型与假设
Simonyan与Zisserman的D/E配置使用3×3卷积、步幅一、填充一,每个块之后是2×2最大池化、步幅二。卷积通道依次为64、128、256、512、512,全连接头为4096、4096、1000,隐藏层使用ReLU。Simonyan与Zisserman,2015
| 配置 | 每块卷积数 | 卷积层+全连接层 |
|---|---|---|
| D | 2,2,3,3,3 | 13+3=16 |
| E | 2,2,4,4,4 | 16+3=19 |
深度计数不含池化和激活。论文还有其他配置,例如C同样有16个带权层,却包含1×1卷积;明确写D或E,可以消除歧义。224像素输入经过五次池化后,边长依次为112、56、28、14、7。D2L解释了如何用一个块在降采样之前执行多次卷积。Simonyan与Zisserman,2015 D2L:VGG块
从开始,可以跟踪理论感受野边长r,以及相邻输出对应的输入间距j。无空洞卷积时,对于核大小k、步幅s:
因此,两层3×3、步幅一的卷积有5×5理论感受野,三层则是7×7。这是结构上的支持范围上界,不保证考虑权重与ReLU门之后,每个输入像素都有相同或非零影响。
假设输入、中间和输出通道都为C,忽略偏置,三层3×3比一层7×7使用更少权重:
两层3×3与一层5×5的对应计数为18C²和25C²。若中间通道变宽,比较结果也会改变。感受野相同,不意味着函数相同:中间ReLU使一般情形不能用一次线性卷积替换。
单个带偏置的卷积层和全连接层,参数分别为:
完整D配置的首个全连接层接收个输入,仅这一层就有102764544个参数。因此,大量参数存储不只由卷积阶段数量决定,分类头也占很大分量。
完整小程序
使用Python3.12与NumPy1.26.4。plan不分配全网络权重,只计算规模。tiny_vgg保留完整D或E层模式,但使用32×32 RGB输入、2/4/8/8/8通道、16单元隐藏层和十个输出,实际执行卷积、池化、全连接与softmax。没有复现训练、dropout掩码或原始预训练初始化。
import numpy as np
REPEATS = {'D': (2,2,3,3,3), 'E': (2,2,4,4,4)}
def plan(configuration='D', side=224, channels=(64,128,256,512,512), hidden=4096, classes=1000):
if configuration not in REPEATS or type(side) is not int or side < 32:
raise ValueError('need configuration D/E and integer side >= 32')
if len(channels) != 5 or any(type(c) is not int or c < 1 for c in (*channels,hidden,classes)):
raise ValueError('need five positive integer widths, hidden size and class count')
n, incoming, layers = side, 3, []
for block,(repeats,outgoing) in enumerate(zip(REPEATS[configuration],channels),1):
for index in range(repeats):
weights = 9*incoming*outgoing
layers.append(dict(kind='conv', name=f'conv{block}_{index+1}', side=n,
incoming=incoming,outgoing=outgoing,
parameters=weights+outgoing, macs=n*n*weights))
incoming=outgoing
n//=2
layers.append(dict(kind='pool',name=f'pool{block}',side=n,channels=incoming,
parameters=0,macs=0))
incoming=n*n*incoming
for index,outgoing in enumerate((hidden,hidden,classes),1):
layers.append(dict(kind='fc',name=f'fc{index}',incoming=incoming,outgoing=outgoing,
parameters=incoming*outgoing+outgoing,macs=incoming*outgoing))
incoming=outgoing
return layers
def conv_same(image, weights, bias):
# HWC image; output-channel, input-channel, height, width weights.
a,w,b=np.asarray(image,dtype=float),np.asarray(weights,dtype=float),np.asarray(bias,dtype=float)
if a.ndim!=3 or w.ndim!=4 or w.shape[2:]!=(3,3) or w.shape[1]!=a.shape[2] or b.shape!=(w.shape[0],):
raise ValueError('need HWC image, OI33 weights and O bias')
if min(a.shape)<1 or w.shape[0]<1 or not all(np.isfinite(v).all() for v in (a,w,b)):
raise ValueError('arrays must be finite and nonempty')
padded=np.pad(a,((1,1),(1,1),(0,0)))
windows=np.lib.stride_tricks.sliding_window_view(padded,(3,3),axis=(0,1))
return np.einsum('hwcij,ocij->hwo',windows,w)+b
def max_pool(image):
a=np.asarray(image,dtype=float)
if a.ndim!=3 or min(a.shape[:2])<2 or a.shape[2]<1 or not np.isfinite(a).all():
raise ValueError('need finite HWC image with spatial dimensions >= 2')
h,w=a.shape[0]//2,a.shape[1]//2
return a[:2*h,:2*w].reshape(h,2,w,2,a.shape[2]).max(axis=(1,3))
def tiny_vgg(image, configuration='D', seed=17):
a=np.asarray(image,dtype=float)
if a.shape!=(32,32,3) or not np.isfinite(a).all():
raise ValueError('tiny demonstration expects finite 32x32 RGB values')
layers=plan(configuration,side=32,channels=(2,4,8,8,8),hidden=16,classes=10)
rng=np.random.default_rng(seed)
for layer in layers:
if layer['kind']=='conv':
incoming,outgoing=layer['incoming'],layer['outgoing']
weights=rng.normal(size=(outgoing,incoming,3,3))*np.sqrt(2/(9*incoming))
a=np.maximum(conv_same(a,weights,np.zeros(outgoing)),0)
elif layer['kind']=='pool':
a=max_pool(a)
else:
a=a.ravel()
weights=rng.normal(size=(layer['incoming'],layer['outgoing']))*np.sqrt(2/layer['incoming'])
a=a@weights
if layer['name']!='fc3':
a=np.maximum(a,0)
exponent=np.exp(a-a.max())
return exponent/exponent.sum()
if __name__=='__main__':
for configuration in ('D','E'):
layers=plan(configuration)
print(configuration,'weight layers:',sum(l['kind']!='pool' for l in layers),
'parameters:',sum(l['parameters'] for l in layers),
'multiply-accumulates:',sum(l['macs'] for l in layers))
image=np.random.default_rng(5).normal(size=(32,32,3))
p=tiny_vgg(image)
print('untrained tiny D probabilities:',p.round(5).tolist())
print('sum:',round(float(p.sum()),12))
D weight layers: 16 parameters: 138357544 multiply-accumulates: 15470264320
E weight layers: 19 parameters: 143667240 multiply-accumulates: 19632062464
untrained tiny D probabilities: [0.05428, 0.02933, 0.01649, 0.51783, 0.04502, 0.10334, 0.0211, 0.04703, 0.03642, 0.12918]
sum: 1.0
精确总数根据声明的形状与偏置推导,原表只报告四舍五入后的百万数量,并未列出所有这些数字。本例一次乘累加计一次,MAC不包含偏置加法、池化比较和激活。若某种FLOP口径把乘法和加法分别计数,需要另行核算。Simonyan与Zisserman,2015
检查覆盖D/E深度与尺寸、字面多通道卷积、奇数边界池化、两种小型网络、零输入输出及非法输入。冲激测试测量一、二、三层小卷积后的3×3、5×5、7×7支持范围;另一个反例确认删除中间ReLU会改变函数。
耗时取决于每层空间大小、通道和核,不只取决于层在列表中的位置。固定核大小,把输入与输出通道都翻倍,同时把两个空间维度都减半,主要卷积MAC数不变。但这不意味着延迟或激活内存相同。
局限与比较
小核组织了设计空间,但不会让深度免费。训练需要保留激活或重新计算,参数精度改变存储,宽全连接头可能主导参数内存。理论感受野更大,也不能证明模型有效利用了上下文。
所读论文训练段报告批量256、momentum0.9、weight decay5×10⁻⁴,以及前两个全连接层dropout0.5。它描述了用配置A初始化部分深层网络层,之后又指出另一种随机初始化也可以工作。这些是作者报告的实验选择,不是小型前向例子已验证的设置;不把作者关于收敛原因的推测当成已证明解释。Simonyan与Zisserman,2015
面向其他图像大小或标签集合的分类器,需要明确分类头与预处理契约。改成全局池化、插入归一化或改变块宽度,都会形成应当注明并测量的变体。比较方法时,应保持数据划分与推理方案一致,不能把层数当成准确率排名。
练习与答案
1. 配置D为何计为16个带权层?
答案: 五块共有2+2+3+3+3=13个卷积,再加三个全连接层。这种深度口径不计池化与ReLU。
2. 通道恒为C时,比较三层3×3与一层7×7。
答案: 步幅一、中间不池化时,理论感受野同为7×7;忽略偏置,权重为27C²与49C²。含非线性时,函数不必相同。
3. 计算全尺寸首个全连接层的参数量。
答案: 25088个输入连接4096个输出,各有一个偏置:25088×4096+4096=102764544。
4. 为什么ReLU隔开的两个线性映射不能总是合并?
答案: 输入−1,第一个映射乘正一,第二个乘负一。中间及末尾都用ReLU得到0;先合并映射、只在末尾用ReLU得到1。
来源与下一步
ICLR2015作者论文提供配置、设计理由与限定训练记录。实际目视核对了表格,避免文本抽取时混淆列。D2L提供按块讲解的方法,本篇论证不依赖其中宽泛的优先权说法。Simonyan与Zisserman,2015 D2L:VGG块
Inception通过并行空间分支改变块,ResNet通过捷径改变经过块的路径。比较时,把这些变化与VGG明确的形状和成本联系起来,而不只是比较名字。
先判断,再看解释
配置D有13个卷积层,为何按论文深度口径计为16层?
学习目标
- 重建D/E深度、空间形状与精确参数数目。
- 区分理论感受野、非线性表达与计算成本。
先修与延伸
查看知识关联图 →参考文献
- Very Deep Convolutional Networks for Large-Scale Image Recognition — ICLR 2015 author paper
Karen Simonyan; Andrew Zisserman · 2015 - Dive into Deep Learning 1.0.3 — vgg
Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary-source passages, explicit image classification experiments and CNN architecture models, executed programs, independent mathematical references, input boundaries and bilingual alignment. Not independent human or second-agent review; no full-system research reproduction claimed.
- 单个AI作者进行技术检查:可运行示例、精确或字面参照、明确假设及对应的双语公式与习题。实际执行和渲染结果另行记录。
- 8项检查:D/E深度、尺寸与精确参数算术,字面多通道卷积,奇数边界池化,两种小图,3/5/7冲激支持、非线性不可合并与非法输入。修正文案为支持运行任一小模式,默认main实际运行D。
- 单AI作者对照双语六节、假设、定义、公式、实际代码与输出、四组习题答案及限定引用。六篇草稿合计43项检查;不是独立人工审校或完整历史训练复现。
- 完整双语正文与对应习题迁入,正式文章状态及SHA绑定。算法篇测试读取正式MDX;历史篇不虚列可执行程序或计算测试。
- 视觉阅读核对后缩短并本地化行内引文标签;验证链接目标顺序及全部代码/公式/标签保护段未变,完整来源身份仍在元数据。冻结稿保留,最终正文SHA重新绑定。
- 补全描述两种受支持小配置句子的英文连接词,实现范围不变。
核对的来源位置:
- Very Deep Convolutional Networks for Large-Scale Image Recognition — ICLR 2015 author paper · ICLR2015 paper sections2.1/2.3, visually checked physical3 tables1/2, bounded physical4 training passage.
- Dive into Deep Learning 1.0.3 — vgg · Section8.2.1 VGG blocks and implementation; no upstream runtime or training reproduction.
相关主题