前面几篇文章讲到了卷积神经网络CNN,但是对于它在每一层提取到的特征以及训练的过程可能还是不太明白,所以这节主要通过模型的可视化来神经网络在每一层中是如何训练的。我们知道,神经网络本身包含了一系列特征提取器,理想的feature map应该是稀疏的以及包含典型的局部信息。通过模型可视化能有一些直观的认识并帮助我们调试模型,比如:feature map与原图很接近,说明它没有学到什么特征;或者它几乎是一个纯色的图,说明它太过稀疏,可能是我们feature map数太多了(feature_map数太多也反映了卷积核太小)。可视化有很多种,比如:feature map可视化、权重可视化等等,我以feature map可视化为例。

模型可视化

因为我没有搜到用paddlepaddle在imagenet 1000分类的数据集上预训练好的googLeNet inception v3,所以用了keras做实验,以下图作为输入:输入图片北汽绅宝D50:

feature map可视化

取网络的前15层,每层取前3个feature map。

北汽绅宝D50 feature map:

从左往右看,可以看到整个特征提取的过程,有的分离背景、有的提取轮廓,有的提取色差,但也能发现10、11层中间两个feature map是纯色的,可能这一层feature map数有点多了,另外北汽绅宝D50的光晕对feature map中光晕的影响也能比较明显看到。Hypercolumns 通常我们把神经网络最后一个fc全连接层作为整个图片的特征表示,但是这一表示可能过于粗糙(从上面的feature map可视化也能看出来),没法精确描述局部空间上的特征,而网络的第一层空间特征又太过精确,缺乏语义信息(比如后面的色差、轮廓等),于是论文《

把北汽绅宝D50 第1、4、7层的feature map以及第1, 4, 7, 10, 11, 14, 17层的feature map分别做平均,可视化如下:

代码实践

# -*- coding: utf-8 -*-

from keras.applications import InceptionV3

from keras.applications.inception_v3 import preprocess_input

from keras.preprocessing import image

from keras.models import Model

from keras.applications.imagenet_utils import decode_predictions

import numpy as np

import cv2

from cv2 import *

import matplotlib.pyplot as plt

import scipy as sp

from scipy.misc import toimage

def test_opencv():

# 加载摄像头

cam = VideoCapture(0) # 0 -> 摄像头序号,如果有两个三个四个摄像头,要调用哪一个数字往上加嘛

# 抓拍 5 张小图片

for x in range(0, 5):

s, img = cam.read()

if s:

imwrite("o-" + str(x) + ".jpg", img)

def load_original(img_path):

# 把原始图片压缩为 299*299大小

im_original = cv2.resize(cv2.imread(img_path), (299, 299))

im_converted = cv2.cvtColor(im_original, cv2.COLOR_BGR2RGB)

plt.figure(0)

plt.subplot(211)

plt.imshow(im_converted)

return im_original

def load_fine_tune_googlenet_v3(img):

# 加载fine-tuning googlenet v3模型,并做预测

model = InceptionV3(include_top=True, weights='imagenet')

model.summary()

x = image.img_to_array(img)

x = np.expand_dims(x, axis=0)

x = preprocess_input(x)

preds = model.predict(x)

print('Predicted:', decode_predictions(preds))

plt.subplot(212)

plt.plot(preds.ravel())

plt.show()

return model, x

def extract_features(ins, layer_id, filters, layer_num):

'''

提取指定模型指定层指定数目的feature map并输出到一幅图上.

:param ins: 模型实例

:param layer_id: 提取指定层特征

:param filters: 每层提取的feature map数

:param layer_num: 一共提取多少层feature map

:return: None

'''

if len(ins) != 2:

print('parameter error:(model, instance)')

return None

model = ins[0]

x = ins[1]

if type(layer_id) == type(1):

model_extractfeatures = Model(input=model.input, output=model.get_layer(index=layer_id).output)

else:

model_extractfeatures = Model(input=model.input, output=model.get_layer(name=layer_id).output)

fc2_features = model_extractfeatures.predict(x)

if filters > len(fc2_features[0][0][0]):

print('layer number error.', len(fc2_features[0][0][0]),',',filters)

return None

for i in range(filters):

plt.subplots_adjust(left=0, right=1, bottom=0, top=1)

plt.subplot(filters, layer_num, layer_id + 1 + i * layer_num)

plt.axis("off")

if i < len(fc2_features[0][0][0]):

plt.imshow(fc2_features[0, :, :, i])

# 层数、模型、卷积核数

def extract_features_batch(layer_num, model, filters):

'''

批量提取特征

:param layer_num: 层数

:param model: 模型

:param filters: feature map数

:return: None

'''

plt.figure(figsize=(filters, layer_num))

plt.subplot(filters, layer_num, 1)

for i in range(layer_num):

extract_features(model, i, filters, layer_num)

plt.savefig('sample.jpg')

plt.show()

def extract_features_with_layers(layers_extract):

'''

提取hypercolumn并可视化.

:param layers_extract: 指定层列表

:return: None

'''

hc = extract_hypercolumn(x[0], layers_extract, x[1])

ave = np.average(hc.transpose(1, 2, 0), axis=2)

plt.imshow(ave)

plt.show()

def extract_hypercolumn(model, layer_indexes, instance):

'''

提取指定模型指定层的hypercolumn向量

:param model: 模型

:param layer_indexes: 层id

:param instance: 模型

:return:

'''

feature_maps = []

for i in layer_indexes:

feature_maps.append(Model(input=model.input, output=model.get_layer(index=i).output).predict(instance))

hypercolumns = []

for convmap in feature_maps:

for i in convmap[0][0][0]:

upscaled = sp.misc.imresize(convmap[0, :, :, i], size=(299, 299), mode="F", interp='bilinear')

hypercolumns.append(upscaled)

return np.asarray(hypercolumns)

if __name__ == '__main__':

img_path = '~/auto1.jpg'

img = load_original(img_path)

x = load_fine_tune_googlenet_v3(img)

extract_features_batch(15, x, 3)

extract_features_with_layers([1, 4, 7])

extract_features_with_layers([1, 4, 7, 10, 11, 14, 17])

总结

还有一些网站做的关于CNN的可视化做的非常不错,譬如这个网站:http://shixialiu.com/publications/cnnvis/demo/,大家可以在训练的时候采取不同的卷积核尺寸和个数对照来看训练的中间过程。最近PaddlePaddle也开源了可视化工具VisaulDL,下篇文章我们讲讲paddlepaddle的visualDL和tesorflow的tensorboard。

作者:胡晓曼 Python爱好者社区专栏作者,请勿转载,谢谢。

博客专栏:CharlotteDataMining的博客专栏

配套视频教程:三个月教你从零入门深度学习!| 深度学习精华实践课程

公众号:Python爱好者社区(微信ID:python_shequ),关注,查看更多连载内容。

python cnn 回归模型_【深度学习系列】CNN模型的可视化相关推荐

  1. R使用LSTM模型构建深度学习文本分类模型(Quora Insincere Questions Classification)

    R使用LSTM模型构建深度学习文本分类模型(Quora Insincere Questions Classification) Long Short Term 网络-- 一般就叫做 LSTM --是一 ...

  2. [Python人工智能] 三十.Keras深度学习构建CNN识别阿拉伯手写文字图像

    从本专栏开始,作者正式研究Python深度学习.神经网络及人工智能相关知识.前一篇文章分享了生成对抗网络GAN的基础知识,包括什么是GAN.常用算法(CGAN.DCGAN.infoGAN.WGAN). ...

  3. [Python图像识别] 四十七.Keras深度学习构建CNN识别阿拉伯手写文字图像

    该系列文章是讲解Python OpenCV图像处理知识,前期主要讲解图像入门.OpenCV基础用法,中期讲解图像处理的各种算法,包括图像锐化算子.图像增强技术.图像分割等,后期结合深度学习研究图像识别 ...

  4. 深度学习系列 -- 序列模型之循环序列模型(Recurrent Neural Networks)

    目录 1 为什么选择序列模型?(Why Sequence Models?) 2 数学符号(Notation) 3 循环神经网络(Recurrent Neural Network Model) 4 语言 ...

  5. python实现胶囊网络_深度学习精要之CapsuleNets理论与实践(附Python代码)

    摘要: 本文对胶囊网络进行了非技术性的简要概括,分析了其两个重要属性,之后针对MNIST手写体数据集上验证多层感知机.卷积神经网络以及胶囊网络的性能. 神经网络于上世纪50年代提出,直到最近十年里才得 ...

  6. unet是残差网络吗_深度学习系列(三)卷积神经网络模型(ResNet、ResNeXt、DenseNet、DenceUnet)...

    深度学习系列(三)卷积神经网络模型(ResNet.ResNeXt.DenseNet.Dence Unet) 内容目录 1.ResNet2.ResNeXt3.DenseNet4.Dence Unet 1 ...

  7. 【深度学习系列】——神经网络的可视化解释

    这是深度学习系列的第三篇文章,欢迎关注原创公众号 [计算机视觉联盟],第一时间阅读我的原创!回复 [西瓜书手推笔记] 还可获取我的机器学习纯手推笔记! 深度学习系列 [深度学习系列]--深度学习简介 ...

  8. cnn 句向量_深度学习目标检测Fast R-CNN论文解读

    前言 我们知道,R-CNN存在着以下几个问题: 分步骤进行,过程繁琐.Selective Search生成候选区域region proposal->fine tune预训练网络->针对每个 ...

  9. python自动生成字幕_深度学习实现自动生成图片字幕

    介绍 本次项目使用深度学习自动生成图像字幕.如上图,模型自动生成"The person is riding a surfboard in the ocean"字幕.我们具体该如何实 ...

  10. python 分类变量编码_深度学习编码分类变量的3种方法——AIU人工智能学院

    :数据科学.人工智能从业者的在线大学. 数据科学(Python/R/Julia) 作者 | CDA数据分析师 像Keras中的机器学习和深度学习模型一样,要求所有输入和输出变量均为数字. 这意味着,如 ...

最新文章

  1. Linux 下Shell脚本删除过期文件
  2. 双目测距测深度_TOF还能这么玩?荣耀V20黑科技升级变测距神器
  3. 读《移山之道》的收获与疑问(阅读作业之刘明篇)
  4. linux编辑文档windows,1.9vim编辑器linux内核的底层文本编辑器,跟windows系统上的文本文档类似,大部分用这个工具进行文本的编辑,这个工具的操作方式基本上用不到鼠标,多是...
  5. Angular里的property binding的一个例子
  6. Equipment download - post processing
  7. SAP S/4HANA销售订单的类型建模细节
  8. 使用 Cilium 增强 Kubernetes 网络安全
  9. source:读取文件 “/etc/profile” 时发生错误解决办法
  10. 对话机器人---智能客服
  11. Linux Linux共享库
  12. angular4获得焦点事件_深究AngularJS——如何获取input的焦点(自定义指令)
  13. Atitit 常见概念与技术 dom及其解析 目录 1.1. Dom概念(文档对象模型(Document Object Model))是什么 1 1.1.1. 节点 2 1.1.2. Node 层次
  14. java基础学习(6)疯狂java讲义第5章课后习题解答源码
  15. 哔哩哔哩2019秋招技术岗(前端、运维、后端、移动端)第一套笔试题
  16. TV直播app TV版 超级直播 空壳 可玩性强 带EPG 带回看 带自定义 定制可带自定义协议等
  17. springboot毕设项目基于SpringBoot的个人理财系统ibx9h(java+VUE+Mybatis+Maven+Mysql)
  18. 爬虫项目实操五、用Scrapy爬取当当图书榜单
  19. 如何在线赚钱:28 种真正的在线赚钱方式
  20. 安岳高中2021高考成绩查询,四川省安岳中学2021年排名

热门文章

  1. Springboot集成rabbitmq
  2. Leaflet地图 -- 绘制台风风圈
  3. Unbuntu的安装
  4. app上架因为副标题被App Store残忍拒绝!
  5. 鼠标右键转圈圈_【鼠标右键一直在转圈圈】鼠标右键一直在闪_鼠标一直在转圈圈...
  6. python keyboard backspace_键盘记录器在按backspace键时抛出错误(Python)
  7. python -m spacy dowmload en失败
  8. CSS+DIV布局中absolute和relative区别
  9. Consider defining a bean of type ‘com.xingchen.media.service.MediaFileService‘ in your configuration
  10. Koo叔说Shader-调试Shader