基于PyTorch的深度残差收缩网络
深度残差收缩网络(Deep Residual Shrinkage Networks, DRSN)是一种将软阈值化机制引入深度残差网络结构中的特征学习模型,增强网络抑制信号中无关冗余特征的能力。该网络结构发表于《IEEE Transactions on Industrial Informatics》期刊,论文题为《Deep Residual Shrinkage Networks for Fault Diagnosis》。本文将聚焦于该论文所提出的通道共享阈值深度残差收缩网络(DRSN-CS)与通道独立阈值深度残差收缩网络(DRSN-CW),对其网络结构设计及相应的PyTorch代码实现进行阐述。
一、网络结构解析

Fig. 4. (a) RSBU-CS构建单元;(b) DRSN-CS整体网络结构;© RSBU-CW构建单元;(d) DRSN-CW整体网络结构
如论文图4所示,DRSN-CS与DRSN-CW均以经典预激活残差网络(ResNet)为基础框架,通过将传统残差构建单元(RBU)替换为带有自适应阈值学习子网的残差收缩构建单元(RSBU),实现了在深层特征提取过程中对近零特征的自动置零。
1. 软阈值化层
软阈值化(Soft Thresholding)是信号去噪领域常用的收缩函数,在DRSN中作为非线性变换层嵌入每个残差收缩单元的末端。设输入特征为 ,输出特征为 ,正值阈值为 ,其函数表达式为:
与ReLU将所有负值置零不同,软阈值化仅将绝对值小于等于 的近零特征置零,同时保留绝对值较大的正、负特征。其输出对输入的导数为:
该导数在非零收缩区间外恒为1、区间内恒为0,有助于在反向传播过程中缓解梯度消失或梯度爆炸问题。
2. 残差收缩构建单元(RSBU-CS 与 RSBU-CW)
针对一维信号,论文中将特征图表示为三维张量 (通道数为 、宽度为 、高度为 )。每个构建单元内部包含一条主干特征提取路径、一条恒等捷径(Identity Shortcut)以及一个用于估计阈值 的子网络。
主干路径采用两个“批归一化(BN)→ 激活函数(ReLU)→ 卷积层(Conv)”的顺序连接,得到中间特征图 。随后,阈值估计子网络对 进行处理:
-
RSBU-CS(通道共享阈值单元,对应图4(a)):
- 对中间特征图 取绝对值 ,并通过全局平均池化(GAP)压缩空间维度,得到大小为 的一维向量。
- 一方面,该向量进入一个两层全连接(FC)网络(第一层神经元数 ,经BN与ReLU后,第二层神经元数 ),再通过Sigmoid函数输出缩放系数 :
- 另一方面,对GAP后的 向量再求一次通道均值(Average),即计算整个特征图绝对值的全局均值。将 与该均值相乘,得到通道共享的标量阈值:
- 利用 对 执行软阈值化,随后与恒等捷径相加作为单元输出。
-
RSBU-CW(通道独立阈值单元,对应图4©):
- 同样先对 执行绝对值操作与GAP,得到 的通道均值向量。
- 该向量送入两层FC网络,但第二层神经元数量设为 ,经Sigmoid激活后输出维度为 的缩放系数向量 :
- 将 与GAP后的通道均值向量按元素相乘,得到各通道独立的阈值向量:
- 按通道分别对 进行软阈值化,再与恒等捷径相加输出。
3. 整体网络架构
如图4(b)与图4(d)所示,DRSN-CS与DRSN-CW的整体结构由输入层、初始卷积层、若干堆叠的RSBU模块以及后端分类层构成。参考论文的具体结构参数,以输入长度为2048的一维信号为例,完整网络的数据流向与维度变化如下:
- 输入层:输入形状为 。
- 初始卷积层:使用 个宽度为 、步长为 的卷积核,输出形状为 。
- 堆叠RSBU模块(共12个单元,分为3个阶段):
- 第一阶段:1个步长为 的下采样RSBU(输出 ),接3个步长为 的标准RSBU(保持 )。
- 第二阶段:1个步长为 且通道数翻倍的RSBU(输出 ),接3个标准RSBU(保持 )。
- 第三阶段:1个步长为 且通道数翻倍的RSBU(输出 ),接3个标准RSBU(保持 )。
- 输出分类层:依次经过BN、ReLU以及全局平均池化(GAP),将特征图压缩为长度为 的一维特征向量,最后接入全连接(FC)层输出类别预测(论文实验中为 类)。
二、PyTorch代码实现
在PyTorch中,高度为 的 特征图可以直接对应一维卷积模块(nn.Conv1d、nn.BatchNorm1d)中的 (Batch, C, W) 张量格式。软阈值化操作可等价表示为 ,该形式可由PyTorch自动求导机制准确计算梯度。此外,当RSBU的步长为 或输入输出通道数发生变化时,代码中在捷径分支采用核大小为 的卷积层完成张量维度的对齐。
以下是PyTorch完整实现代码:
import torch
import torch.nn as nn
import torch.nn.functional as F
class SoftThresholding(nn.Module):
"""软阈值化非线性变换层"""
def __init__(self):
super().__init__()
def forward(self, x: torch.Tensor, threshold: torch.Tensor) -> torch.Tensor:
# x 形状: (B, C, W)
# threshold 形状: (B, 1, 1) 或 (B, C, 1)
return torch.sign(x) * F.relu(torch.abs(x) - threshold)
class RSBU_CS(nn.Module):
"""通道共享阈值的残差收缩构建单元 (RSBU-CS)"""
def __init__(self, in_channels: int, out_channels: int, kernel_size: int = 3, stride: int = 1):
super().__init__()
padding = kernel_size // 2
# 主干卷积分支
self.bn1 = nn.BatchNorm1d(in_channels)
self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size, stride=stride, padding=padding)
self.bn2 = nn.BatchNorm1d(out_channels)
self.conv2 = nn.Conv1d(out_channels, out_channels, kernel_size, stride=1, padding=padding)
# 通道共享阈值估计子网络
self.fc1 = nn.Linear(out_channels, out_channels)
self.bn_fc = nn.BatchNorm1d(out_channels)
self.fc2 = nn.Linear(out_channels, 1)
self.shrinkage = SoftThresholding()
# 捷径分支:当空间尺寸或通道数变化时对齐维度
if stride != 1 or in_channels != out_channels:
self.shortcut = nn.Conv1d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False)
else:
self.shortcut = nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
residual = self.shortcut(x)
out = self.conv1(F.relu(self.bn1(x)))
out = self.conv2(F.relu(self.bn2(out)))
# 1. 取绝对值并进行GAP -> (B, C)
abs_out = torch.abs(out)
gap = torch.mean(abs_out, dim=-1)
# 2. 两层FC网络计算缩放参数 alpha -> (B, 1)
scale = self.fc1(gap)
scale = F.relu(self.bn_fc(scale))
alpha = torch.sigmoid(self.fc2(scale))
# 3. 乘以特征图绝对值的全局均值 -> (B, 1, 1)
avg_abs = torch.mean(gap, dim=-1, keepdim=True)
tau = (alpha * avg_abs).unsqueeze(-1)
# 4. 软阈值化并与捷径相加
out = self.shrinkage(out, tau)
return out + residual
class RSBU_CW(nn.Module):
"""通道独立阈值的残差收缩构建单元 (RSBU-CW)"""
def __init__(self, in_channels: int, out_channels: int, kernel_size: int = 3, stride: int = 1):
super().__init__()
padding = kernel_size // 2
# 主干卷积分支
self.bn1 = nn.BatchNorm1d(in_channels)
self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size, stride=stride, padding=padding)
self.bn2 = nn.BatchNorm1d(out_channels)
self.conv2 = nn.Conv1d(out_channels, out_channels, kernel_size, stride=1, padding=padding)
# 通道独立阈值估计子网络
self.fc1 = nn.Linear(out_channels, out_channels)
self.bn_fc = nn.BatchNorm1d(out_channels)
self.fc2 = nn.Linear(out_channels, out_channels)
self.shrinkage = SoftThresholding()
# 捷径分支:当空间尺寸或通道数变化时对齐维度
if stride != 1 or in_channels != out_channels:
self.shortcut = nn.Conv1d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False)
else:
self.shortcut = nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
residual = self.shortcut(x)
out = self.conv1(F.relu(self.bn1(x)))
out = self.conv2(F.relu(self.bn2(out)))
# 1. 取绝对值并进行GAP -> (B, C)
abs_out = torch.abs(out)
gap = torch.mean(abs_out, dim=-1)
# 2. 两层FC网络计算各通道缩放参数 alpha_c -> (B, C)
scale = self.fc1(gap)
scale = F.relu(self.bn_fc(scale))
alpha = torch.sigmoid(self.fc2(scale))
# 3. 与各通道绝对值均值逐元素相乘 -> (B, C, 1)
tau = (alpha * gap).unsqueeze(-1)
# 4. 软阈值化并与捷径相加
out = self.shrinkage(out, tau)
return out + residual
class DRSN(nn.Module):
"""深度残差收缩网络整体架构 (支持 DRSN-CS 与 DRSN-CW)"""
def __init__(self, block_type: str = "CW", in_channels: int = 1, num_classes: int = 8):
super().__init__()
if block_type == "CS":
block = RSBU_CS
elif block_type == "CW":
block = RSBU_CW
else:
raise ValueError("block_type 仅支持 'CS' 或 'CW'")
# 初始卷积层: Conv(4, 3, /2)
self.conv_in = nn.Conv1d(in_channels, 4, kernel_size=3, stride=2, padding=1)
# 三个阶段的残差收缩单元堆叠
self.stage1 = self._make_stage(block, in_ch=4, out_ch=4, num_blocks=4)
self.stage2 = self._make_stage(block, in_ch=4, out_ch=8, num_blocks=4)
self.stage3 = self._make_stage(block, in_ch=8, out_ch=16, num_blocks=4)
# 后端分类层: BN -> ReLU -> GAP -> FC
self.bn_out = nn.BatchNorm1d(16)
self.fc_out = nn.Linear(16, num_classes)
@staticmethod
def _make_stage(block, in_ch: int, out_ch: int, num_blocks: int) -> nn.Sequential:
# 每个阶段的第一个单元步长为2(下采样),其余单元步长为1
layers = [block(in_ch, out_ch, kernel_size=3, stride=2)]
for _ in range(1, num_blocks):
layers.append(block(out_ch, out_ch, kernel_size=3, stride=1))
return nn.Sequential(*layers)
def forward(self, x: torch.Tensor) -> torch.Tensor:
out = self.conv_in(x)
out = self.stage1(out)
out = self.stage2(out)
out = self.stage3(out)
out = F.relu(self.bn_out(out))
out = torch.mean(out, dim=-1) # 全局平均池化 (GAP)
out = self.fc_out(out)
return out
if __name__ == "__main__":
# 构造测试输入: (Batch=2, Channels=1, Length=2048)
dummy_input = torch.randn(2, 1, 2048)
model_cs = DRSN(block_type="CS", in_channels=1, num_classes=8)
model_cw = DRSN(block_type="CW", in_channels=1, num_classes=8)
out_cs = model_cs(dummy_input)
out_cw = model_cw(dummy_input)
print("DRSN-CS 输出维度:", out_cs.shape) # torch.Size([2, 8])
print("DRSN-CW 输出维度:", out_cw.shape) # torch.Size([2, 8])
上述实现将 RSBU-CS 与 RSBU-CW 的差异严格限定于阈值估计子网络的输出维度及通道均值计算方式:前者输出单标量阈值并广播至所有通道,后者输出长度等于通道数的阈值向量以实现逐通道独立收缩。在实际工程应用中,可根据输入信号长度与任务类别数调整 in_channels、num_classes 以及各阶段的通道规模。
参考文献
Deep Residual Shrinkage Networks for Fault Diagnosis[J]. IEEE Transactions on Industrial Informatics, 2020.
- 点赞
- 收藏
- 关注作者
评论(0)