DenseNet:保留并复用早先的特征
DenseNet
跟踪密集连接,推导增长率与BC成本,运行原创NumPy小分类器。
densenet跟着数据看
某一层已经找到了边缘,后面的层还要重新描述一遍吗?DenseNet让后面的层直接读取早先的特征图,把新增通道留给其他特征。它是否真的学出了有用的新东西,要看训练;能够读取旧特征,则是架构本身保证的。
先算一个小例子。输入有3个通道,连续三个变换各产生2个新通道,整个状态的宽度便依次是3、5、7、9。第二个变换读取已有的全部5个通道,不只读取最新产生的2个。“密集连接”不等于“全连接层”:变换本身仍可以是空间卷积。
原始设计把这些连接组织成密集块。块内的高和宽保持不变,特征图才能沿通道轴拼接;块间再通过过渡层改变尺寸。这是Huang等人在CVPR2017论文中提出的核心构造。DenseNet原论文
可以把拼接想成保留分格的抽屉:各坐标仍可单独读取;相加则把对应坐标合在一起。比喻只能帮助理解操作,不能代替效果证据:保留下来的特征可能重复,后续卷积也可能忽略它们。
定义与计算
设块输入有个通道,变换在相同空间尺寸上产生个通道。方括号表示沿通道拼接,不是求和:
经过个变换后,状态共有个通道。增长率表示每个变换新增多少通道,不是整个块的宽度。把块输入也算作一个先前状态,直接连接数为。这里数的是图中的边,既不是参数量,也不是实际张量副本数。
基础版的依次执行BN、ReLU和带填充的卷积。DenseNet-B在空间卷积之前加入输出通道的卷积,两次卷积前都做BN和ReLU。DenseNet-C在块间压缩通道,BC同时采用两者。若块输出有个通道,过渡层先产生个通道,再做均值池化,其中。论文的压缩实验使用。公式2与BC定义
为什么加瓶颈?这次比较先不计BN和偏置。输入通道的基础层需要个卷积权重;BC层的逐点卷积需要个,空间卷积需要个:
取,两者为54和168:名叫“瓶颈”,中间表示却变宽了,计算也更多。换成,两者为576和400。名称不能保证每层都节省参数。输出尺寸相同时,卷积MAC等于权重数乘输出位置数;BN、激活与数据搬运要另外计算。
块中原样保留的输入切片很容易分析。把整个状态写为,再按旧、新特征划分上游导数:
这里存在一条恒等路径,但它传回的贡献可能是零,也可能与另一项抵消。过渡层还可能丢掉信息。公式说明导数有路可走,没有证明训练中每个梯度都会保持足够大。
运行小模型
下面的原创小分类器使用NumPy1.26.4和Python3.12.4,实际执行:3×3起始卷积、两个BC变换、一个过渡层、另外两个BC变换、末端归一化、全局均值池化及三类输出。输入是单张HWC图像。BN使用指定的零均值和单位方差做推理,gamma与beta分别初始化为1和0,没有拿数据估计这些统计量。
独立的imagenet_plan函数只计算论文的四块配置,不运行这些大模型。121配置的块输出宽度为256、512、1024、1024。层数包括起始卷积、每个BC变换的两次卷积、三个过渡层和分类器,共121层。7,978,856个参数计入BN仿射项与分类头偏置,不计BN运行统计缓冲区,并采用无偏置卷积。2,834,161,664次MAC只包含卷积与线性乘加。这些是按明确口径计算的结果,不是实测耗时。
"""Original NumPy DenseNet teaching preflight; not a trained DenseNet-121.
HWC single-image inputs, cross-correlation, bias-free convolutions,
inference BN with supplied zero means/unit variances, and floor pooling.
The classifier executes two small BC blocks; imagenet_plan only counts
paper configurations and does not allocate or run those full models.
"""
import math
import numpy as np
def positive(n):
if isinstance(n, (bool, np.bool_)) or not isinstance(n, (int, np.integer)) or n < 1:
raise ValueError('expected a positive integer')
return int(n)
def image(x):
x = np.asarray(x, dtype=float)
if x.ndim != 3 or min(x.shape) < 1 or not np.isfinite(x).all():
raise ValueError('expected finite nonempty HWC input')
return x
def conv(x, w):
x, w = image(x), np.asarray(w, dtype=float)
if (w.ndim != 4 or min(w.shape) < 1 or w.shape[0] != w.shape[1]
or w.shape[0] % 2 != 1 or w.shape[2] != x.shape[2]
or not np.isfinite(w).all()):
raise ValueError('expected finite odd square KH-KW-Cin-Cout weights')
k, _, _, out = w.shape
z = np.pad(x, ((k//2, k//2), (k//2, k//2), (0, 0)))
y = np.empty((*x.shape[:2], out))
for i in range(x.shape[0]):
for j in range(x.shape[1]):
y[i, j] = np.einsum('abc,abcd->d', z[i:i+k, j:j+k], w)
return y
def bn_relu(x, gamma, beta, mean, variance, eps=1e-5):
x = image(x)
vectors = [np.asarray(v, dtype=float) for v in (gamma, beta, mean, variance)]
if any(v.shape != (x.shape[2],) or not np.isfinite(v).all() for v in vectors):
raise ValueError('BN vectors must match channels')
if not np.isfinite(eps) or eps <= 0 or (vectors[3] < 0).any():
raise ValueError('invalid BN variance or epsilon')
g, b, mu, var = vectors
return np.maximum(g * (x-mu) / np.sqrt(var+eps) + b, 0)
def avg_pool(x):
x = image(x)
h, w, c = x.shape
if min(h, w) < 2:
raise ValueError('pooling needs at least 2 by 2')
return x[:h//2*2, :w//2*2].reshape(h//2, 2, w//2, 2, c).mean(axis=(1, 3))
def compressed(channels, theta):
channels = positive(channels)
if not np.isfinite(theta) or not 0 < theta <= 1:
raise ValueError('compression must be in (0, 1]')
result = math.floor(channels * theta)
if result == 0:
raise ValueError('compression would remove every channel')
return result
def block(x, layers):
state = image(x).copy()
for first, second, norm1, norm2 in layers:
added = conv(bn_relu(conv(bn_relu(state, *norm1), first), *norm2), second)
state = np.concatenate((state, added), axis=2)
return state
def transition(x, w, norm):
if np.asarray(w).ndim != 4 or w.shape[:2] != (1, 1):
raise ValueError('transition convolution must be 1 by 1')
return avg_pool(conv(bn_relu(x, *norm), w))
def make_layers(channels, count, growth, rng):
channels, count, growth = map(positive, (channels, count, growth))
layers = []
for i in range(count):
m, b = channels + i*growth, 4*growth
layers.append((rng.normal(0, .1, (1, 1, m, b)),
rng.normal(0, .1, (3, 3, b, growth)),
norm(m), norm(b)))
return layers
def norm(channels):
channels = positive(channels)
return (np.ones(channels), np.zeros(channels), np.zeros(channels), np.ones(channels))
def imagenet_plan(counts=(6, 12, 24, 16), growth=32, theta=.5, classes=1000):
counts = tuple(positive(n) for n in counts)
growth, classes = positive(growth), positive(classes)
if len(counts) != 4:
raise ValueError('this ImageNet plan requires four blocks')
m = 2*growth
compressed(m, theta)
# Stem conv and BN affine parameters. Running means/variances are buffers.
params, macs, side = 7*7*3*m + 2*m, 112*112*7*7*3*m, 56
widths = []
for j, count in enumerate(counts):
for _ in range(count):
b = 4*growth
weights = m*b + 9*b*growth
params += weights + 2*m + 2*b
macs += side*side*weights
m += growth
widths.append(m)
if j < 3:
out = compressed(m, theta)
params += 2*m + m*out
macs += side*side*m*out
m, side = out, side//2
params += 2*m + m*classes + classes
macs += m*classes
return dict(widths=widths, depth=1+2*sum(counts)+3+1,
parameters=params, convolution_and_linear_macs=macs)
def tiny_classifier(x, seed=9):
x = image(x)
if x.shape[2] != 3 or min(x.shape[:2]) < 2:
raise ValueError('classifier expects RGB input with sides at least 2')
rng = np.random.default_rng(seed)
state = conv(x, rng.normal(0, .1, (3, 3, 3, 4)))
state = block(state, make_layers(4, 2, 2, rng))
state = transition(state, rng.normal(0, .1, (1, 1, 8, 4)), norm(8))
state = block(state, make_layers(4, 2, 2, rng))
features = bn_relu(state, *norm(8)).mean(axis=(0, 1))
scores = features @ rng.normal(0, .1, (8, 3))
probabilities = np.exp(scores-scores.max())
return probabilities/probabilities.sum()
if __name__ == '__main__':
print(imagenet_plan())
x = np.arange(8*8*3, dtype=float).reshape(8, 8, 3)/(8*8*3)
print('tiny probabilities:', np.round(tiny_classifier(x), 6).tolist())
运行输出:
{'widths': [256, 512, 1024, 1024], 'depth': 121, 'parameters': 7978856, 'convolution_and_linear_macs': 2834161664}
tiny probabilities: [0.330595, 0.33332, 0.336085]
改变种子,输出概率会变。零输入得到均匀分布,因为这组初始化没有加性偏移。这两种现象都不代表识别准确率。测试还构造了精确的状态:第二个新特征必须读取第一个新特征才能得到。相比看一组貌似合理的分类概率,这更直接地检查了连接机制。
模型能说明到哪里
密集连接的范围是一个块。空间尺寸不同时,若没有额外对齐规则,就不能直接拼接;过渡层通过先结束一个块、再下采样来解决这个问题。投影和池化通常会使原状态无法被精确恢复。
参数省不省,与内存省不省,是两个问题。设空间面积固定为,块的最终独立状态保存个数。如果朴素实现每一步都重新创建拼接状态,累计复制量正比于。固定时,后者随二次增长,而最终状态只线性增长。但这不是峰值训练内存公式:临时数组、梯度、保存的激活和内存复用都会影响峰值。
D2L的密集块讲解便于理解拼接和过渡层,但其基础块没有4k瓶颈。如果套用BC参数表,就会把不同模型混在一起。本例采用BC构造,同时明确省略训练、数据预处理、增强和优化过程。
可以对照ResNet的相加、Inception的并行分支,以及MobileNet的分解卷积。没有一个架构在所有条件下都最好;先说明准确率、数据、内存、批量大小和部署硬件,再作选择。
练习与答案
1. 每层新增三个通道
答案:输入5通道,四个变换的增长率为3,最终状态有17通道。第四个变换读取14通道,再新增3个。
2. 瓶颈什么时候更省?
答案:m=32、k=2时,基础层和BC层的卷积权重为576和400;m=3时为54和168。条件是m>7.2k;统计可训练参数时还要另加BN。
3. 能直接读取,就保证梯度非零吗?
答案:不能。下游目标可能完全忽略保留的坐标,使直接导数为零;不同路径的贡献还可能抵消,投影也可能丢弃坐标。
4. 压缩七通道状态
答案:theta=.5时输出3通道。本程序采用向下取整池化,5×5变为2×2。边缘被舍去,通道也经过投影,不能假设可以无损恢复;其他池化约定要另测。
来源与下一步
把原论文公式2、增长率段、BC定义和表1连起来读。表1描述ImageNet配置,不能把其中层数移植到这里的两块小程序。本文参数表按明确的BN与偏置口径独立计算。Huang等,2017
再通过D2L§8.7.2–8.7.4跟踪张量如何经过较简单的密集块与过渡层。应比较操作顺序和通道尺寸,而不是假设凡是叫DenseNet的实现都完全相同。D2L1.0.3
进一步的实验可以逐渐增加L,分别记录最终状态大小与累计拼接复制量,再与峰值驻留内存、实际延迟分开比较。这样,“特征复用”就变成了可以检查的具体量。
先判断,再看解释
一个块输入5通道,4个变换各新增3通道。过渡层之前有多少通道?
学习目标
- 计算通道增长与过渡层压缩。
- 在明确假设下比较基础层与BC参数成本。
- 区分保留特征路径与梯度、内存保证。
先修与延伸
查看知识关联图 →参考文献
- Densely Connected Convolutional Networks — CVPR2017 method
Gao Huang; Zhuang Liu; Laurens van der Maaten; Kilian Q. Weinberger · 2017 - Dive into Deep Learning1.0.3 — DenseNet blocks and transitions
Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: bounded original method passages and fixed official code, explicit NumPy teaching models, independent numerical references, boundary cases and corresponding bilingual reasoning. Not independent human or second-agent review; no full training or deployment benchmark reproduction.
- 单个AI作者进行技术检查:可运行示例、精确或字面参照、明确假设及对应的双语公式与习题。实际执行和渲染结果另行记录。
- 核对有符号坐标保留与有限差分恒等路径、[x,2x,6x]跨层依赖、字面卷积、BN/池化、独立分段参数表及瓶颈反例。8项正文检查,未复现训练。
- 逐节对照中英文论点、限制、定义、例子、公式与四组答案。冻结前仅在代码、数学、标签和链接目标之外调整英文间距。
- 完整双语正文与对应习题迁入,正式文章状态及SHA绑定。算法篇测试读取正式MDX;历史篇不虚列可执行程序或计算测试。
- 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。
- 手机目视检查发现长复合公式超出数学区域初始可见宽度,双语同步改为aligned分行;数值、论点、例子、代码和引用目标未变。保留冻结原稿,重新核查正式文件并绑定SHA。
核对的来源位置:
- Densely Connected Convolutional Networks — CVPR2017 method · CVPR PDF physical pages3–4, section3/equation2, BC paragraphs and visually checked table1.
- Dive into Deep Learning1.0.3 — DenseNet blocks and transitions · D2L1.0.3 sections8.7.1–8.7.4; PyTorch concatenation, basic block and transition.
相关主题