MATLAB环境下可视化卷积神经网络CNN的激活图

发布于:2022-11-28 ⋅ 阅读:(662) ⋅ 点赞:(0)

深度学习,一个大号/深层的,现代的,黑箱的,信号/图像处理器。

本文简单讲解如何将图像输入到卷积神经网络CNN并显示网络不同层的激活图,并通过将激活图与原始图像进行比较以探索网络学习哪些特征

本例需要用到MATLAB Neural Network Toolbox(TM), Image Processing

Toolbox 和 the Neural Network Toolbox(TM) Model _for AlexNet Network_.

代码如下

🍞正在为您运送作品详情

加载预训练模型和数据

加载预训练的AlexNet 网络。如果Neural Network Toolbox Model _for AlexNet Network_没有安装,则MATLAB会提供下载链接。

net = alexnet;

读取一张图片并显示

imshow(im)
imgSize = size(im);
imgSize = imgSize(1:2);

可视化网络结构

显示网络的层信息,观察第一个卷积层有 96 个通道

net.Layers

ans =

25x1 Layer array with layers:

1 'data' Image Input 227x227x3 images with 'zerocenter' normalization
2 'conv1' Convolution 96 11x11x3 convolutions with stride [4 4] and padding [0 0]
3 'relu1' ReLU ReLU
4 'norm1' Cross Channel Normalization cross channel normalization with 5 channels per element
5 'pool1' Max Pooling 3x3 max pooling with stride [2 2] and padding [0 0]
6 'conv2' Convolution 256 5x5x48 convolutions with stride [1 1] and padding [2 2]
7 'relu2' ReLU ReLU
8 'norm2' Cross Channel Normalization cross channel normalization with 5 channels per element
9 'pool2' Max Pooling 3x3 max pooling with stride [2 2] and padding [0 0]
10 'conv3' Convolution 384 3x3x256 convolutions with stride [1 1] and padding [1 1]
11 'relu3' ReLU ReLU
12 'conv4' Convolution 384 3x3x192 convolutions with stride [1 1] and padding [1 1]
13 'relu4' ReLU ReLU
14 'conv5' Convolution 256 3x3x192 convolutions with stride [1 1] and padding [1 1]
15 'relu5' ReLU ReLU
16 'pool5' Max Pooling 3x3 max pooling with stride [2 2] and padding [0 0]
17 'fc6' Fully Connected 4096 fully connected layer
18 'relu6' ReLU ReLU
19 'drop6' Dropout 50% dropout
20 'fc7' Fully Connected 4096 fully connected layer
21 'relu7' ReLU ReLU
22 'drop7' Dropout 50% dropout
23 'fc8' Fully Connected 1000 fully connected layer
24 'prob' Softmax softmax
25 'output' Classification Output crossentropyex with 'tench', 'goldfish', and 998 other classes

显示第一个卷积层的激活图

act1 = activations(net,im,'conv1','OutputAs','channels');
sz = size(act1);
act1 = reshape(act1,[sz(1) sz(2) 1 sz(3)]);

使用mat2gray函数对输出进行规范化,并显示8 x 12的96张图像,层中的每个通道对应一张图像。

montage(mat2gray(act1),'Size',[8 12])

指定通道的激活图

调整通道 32 中激活的大小,使其与原始图像相同,并显示激活图

act1ch32 = act1(:,:,:,32);
act1ch32 = mat2gray(act1ch32);
act1ch32 = imresize(act1ch32,imgSize);
imshowpair(im,act1ch32,'montage')

查找最强的激活通道

[maxValue,maxValueIndex] = max(max(max(act1)));
act1chMax = act1(:,:,:,maxValueIndex);
act1chMax = mat2gray(act1chMax);
act1chMax = imresize(act1chMax,imgSize);
imshowpair(im,act1chMax,'montage')

下面研究更深的网络层的激活

以conv5层的激活图为例,代码与上面类似

conv5层的最强激活图

进一步查看通道3和通道5。

可视化relu5层的激活值

与conv5层的激活相比,relu5层清晰地精确定位图像中具有强烈激活的面部区域特征。

本文含有隐藏内容,请 开通VIP 后查看