基于MATLAB的深度残差收缩网络程序实现

举报
hw9826 发表于 2026/11/18 10:44:37 2026/11/18
【摘要】 本文给出深度残差收缩网络(Deep Residual Shrinkage Network, DRSN)的网络结构说明及其在MATLAB中的完整实现程序,涵盖通道共享阈值(DRSN-CS)与通道独立阈值(DRSN-CW)两种结构。该网络提出于论文《Deep Residual Shrinkage Networks for Fault Diagnosis》,发表于期刊《IEEE Transacti...

本文给出深度残差收缩网络(Deep Residual Shrinkage Network, DRSN)的网络结构说明及其在MATLAB中的完整实现程序,涵盖通道共享阈值(DRSN-CS)与通道独立阈值(DRSN-CW)两种结构。该网络提出于论文《Deep Residual Shrinkage Networks for Fault Diagnosis》,发表于期刊《IEEE Transactions on Industrial Informatics》(2020年第16卷第7期)。下文根据原论文给出的模块构造与超参数配置,依次说明网络结构与对应的MATLAB代码实现。


一、网络结构

深度残差收缩网络在经典残差网络(ResNet)的残差构建单元(RBU)基础上,引入了软阈值化(soft thresholding)作为非线性变换层,并通过嵌入的阈值估计子网络自动确定阈值。论文中DRSN-CS与DRSN-CW的构建单元及整体架构如图4所示。

原论文图4:(a) RSBU-CS构建单元;(b) DRSN-CS整体架构;© RSBU-CW构建单元;(d) DRSN-CW整体架构
图中 KK 为卷积核数量,MM 为全连接层神经元数量,C×W×1C \times W \times 1 分别表示特征图的通道数、宽度和高度,xx、zz 和 α\alpha 为阈值计算过程中的中间特征图

1. 软阈值化层

软阈值化函数定义如下:

y={x−τ,x>τ0,−τ≤x≤τx+τ,x<−τy = \begin{cases} x - \tau, & x > \tau \\ 0, & -\tau \le x \le \tau \\ x + \tau, & x < -\tau \end{cases}

其中 xx 为输入特征,yy 为输出特征,τ>0\tau > 0 为阈值。该函数对输入 xx 的偏导数为:

∂y∂x={1,x>τ0,−τ≤x≤τ1,x<−τ\frac{\partial y}{\partial x} = \begin{cases} 1, & x > \tau \\ 0, & -\tau \le x \le \tau \\ 1, & x < -\tau \end{cases}

2. 残差收缩构建单元(RSBU-CS 与 RSBU-CW)

如论文图4(a)和图4©所示,残差收缩构建单元的主干路径由两组批归一化(BN)、ReLU激活函数和一维卷积层(在二维张量形式下卷积核尺寸为 1×31 \times 3)顺序组成,输出特征图记为 xx(维度为 C×W×1C \times W \times 1)。随后由嵌入的阈值估计子网络计算软阈值 τ\tau,并与恒等快捷连接(identity shortcut)相加。两种构建单元的阈值计算方式差异如下:

  • RSBU-CS(通道共享阈值):如图4(a)所示,先对特征图 xx 取绝对值并经过全局平均池化(GAP),得到维度为 C×1×1C \times 1 \times 1 的一维向量;一路再经通道维求平均得到标量 average⁡i,j,c∣xi,j,c∣\operatorname{average}_{i,j,c}|x_{i,j,c}|,另一路经两层全连接网络(隐含层神经元数为 CC,中间接 BN 与 ReLU,输出层神经元数为 11)及 Sigmoid 函数得到缩放参数 α∈(0,1)\alpha \in (0, 1):

    α=11+e−z,τ=α⋅average⁡i,j,c∣xi,j,c∣\alpha = \frac{1}{1 + e^{-z}}, \quad \tau = \alpha \cdot \operatorname{average}_{i,j,c}|x_{i,j,c}|

    最终所有通道共享同一个标量阈值 τ\tau。

  • RSBU-CW(通道独立阈值):如图4©所示,对特征图 xx 取绝对值并经GAP后得到每个通道的绝对值均值向量 average⁡i,j∣xi,j,c∣\operatorname{average}_{i,j}|x_{i,j,c}|(维度为 C×1×1C \times 1 \times 1);全连接网络输出层神经元数保持为 CC,经 Sigmoid 函数得到向量 α\alpha(维度为 C×1×1C \times 1 \times 1),再与 GAP 结果逐元素相乘,为第 cc 个通道独立计算阈值 τc\tau_c:

    αc=11+e−zc,τc=αc⋅average⁡i,j∣xi,j,c∣\alpha_c = \frac{1}{1 + e^{-z_c}}, \quad \tau_c = \alpha_c \cdot \operatorname{average}_{i,j}|x_{i,j,c}|

当某个构建单元需要执行步长为 22 的下采样或通道数加倍时,为使快捷连接分支与主干输出特征图尺寸一致,快捷连接上采用步长为 22、核尺寸为 1×11 \times 1 的卷积层进行维数匹配。

3. 整体网络配置

如图4(b)与图4(d)所示,DRSN-CS与DRSN-CW的整体网络由输入层、初始卷积层、12个堆叠的RSBU模块以及输出端(BN、ReLU、GAP、全连接层、Softmax与交叉熵损失)构成。各层特征图维度(通道数 ×\times 宽度 ×\times 高度)配置如下:

  1. 输入层:1×2048×11 \times 2048 \times 1
  2. 初始卷积层:Conv(4,3,/2)\text{Conv}(4, 3, /2),输出 4×1024×14 \times 1024 \times 1
  3. 第1阶段 RSBU:1个 RSBU(4,3,/2)\text{RSBU}(4, 3, /2) + 3个 RSBU(4,3)\text{RSBU}(4, 3),输出 4×512×14 \times 512 \times 1
  4. 第2阶段 RSBU:1个 RSBU(8,3,/2)\text{RSBU}(8, 3, /2) + 3个 RSBU(8,3)\text{RSBU}(8, 3),输出 8×256×18 \times 256 \times 1
  5. 第3阶段 RSBU:1个 RSBU(16,3,/2)\text{RSBU}(16, 3, /2) + 3个 RSBU(16,3)\text{RSBU}(16, 3),输出 16×128×116 \times 128 \times 1
  6. 输出端:BN→ReLU→GAP\text{BN} \to \text{ReLU} \to \text{GAP}(输出长度 1616)→FC\to \text{FC}(输出长度 88)→Softmax→Classification\to \text{Softmax} \to \text{Classification}

括号中前两个数字依次表示卷积核数量与卷积核宽度,“/2/2”表示卷积步长为 22。训练优化超参数为:SGDM优化器,动量系数 0.90.9,L2正则化系数 0.00010.0001,小批量大小(mini-batch size)128128,总训练轮次 100100(前 4040 轮学习率为 0.10.1,中间 4040 轮为 0.010.01,最后 2020 轮为 0.0010.001)。


二、完整MATLAB程序

在MATLAB深度学习工具箱(Deep Learning Toolbox)中,每个自定义网络层需保存在与类名同名的独立 .m 文件中。将以下三个自定义层文件与主程序脚本置于同一工作目录下即可运行。

1. 自定义绝对值层 AbsLayer.m

classdef AbsLayer < nnet.layer.Layer
    methods
        function layer = AbsLayer(name)
            if nargin == 1
                layer.Name = name;
            end
            layer.Description = "Element-wise absolute value";
        end

        function Z = predict(~, X)
            Z = abs(X);
        end

        function dLdX = backward(~, X, ~, dLdZ, ~)
            dLdX = dLdZ .* sign(X);
        end
    end
end

2. 自定义通道平均层 ChannelMeanLayer.m(用于RSBU-CS)

classdef ChannelMeanLayer < nnet.layer.Layer
    methods
        function layer = ChannelMeanLayer(name)
            if nargin == 1
                layer.Name = name;
            end
            layer.Description = "Average across channel dimension";
        end

        function Z = predict(~, X)
            % 输入维度为 [H, W, C, B],沿第3维(通道维)求均值
            Z = mean(X, 3);
        end

        function dLdX = backward(~, X, ~, dLdZ, ~)
            C = size(X, 3);
            dLdX = repmat(dLdZ, [1, 1, C, 1]) / C;
        end
    end
end

3. 自定义软阈值化层 SoftThresholdingLayer.m

classdef SoftThresholdingLayer < nnet.layer.Layer
    methods
        function layer = SoftThresholdingLayer(name)
            layer.NumInputs = 2;
            layer.InputNames = {'in', 'tau'};
            if nargin == 1
                layer.Name = name;
            end
            layer.Description = "Soft thresholding layer";
        end

        function Z = predict(~, X, tau)
            Z = sign(X) .* max(abs(X) - tau, 0);
        end

        function [dLdX, dLdTau] = backward(~, X, tau, ~, dLdZ, ~)
            mask = cast(abs(X) > tau, 'like', X);
            dLdX = dLdZ .* mask;

            dLdTauFull = -dLdZ .* sign(X) .* mask;
            dLdTau = sum(sum(dLdTauFull, 1), 2);
            if size(tau, 3) == 1 && size(X, 3) > 1
                dLdTau = sum(dLdTau, 3);
            end
        end
    end
end

4. 主程序与网络构建脚本 main_DRSN.m

%% 深度残差收缩网络(DRSN-CS / DRSN-CW)完整MATLAB程序
clear; clc; close all;

%% 1. 网络参数与数据格式说明
inputSize = [1, 2048, 1];   % [高度, 宽度, 通道数]
numClasses = 8;             % 分类类别数
mode = 'CW';                % 可选 'CS' (DRSN-CS) 或 'CW' (DRSN-CW)

% 构建网络拓扑
lgraph = buildDRSN(inputSize, numClasses, mode);

% 可视化网络结构(可选)
% analyzeNetwork(lgraph);

%% 2. 准备数据(示例占位数据,实际使用时替换为真实训练集与测试集)
% 数据维度须为 [1, 2048, 1, N],标签为长度为N的categorical向量
numTrain = 1280;
numTest  = 320;
XTrain = randn([inputSize, numTrain], 'single');
YTrain = categorical(randi([1, numClasses], [numTrain, 1]));
XTest  = randn([inputSize, numTest], 'single');
YTest  = categorical(randi([1, numClasses], [numTest, 1]));

%% 3. 训练超参数配置
options = trainingOptions('sgdm', ...
    'Momentum', 0.9, ...
    'L2Regularization', 1e-4, ...
    'MiniBatchSize', 128, ...
    'MaxEpochs', 100, ...
    'InitialLearnRate', 0.1, ...
    'LearnRateSchedule', 'piecewise', ...
    'LearnRateDropPeriod', 40, ...
    'LearnRateDropFactor', 0.1, ...
    'Shuffle', 'every-epoch', ...
    'Verbose', true, ...
    'VerboseFrequency', 10, ...
    'Plots', 'training-progress');

%% 4. 模型训练与测试
net = trainNetwork(XTrain, YTrain, lgraph, options);
YPred = classify(net, XTest);
acc = mean(YPred == YTest);
fprintf('Test Accuracy: %.2f%%\n', acc * 100);

%% ===================== 网络构建局部函数 =====================
function lgraph = buildDRSN(inputSize, numClasses, mode)
    lgraph = layerGraph();

    % 输入层与初始卷积层 Conv(4, 3, /2)
    layersInit = [
        imageInputLayer(inputSize, 'Normalization', 'none', 'Name', 'input')
        convolution2dLayer([1, 3], 4, 'Stride', [1, 2], 'Padding', 'same', 'Name', 'conv0')
    ];
    lgraph = addLayers(lgraph, layersInit);
    lastLayer = 'conv0';

    % 阶段1:输出通道数为4
    [lgraph, lastLayer] = addRSBU(lgraph, lastLayer, 4, 4, 2, mode, 'rsbu1_1');
    [lgraph, lastLayer] = addRSBU(lgraph, lastLayer, 4, 4, 1, mode, 'rsbu1_2');
    [lgraph, lastLayer] = addRSBU(lgraph, lastLayer, 4, 4, 1, mode, 'rsbu1_3');
    [lgraph, lastLayer] = addRSBU(lgraph, lastLayer, 4, 4, 1, mode, 'rsbu1_4');

    % 阶段2:输出通道数为8
    [lgraph, lastLayer] = addRSBU(lgraph, lastLayer, 4, 8, 2, mode, 'rsbu2_1');
    [lgraph, lastLayer] = addRSBU(lgraph, lastLayer, 8, 8, 1, mode, 'rsbu2_2');
    [lgraph, lastLayer] = addRSBU(lgraph, lastLayer, 8, 8, 1, mode, 'rsbu2_3');
    [lgraph, lastLayer] = addRSBU(lgraph, lastLayer, 8, 8, 1, mode, 'rsbu2_4');

    % 阶段3:输出通道数为16
    [lgraph, lastLayer] = addRSBU(lgraph, lastLayer, 8, 16, 2, mode, 'rsbu3_1');
    [lgraph, lastLayer] = addRSBU(lgraph, lastLayer, 16, 16, 1, mode, 'rsbu3_2');
    [lgraph, lastLayer] = addRSBU(lgraph, lastLayer, 16, 16, 1, mode, 'rsbu3_3');
    [lgraph, lastLayer] = addRSBU(lgraph, lastLayer, 16, 16, 1, mode, 'rsbu3_4');

    % 输出端:BN, ReLU, GAP, FC, Softmax, Classification
    layersOut = [
        batchNormalizationLayer('Name', 'bn_out')
        reluLayer('Name', 'relu_out')
        globalAveragePooling2dLayer('Name', 'gap_out')
        fullyConnectedLayer(numClasses, 'Name', 'fc_out')
        softmaxLayer('Name', 'softmax')
        classificationLayer('Name', 'output')
    ];
    lgraph = addLayers(lgraph, layersOut);
    lgraph = connectLayers(lgraph, lastLayer, 'bn_out');
end

function [lgraph, outName] = addRSBU(lgraph, inName, inChannels, outChannels, stride, mode, prefix)
    % 1. 主干路径:两层 [BN -> ReLU -> Conv]
    mainBranch = [
        batchNormalizationLayer('Name', [prefix '_bn1'])
        reluLayer('Name', [prefix '_relu1'])
        convolution2dLayer([1, 3], outChannels, 'Stride', [1, stride], 'Padding', 'same', 'Name', [prefix '_conv1'])
        batchNormalizationLayer('Name', [prefix '_bn2'])
        reluLayer('Name', [prefix '_relu2'])
        convolution2dLayer([1, 3], outChannels, 'Stride', [1, 1], 'Padding', 'same', 'Name', [prefix '_conv2'])
    ];
    lgraph = addLayers(lgraph, mainBranch);
    lgraph = connectLayers(lgraph, inName, [prefix '_bn1']);
    conv2Name = [prefix '_conv2'];

    % 2. 阈值估计子网络:Abs -> GAP
    absGapBranch = [
        AbsLayer([prefix '_abs'])
        globalAveragePooling2dLayer('Name', [prefix '_gap'])
    ];
    lgraph = addLayers(lgraph, absGapBranch);
    lgraph = connectLayers(lgraph, conv2Name, [prefix '_abs']);
    gapName = [prefix '_gap'];

    % 缩放因子分支:FC(M=C) -> BN -> ReLU -> FC -> Sigmoid
    if strcmpi(mode, 'CS')
        fc2Neurons = 1;
    elseif strcmpi(mode, 'CW')
        fc2Neurons = outChannels;
    else
        error("mode 参数必须为 'CS' 或 'CW'。");
    end

    scaleBranch = [
        fullyConnectedLayer(outChannels, 'Name', [prefix '_fc1'])
        batchNormalizationLayer('Name', [prefix '_fc_bn'])
        reluLayer('Name', [prefix '_fc_relu'])
        fullyConnectedLayer(fc2Neurons, 'Name', [prefix '_fc2'])
        sigmoidLayer('Name', [prefix '_sigmoid'])
    ];
    lgraph = addLayers(lgraph, scaleBranch);
    lgraph = connectLayers(lgraph, gapName, [prefix '_fc1']);

    % 均值分支与乘法得到阈值 tau
    lgraph = addLayers(lgraph, multiplicationLayer(2, 'Name', [prefix '_mul']));
    lgraph = connectLayers(lgraph, [prefix '_sigmoid'], [prefix '_mul/in1']);

    if strcmpi(mode, 'CS')
        lgraph = addLayers(lgraph, ChannelMeanLayer([prefix '_cmean']));
        lgraph = connectLayers(lgraph, gapName, [prefix '_cmean']);
        lgraph = connectLayers(lgraph, [prefix '_cmean'], [prefix '_mul/in2']);
    else
        lgraph = connectLayers(lgraph, gapName, [prefix '_mul/in2']);
    end

    % 3. 软阈值化层
    lgraph = addLayers(lgraph, SoftThresholdingLayer([prefix '_st']));
    lgraph = connectLayers(lgraph, conv2Name, [prefix '_st/in']);
    lgraph = connectLayers(lgraph, [prefix '_mul'], [prefix '_st/tau']);

    % 4. 残差快捷连接与逐元素相加
    outName = [prefix '_add'];
    lgraph = addLayers(lgraph, additionLayer(2, 'Name', outName));
    lgraph = connectLayers(lgraph, [prefix '_st'], [outName '/in1']);

    if stride ~= 1 || inChannels ~= outChannels
        projName = [prefix '_proj'];
        lgraph = addLayers(lgraph, convolution2dLayer([1, 1], outChannels, ...
            'Stride', [1, stride], 'Padding', 'same', 'Name', projName));
        lgraph = connectLayers(lgraph, inName, projName);
        lgraph = connectLayers(lgraph, projName, [outName '/in2']);
    else
        lgraph = connectLayers(lgraph, inName, [outName '/in2']);
    end
end

参考文献

Deep Residual Shrinkage Networks for Fault Diagnosis[J]. IEEE Transactions on Industrial Informatics, 2020.

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0)

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。