知行编程网知行编程网  2022-07-21 15:00 知行编程网 隐藏边栏 |   抢沙发  5 
文章评分 0 次,平均分 0.0




服不服?40行Python代码,实现卷积特征可视化

选自 | towardsdatascience   作者 | Fabio M. Graetz
编译 | 机器之心

卷积神经网络(CNN)变革了计算机视觉,并将彻底改变整个世界。因此,开发解释 CNN 的技术也同样是一个重要的研究领域。本文将向你解释如何仅使用 40 行 Python 代码将卷积特征可视化。


服不服?40行Python代码,实现卷积特征可视化

本文的结构如下:首先,我将展示 VGG-16 网络的几个层次中的卷积特征的可视化;然后,尝试理解其中一些可视化,我将展示如何快速测试一个假设,即特定的滤波器会检测到哪种模式;最后,我将解释创建本文中提供的模式所需的代码。

   特征可视化

神经网络学习将输入数据(如图像)转换为越来越有意义但表征越来越复杂的连续层。

你可以将深度网络看做一个多阶段信息蒸馏操作,其中信息通过连续的滤波器并不断被「提纯」。(François Chollet, Deep Learning with Python (Shelter Island, NY: Manning Publications, 2018), p. 9)

阅读完他的文章后,你将了解如何生成模式,以最大化这些层次表征的某个层中所选特征图的平均激活,如何解释其中一些可视化,以及最终如何测试所选滤波器可能响应的模式或纹理的假设。你可以在下面找到 VGG-16 网络多个层中滤波器的特征可视化。在查看它们时,希望你能观察到生成模式的复杂性如何随着进入网络的深度而增加。

Layer 7: Conv2d(64, 128)

服不服?40行Python代码,实现卷积特征可视化
滤波器 12, 16, 86, 110(左上到右下,逐行)

Layer 14: Conv2d(128, 256)

服不服?40行Python代码,实现卷积特征可视化
滤波器 1, 6, 31, 32, 54, 77, 83, 97, 125, 158, 162, 190(左上到右下,逐行)

Layer 20: Conv2d(256, 256)

服不服?40行Python代码,实现卷积特征可视化
滤波器 3, 34, 39, 55, 62, 105, 115, 181, 231(左上到右下,逐行)

Layer 30: Conv2d(512, 512)

服不服?40行Python代码,实现卷积特征可视化
服不服?40行Python代码,实现卷积特征可视化
滤波器 54, 62, 67, 92, 123, 141, 150, 172, 180, 213, 233, 266, 277, 293, 331, 350, 421, 427(左上到右下,逐行)

Layer 40: Conv2d(512, 512)—top of the network

服不服?40行Python代码,实现卷积特征可视化
服不服?40行Python代码,实现卷积特征可视化
滤波器 4, 9, 34, 35, 75, 123, 150, 158, 203, 234, 246, 253, 256, 261, 265, 277, 286, 462(左上到右下,逐行)

这些模式让我觉得非常震撼!部分原因是,它们太漂亮了,我都想立马将它们裱起来挂在墙上;但主要的原因是,它们仅仅是通过最大化由数千张图像训练出的数学方程中的某个值得到的。在浏览通过最大化最后一层卷积层特征图的平均激活得到的 512 个模式时,我经常发出感慨「哇,这是一只鸡」,或「这不是一根羽毛嘛」。

   识别模式

我们来尝试解释几个可视化的特征。从这个开始,有没有让你想起些什么?


服不服?40行Python代码,实现卷积特征可视化
第 40 层第 286 个滤波器

这张照片立刻让我想起了教堂拱形天花板的圆拱。

服不服?40行Python代码,实现卷积特征可视化

来,让我们检验一下。人造的那张图片是通过最大化第 40 层第 286 个特征图的平均激活创造出来的。我们来看看当把拱门的照片输入网络后,第 40 层特征图的平均激活会是怎样:

服不服?40行Python代码,实现卷积特征可视化

看到了什么?正如期望的那样,特征图上的 286 处有一个极强的尖峰。所以,这是否意味着第 40 层第 286 个滤波器是负责检测拱形天花板的呢?这里我们要小心一点,滤波器 286 显然会响应图像中的拱形结构,但请记住,这样的拱形结构可能会在几个不同的类别中起到重要作用。

注意:虽然我使用第 40 层(卷积层)来生成我们当前正在查看的图像,但我使用了第 42 层来生成显示每个特征图的平均激活的图。第 41 和 42 层是 batch-norm 和 ReLU。ReLU 激活函数删除所有负值,选择第 42 层而不是 40 的唯一原因是,后者将显示大量负噪声,这使得我们很难看到我们感兴趣的正峰值。

再来一例。

服不服?40行Python代码,实现卷积特征可视化
第 40 层第 256 个滤波器

我敢保证,这些是鸡头(或者至少是鸟头)!从图中我们可以看到尖尖的喙和黑色的眼睛。我们可以用下面的这个图片来检验:

服不服?40行Python代码,实现卷积特征可视化

类似地,特征图上的 256 处会出现强烈的尖峰:

服不服?40行Python代码,实现卷积特征可视化

再来:

服不服?40行Python代码,实现卷积特征可视化
第 40 层第 462 个滤波器

滤波器 462 会不会对羽毛作出反应呢?来,输入一张羽毛图片:

服不服?40行Python代码,实现卷积特征可视化

Yes!滤波器 462 果然反应强烈:

服不服?40行Python代码,实现卷积特征可视化

猜一猜滤波器 265 会对什么产生响应?

服不服?40行Python代码,实现卷积特征可视化
第 40 层第 265 个滤波器

或许是链条吧?来,我们输入一张试试:

服不服?40行Python代码,实现卷积特征可视化

Yes,看起来猜对了!

服不服?40行Python代码,实现卷积特征可视化

不过从上图可以看到,除了最大的尖峰外,还有几个较大的次尖峰。我们看看对应的第 95 和第 303 个特征可视化图是什么:

服不服?40行Python代码,实现卷积特征可视化
第 40 层第 95 和第 303 个滤波器

再来看张比较酷的:

服不服?40行Python代码,实现卷积特征可视化
第 40 层第 64 个滤波器

有许多看起来像羽毛一样的结构,似乎还有鸟腿,左下方有个类似鸟头的东西。腿和喙显然比鸡的长,所以可能是一只鸟。我们将下面这幅图输入网络:

服不服?40行Python代码,实现卷积特征可视化

得到这样的特征图:

服不服?40行Python代码,实现卷积特征可视化

好吧,😂,在 64 处确实有个尖峰,但好像有许多比它更高的。让我们再来看看其中四个特征尖峰对应的滤波器生成的模式:

服不服?40行Python代码,实现卷积特征可视化
第 40 层第 172 和第 288 个滤波器

服不服?40行Python代码,实现卷积特征可视化
第 40 层第 437 和第 495 个滤波器

上面两幅(172、288)图看起来似乎有更多腿和眼睛/喙;不过下面两幅(437、495)我实在看不出它表示了什么。也许这些模式与图像的背景相关,或者只是代表网络检测到了一些我所不能理解的鸟类的信息。我想现在这个地方仍然是黑匣子的一部分。

再来最后一张,比较可爱,之后我们就直接进入代码部分。你能猜到这个是什么吗?

服不服?40行Python代码,实现卷积特征可视化
第 40 层第 277 个滤波器

我撸猫多年,所以我立马看到了毛茸茸的猫耳。左上角那个较大的最为明显。好,让我们输入一张猫图:

服不服?40行Python代码,实现卷积特征可视化

Yes,特征图上 277 处确实有一个强烈的尖峰,但是旁边更强烈的尖峰是怎么回事?

服不服?40行Python代码,实现卷积特征可视化

我们快速看下特征图 281 对应的模式图:

服不服?40行Python代码,实现卷积特征可视化
第 40 层第 281 个滤波器

也许是条纹猫的皮毛?

对于从网络中发现上述这样的秘密,我简直乐此不疲。但事实上,即使在最终的卷积层,大多数滤波器生成的模式对我来说还是非常抽象的。更为严格的方法应该是将网络应用于整个包含许多不同种类图像的数据集,并跟踪在某一层中激发特定滤波器的图像。

   代码详解

思路大致如下:我们从包含随机像素的图片开始,将它输入到评估模式的网络中,计算特定层中某个特征图的平均激活,然后计算输入图像像素值的梯度;知道像素值的梯度后,我们继续以最大化所选特征图的平均激活的方式更新像素值。

貌似这样说不好理解,那我们换种方式:网络权重是固定的,网络也不会被训练,我们试图找到一个图像,通过在像素值上执行梯度下降优化来最大化特定特征图的平均激活。

这个技术也叫做神经风格迁移。

为了实现这一点,我们需要:

  1. 从随机图像开始;

  2. 评估模式下的预训练网络;

  3. 一种访问我们感兴趣的任何隐藏层激活函数的方式;

  4. 用于计算渐梯度的损失函数和用于更新像素值的优化器。


我们先来生成一张带噪图作为输入。我们可以如下这样做:

<section style="box-sizing: border-box;padding: 0.5em;font-size: 14px;color: rgb(169, 183, 198);line-height: 18px;border-radius: 0px;background: rgb(40, 43, 46);font-family: Consolas, Inconsolata, Courier, monospace;display: block;overflow-x: auto;letter-spacing: 0px;margin-left: 8px;margin-right: 8px;overflow-wrap: normal !important;word-break: normal !important;overflow-y: auto !important;">img = np.uint8(np.random.uniform(<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">150</span>, <span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">180</span>, (sz, sz, <span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">3</span>)))/<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">255</span> </section>

其中 sz 是图像的长、宽,3 是颜色通道数,我们除以 255 是因为 uint8 类型的变量最大值是 255。如果你想得到更多或更少的噪声,可以修改 150 和 180。

然后我们用

<section style="box-sizing: border-box;padding: 0.5em;font-size: 14px;color: rgb(169, 183, 198);line-height: 18px;border-radius: 0px;background: rgb(40, 43, 46);font-family: Consolas, Inconsolata, Courier, monospace;display: block;overflow-x: auto;letter-spacing: 0px;margin-left: 8px;margin-right: 8px;overflow-wrap: normal !important;word-break: normal !important;overflow-y: auto !important;"> img_var = V(img[None], requires_grad=True) </section>

将之转化为一个需要梯度的 PyTorch 变量。像素值需要梯度,因为我们要使用反向传播来优化它们。

接着,我们需要一个评估模式下(意味着其权重是不变的)的预训练网络。这可以用如下代码:

<section style="box-sizing: border-box;padding: 0.5em;font-size: 14px;color: rgb(169, 183, 198);line-height: 18px;border-radius: 0px;background: rgb(40, 43, 46);font-family: Consolas, Inconsolata, Courier, monospace;display: block;overflow-x: auto;letter-spacing: 0px;margin-left: 8px;margin-right: 8px;overflow-wrap: normal !important;word-break: normal !important;overflow-y: auto !important;">model = vgg16(pre=True).eval()<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />set_trainable(model, False).</section>

再然后,我们需要一种方式来获取隐藏层的特征。我们可以采用在我们感兴趣的某个隐藏层后进行截断的方式获取,这样该隐藏层就成了输出层。不过在 PyTorch 中有一种更好的方法来解决这个问题,称为」hook」,可以在 PyTorch 的 Module 或 Tensor 中说明。要理解这点,你需要知道:

  1. PyTorch Module 是所有神经网络模块的基本类;

  2. 我们的神经网络的每个层都是一个 Module ;

  3. 每个 Module 都有一个称为 forward 的方法,当给 Module 一个输入时它会计算输出。


当我们将噪声图输入到我们的网络中时,forward 方法就会计算出第一层的输出结果;第二层的输入是前一层 forward 方法的输出结果;以此类推。当我们在某个层「register forward hook」时,在该层的 forward 方法被调用后将执行「hook」。

例如,当我们对层 i 的特征映射感兴趣时,我们在 i 层 register 一个「forword hook」;当层 i 的 forward 方法被调用后,层 i 的特征就会保存在一个变量里。

保存变量的类如下:

<section style="box-sizing: border-box;padding: 0.5em;font-size: 14px;color: rgb(169, 183, 198);line-height: 18px;border-radius: 0px;background: rgb(40, 43, 46);font-family: Consolas, Inconsolata, Courier, monospace;display: block;overflow-x: auto;letter-spacing: 0px;margin-left: 8px;margin-right: 8px;overflow-wrap: normal !important;word-break: normal !important;overflow-y: auto !important;"><span style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"><span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">class</span> <span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">SaveFeatures</span>():<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />    <span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">def</span> <span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">__init__</span>(<span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">self</span>, <span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">module</span>):<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />        <span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">self</span>.<span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">hook</span> </span>= <span style="box-sizing: border-box;font-size: inherit;color: rgb(248, 35, 117);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">module</span>.register_forward_hook(self.hook_fn)<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />    def hook_fn(self, <span style="box-sizing: border-box;font-size: inherit;color: rgb(248, 35, 117);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">module</span>, input, output):<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />        self.features = torch.tensor(output,requires_grad=True).cuda()<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />    def close(self):<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />        self.hook.remove()</section>

当执行 hook 时,调用方法 hook_fn。hook_fn 方法会将层输出保存在 self.features。注意这个张量是需要梯度的,因为我们要在像素值上执行反向传播。

怎么用 SaveFeatures 对象呢?

对层 i 的 hook 为:

<section style="box-sizing: border-box;padding: 0.5em;font-size: 14px;color: rgb(169, 183, 198);line-height: 18px;border-radius: 0px;background: rgb(40, 43, 46);font-family: Consolas, Inconsolata, Courier, monospace;display: block;overflow-x: auto;letter-spacing: 0px;margin-left: 8px;margin-right: 8px;overflow-wrap: normal !important;word-break: normal !important;overflow-y: auto !important;">activations = SaveFeatures(list(self.model.children())[i])</section>

当你用 model(img_var) 将模型应用到图像上后,你可以通过 hook 保存在 activations.features 来访问特征。注意别忘了一点,在访问完毕后使用 close 释放内存。

好了,现在我们已经能够访问层 i 的特征图了。特征图的形式为 [ 1, 512, 7, 7 ],其中 1 表示批维度,512 表示滤波器/特征图的个数,7 表示特征图的长和宽。我们的目标就是最大化选择的某一特征图 j 的平均激活值。因此我们定义如下损失函数:

<section style="box-sizing: border-box;padding: 0.5em;font-size: 14px;color: rgb(169, 183, 198);line-height: 18px;border-radius: 0px;background: rgb(40, 43, 46);font-family: Consolas, Inconsolata, Courier, monospace;display: block;overflow-x: auto;letter-spacing: 0px;margin-left: 8px;margin-right: 8px;overflow-wrap: normal !important;word-break: normal !important;overflow-y: auto !important;">loss = -activations.features[<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">0</span>, j].mean()</section>

以及优化器:

<section style="box-sizing: border-box;padding: 0.5em;font-size: 14px;color: rgb(169, 183, 198);line-height: 18px;border-radius: 0px;background: rgb(40, 43, 46);font-family: Consolas, Inconsolata, Courier, monospace;display: block;overflow-x: auto;letter-spacing: 0px;margin-left: 8px;margin-right: 8px;overflow-wrap: normal !important;word-break: normal !important;overflow-y: auto !important;">optimizer = torch.optim.Adam([img_var], lr=lr, weight_decay=<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">1e-6</span>)</section>

默认情况下,优化器可以最大限度地减少损失,因此我们只需将平均激活乘以 -1 即可告知优化器最大化损失。使用 optimizer.zero_grad() 重置梯度,使用 loss.backward() 计算像素值的梯度,并使用 optimizer.step() 更改像素值。

我们现在已经有了所有需要的东西:从随机图像开始,在评估模式下定义预先训练的网络,执行前向传播以获取第 i 层的特征,并定义了允许我们更改像素值以最大化层 i 中特征映射 j 的平均激活的优化器和损失函数。

好,让我们看一个例子:

服不服?40行Python代码,实现卷积特征可视化
第 40 层,第 265 个滤波器

等等,这不正是我们想要的吗?和前面的链条模式很相似;如果你眯着眼睛看,就可以看到链条。但可以肯定的是,我们获得的特征图的局部性必定非常差,因此我们必须找到一种方法来指导我们的优化器以获得最小化模式或者或「更好看」的模式。与我前面展示的模式相反,这张图由高频模式占主导,类似于对抗样本。那么我们该怎么解决这个问题呢?我尝试了不同的优化器、学习速率以及正则化,但似乎没有任何东西可以减少高频模式。

接下来,我变化了一下输入噪声图像的尺寸:

服不服?40行Python代码,实现卷积特征可视化
图像大小分别为 200x200、300x300、400x400。

在这三幅图中,有没有发现「链状图案」的频率随着图像尺寸的增加而增加?由于卷积滤波器具有固定的尺寸,因此当图像分辨率增大时,滤波器的相对尺寸就会变小。换句话说:假设创建的模式都是以像素为单位,当我们增加图像尺寸,则生成图案的相对尺寸将减小,而图案的频率将增加。

如果我的假设是正确的,那么我们想要的是低分辨率样本(甚至比上面显示的还低)但高分辨的低频模式。这有意义吗?以及怎么做?

我的解决方案是:首先从非常低分辨率的图像开始,即 56×56 像素,优化像素值几步,然后将图像尺寸增加一定的系数;在对图像放大后,再将像素值优化几步;然后再次对图像进行放大...

这样获得的结果出奇的好,一个低频、高分辨率、且没有太多噪音的模式图:

服不服?40行Python代码,实现卷积特征可视化
第 40 层,第 265 个滤波器。

我们现在有了一个分辨率好得多的低频模式,并且没有太多的噪音。为什么这样做会有用呢?我的想法是:当我们从低分辨率开始时,我们会得到低频模式。放大后,放大后的模式图相比直接用大尺度图像优化生成的模式图有较低的频率。因此,在下一次迭代中优化像素值时,我们处于一个更好的起点,看起来避免了局部最小值。这有意义吗?为了进一步减少高频模式,我在放大后稍微模糊了图像。

我发现以 1.2 的倍数放大 12 次之后得到的结果不错。

看看下面的代码。你会发现我们已经将重点信息都讲清了,例如创建随机图像、register hook、定义优化器和损失函数,以及优化像素值。唯一重要的新内容是:1)将代码封装到一个类中;2)我们在优化像素值后将图像放大了几次。

<section style="box-sizing: border-box;padding: 0.5em;font-size: 14px;color: rgb(169, 183, 198);line-height: 18px;border-radius: 0px;background: rgb(40, 43, 46);font-family: Consolas, Inconsolata, Courier, monospace;display: block;overflow-x: auto;letter-spacing: 0px;margin-left: 8px;margin-right: 8px;overflow-wrap: normal !important;word-break: normal !important;overflow-y: auto !important;"><span style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"><span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">class</span> <span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">FilterVisualizer</span>():<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />    <span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">def</span> <span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">__init__</span>(<span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">self</span>, <span style="line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">size</span></span>=<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">56</span>, upscaling_steps=<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">12</span>, upscaling_factor=<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">1.2</span>):<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />        self.size, self.upscaling_steps, self.upscaling_factor = size, upscaling_steps, upscaling_factor<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />        self.model = vgg16(pre=True).cuda().eval()<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />        set_trainable(self.model, False)<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  /><br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />    def visualize(self, layer, filter, lr=<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">0.1</span>, opt_steps=<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">20</span>, blur=None):<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />        sz = self.size<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />        img = np.uint8(np.random.uniform(<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">150</span>, <span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">180</span>, (sz, sz, <span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">3</span>)))/<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">255</span>  # generate random image<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />        activations = SaveFeatures(list(self.model.children())[layer])  # register hook<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  /><br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />        <span style="box-sizing: border-box;font-size: inherit;color: rgb(248, 35, 117);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">for</span> _ <span style="box-sizing: border-box;font-size: inherit;color: rgb(248, 35, 117);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">in</span> range(self.upscaling_steps):  # scale the image up upscaling_steps times<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />            train_tfms, val_tfms = tfms_from_model(vgg16, sz)<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />            img_var = V(val_tfms(img)[None], requires_grad=True)  # convert image to Variable that requires grad<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />            optimizer = torch.optim.Adam([img_var], lr=lr, weight_decay=<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">1e-6</span>)<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />            <span style="box-sizing: border-box;font-size: inherit;color: rgb(248, 35, 117);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">for</span> n <span style="box-sizing: border-box;font-size: inherit;color: rgb(248, 35, 117);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">in</span> range(opt_steps):  # optimize pixel values <span style="box-sizing: border-box;font-size: inherit;color: rgb(248, 35, 117);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">for</span> opt_steps times<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />                optimizer.zero_grad()<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />                self.model(img_var)<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />                loss = -activations.features[<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">0</span>, filter].mean()<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />                loss.backward()<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />                optimizer.step()<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />            img = val_tfms.denorm(img_var.data.cpu().numpy()[<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">0</span>].transpose(<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">1</span>,<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">2</span>,<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">0</span>))<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />            self.output = img<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />            sz = int(self.upscaling_factor * sz)  # calculate <span style="box-sizing: border-box;font-size: inherit;color: rgb(248, 35, 117);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">new</span> image size<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />            img = cv2.resize(img, (sz, sz), interpolation = cv2.INTER_CUBIC)  # scale image up<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />            <span style="box-sizing: border-box;font-size: inherit;color: rgb(248, 35, 117);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">if</span> blur is not None: img = cv2.blur(img,(blur,blur))  # blur image to reduce high frequency patterns<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />        self.save(layer, filter)<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />        activations.close()<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  /><br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />    def save(self, layer, filter):<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />        plt.imsave(<span style="box-sizing: border-box;font-size: inherit;color: rgb(238, 220, 112);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">"layer_"</span>+str(layer)+<span style="box-sizing: border-box;font-size: inherit;color: rgb(238, 220, 112);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">"_filter_"</span>+str(filter)+<span style="box-sizing: border-box;font-size: inherit;color: rgb(238, 220, 112);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">".jpg"</span>, np.clip(self.output, <span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">0</span>, <span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">1</span>))</section>

使用 FilterVisualizer :

<section style="box-sizing: border-box;padding: 0.5em;font-size: 14px;color: rgb(169, 183, 198);line-height: 18px;border-radius: 0px;background: rgb(40, 43, 46);font-family: Consolas, Inconsolata, Courier, monospace;display: block;overflow-x: auto;letter-spacing: 0px;margin-left: 8px;margin-right: 8px;overflow-wrap: normal !important;word-break: normal !important;overflow-y: auto !important;">layer = <span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">40</span><br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />filter = <span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">265</span><br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />FV = FilterVisualizer(size=<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">56</span>, upscaling_steps=<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">12</span>, upscaling_factor=<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">1.2</span>)<br style="box-sizing: border-box;font-size: inherit;color: inherit;line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;"  />FV.visualize(layer, filter, blur=<span style="box-sizing: border-box;font-size: inherit;color: rgb(174, 135, 250);line-height: inherit;word-wrap: inherit !important;word-break: inherit !important;">5</span>)</section>

代码默认使用英伟达的 GPU,如果没有,可以在 google colab 上测试。

原文链接:https://towardsdatascience.com/how-to-visualize-convolutional-features-in-40-lines-of-code-70b7d87b0030

<section data-brushtype="text" style="padding-right: 0em;padding-left: 0em;white-space: normal;letter-spacing: 0.544px;color: rgb(62, 62, 62);font-family: "Helvetica Neue", Helvetica, "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;widows: 1;word-spacing: 2px;caret-color: rgb(255, 0, 0);text-align: center;"><strong style="color: rgb(0, 0, 0);font-family: -apple-system-font, system-ui, "Helvetica Neue", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;letter-spacing: 0.544px;"><span style="letter-spacing: 0.5px;font-size: 14px;"><strong style="font-size: 16px;letter-spacing: 0.544px;"><span style="letter-spacing: 0.5px;">—</span></strong>完<strong style="font-size: 16px;letter-spacing: 0.544px;"><span style="letter-spacing: 0.5px;font-size: 14px;"><strong style="font-size: 16px;letter-spacing: 0.544px;"><span style="letter-spacing: 0.5px;">—</span></strong></span></strong></span></strong></section><pre><pre><section style="letter-spacing: 0.544px;white-space: normal;font-family: -apple-system-font, system-ui, "Helvetica Neue", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;"><section powered-by="xiumi.us"><section style="margin-top: 15px;margin-bottom: 25px;opacity: 0.8;"><section><section style="letter-spacing: 0.544px;"><section powered-by="xiumi.us"><section style="margin-top: 15px;margin-bottom: 25px;opacity: 0.8;"><section><section style="margin-bottom: 15px;padding-right: 0em;padding-left: 0em;color: rgb(127, 127, 127);font-size: 12px;font-family: sans-serif;line-height: 25.5938px;letter-spacing: 3px;text-align: center;"><span style="color: rgb(0, 0, 0);"><strong><span style="font-size: 16px;font-family: 微软雅黑;caret-color: red;">为您推荐</span></strong></span></section><p style="margin: 5px 16px;padding-right: 0em;padding-left: 0em;font-family: sans-serif;letter-spacing: 0px;opacity: 0.8;line-height: normal;text-align: center;">深度学习框架简史:未来十年迎来黄金时期<br  /></p><section style="margin-top: 5px;margin-bottom: 5px;padding-right: 0em;padding-left: 0em;min-height: 1em;font-family: sans-serif;letter-spacing: 0px;opacity: 0.8;line-height: normal;text-align: center;">吃透空洞卷积(Dilated Convolutions)<br  /></section><section style="margin-top: 5px;margin-bottom: 5px;padding-right: 0em;padding-left: 0em;min-height: 1em;font-family: sans-serif;letter-spacing: 0px;opacity: 0.8;line-height: normal;text-align: center;"><span style="font-size: 14px;">13个算法工程师必须掌握的PyTorch Tricks</span></section><section style="margin-top: 5px;margin-bottom: 5px;padding-right: 0em;padding-left: 0em;min-height: 1em;font-family: sans-serif;letter-spacing: 0px;opacity: 0.8;line-height: normal;text-align: center;"><span style="font-size: 14px;">吴恩达上新:生成对抗网络(GAN)专项课程</span></section><section style="margin-top: 5px;margin-bottom: 5px;padding-right: 0em;padding-left: 0em;min-height: 1em;font-family: sans-serif;letter-spacing: 0px;opacity: 0.8;line-height: normal;text-align: center;">从SGD到NadaMax,十种优化算法原理及实现</section></section></section></section></section></section></section></section></section>

服不服?40行Python代码,实现卷积特征可视化

本篇文章来源于: 深度学习这件小事

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写

发表评论

表情 格式 链接 私密 签到
扫一扫二维码分享