【深度学习系列】CNN模型的可视化

简介: 【深度学习系列】CNN模型的可视化

模型可视化

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

  • 输入图片
  • 北汽绅宝 D50:



image.png

  • feature map 可视化

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

  北汽绅宝 D50 feature map:



网络异常,图片无法展示
|


从左往右看,可以看到整个特征提取的过程,有的分离背景、有的提取轮廓,有的提取色差,但也能发现 10、11 层中间两个 feature map 是纯色的,可能这一层 feature map 数有点多了,另外北汽绅宝 D50 的光晕对 feature map 中光晕的影响也能比较明显看到。


Hypercolumns

通常我们把神经网络最后一个 fc 全连接层作为整个图片的特征表示,但是这一表示可能过于粗糙(从上面的 feature map 可视化也能看出来),没法精确描述局部空间上的特征,而网络的第一层空间特征又太过精确,缺乏语义信息(比如后面的色差、轮廓等),于是论文《Hypercolumns for Object Segmentation and Fine-grained Localization》提出一种新的特征表示方法:Hypercolumns——将一个像素的 hypercolumn 定义为所有 cnn 单元对应该像素位置的激活输出值组成的向量),比较好的 tradeoff 了前面两个问题,直观地看如图:


image.png



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


image.png


代码实践

1# -*- coding: utf-8 -*-2from keras.applications import InceptionV3
  3from keras.applications.inception_v3 import preprocess_input
  4from keras.preprocessing import image
  5from keras.models import Model
  6from keras.applications.imagenet_utils import decode_predictions
  7import numpy as np
  8import cv2
  9from cv2 import *
 10import matplotlib.pyplot as plt
 11import scipy as sp
 12from scipy.misc import toimage
 1314deftest_opencv():15# 加载摄像头16     cam = VideoCapture(0)  # 0 -> 摄像头序号,如果有两个三个四个摄像头,要调用哪一个数字往上加嘛17# 抓拍 5 张小图片18for x inrange(0, 5):
 19         s, img = cam.read()
 20if s:
 21             imwrite("o-" + str(x) + ".jpg", img)
 2223defload_original(img_path):24# 把原始图片压缩为 299*299大小25     im_original = cv2.resize(cv2.imread(img_path), (299, 299))
 26     im_converted = cv2.cvtColor(im_original, cv2.COLOR_BGR2RGB)
 27     plt.figure(0)
 28     plt.subplot(211)
 29     plt.imshow(im_converted)
 30return im_original
 3132defload_fine_tune_googlenet_v3(img):33# 加载fine-tuning googlenet v3模型,并做预测34     model = InceptionV3(include_top=True, weights='imagenet')
 35     model.summary()
 36     x = image.img_to_array(img)
 37     x = np.expand_dims(x, axis=0)
 38     x = preprocess_input(x)
 39     preds = model.predict(x)
 40print('Predicted:', decode_predictions(preds))
 41     plt.subplot(212)
 42     plt.plot(preds.ravel())
 43     plt.show()
 44return model, x
 4546defextract_features(ins, layer_id, filters, layer_num):47'''
 48     提取指定模型指定层指定数目的feature map并输出到一幅图上.
 49     :param ins: 模型实例
 50     :param layer_id: 提取指定层特征
 51     :param filters: 每层提取的feature map数
 52     :param layer_num: 一共提取多少层feature map
 53     :return: None
 54     '''55iflen(ins) != 2:
 56print('parameter error:(model, instance)')
 57returnNone58     model = ins[0]
 59     x = ins[1]
 60iftype(layer_id) == type(1):
 61         model_extractfeatures = Model(input=model.input, output=model.get_layer(index=layer_id).output)
 62else:
 63         model_extractfeatures = Model(input=model.input, output=model.get_layer(name=layer_id).output)
 64     fc2_features = model_extractfeatures.predict(x)
 65if filters > len(fc2_features[0][0][0]):
 66print('layer number error.', len(fc2_features[0][0][0]),',',filters)
 67returnNone68for i inrange(filters):
 69         plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
 70         plt.subplot(filters, layer_num, layer_id + 1 + i * layer_num)
 71         plt.axis("off")
 72if i < len(fc2_features[0][0][0]):
 73             plt.imshow(fc2_features[0, :, :, i])
 7475# 层数、模型、卷积核数76defextract_features_batch(layer_num, model, filters):77'''
 78     批量提取特征
 79     :param layer_num: 层数
 80     :param model: 模型
 81     :param filters: feature map数
 82     :return: None
 83     '''84     plt.figure(figsize=(filters, layer_num))
 85     plt.subplot(filters, layer_num, 1)
 86for i inrange(layer_num):
 87         extract_features(model, i, filters, layer_num)
 88     plt.savefig('sample.jpg')
 89     plt.show()
 9091defextract_features_with_layers(layers_extract):92'''
 93     提取hypercolumn并可视化.
 94     :param layers_extract: 指定层列表
 95     :return: None
 96     '''97     hc = extract_hypercolumn(x[0], layers_extract, x[1])
 98     ave = np.average(hc.transpose(1, 2, 0), axis=2)
 99     plt.imshow(ave)
100     plt.show()
101102defextract_hypercolumn(model, layer_indexes, instance):103'''
104     提取指定模型指定层的hypercolumn向量
105     :param model: 模型
106     :param layer_indexes: 层id
107     :param instance: 模型
108     :return:
109     '''110     feature_maps = []
111for i in layer_indexes:
112         feature_maps.append(Model(input=model.input, output=model.get_layer(index=i).output).predict(instance))
113     hypercolumns = []
114for convmap in feature_maps:
115for i in convmap[0][0][0]:
116             upscaled = sp.misc.imresize(convmap[0, :, :, i], size=(299, 299), mode="F", interp='bilinear')
117             hypercolumns.append(upscaled)
118return np.asarray(hypercolumns)
119120if __name__ == '__main__':
121     img_path = '~/auto1.jpg'122     img = load_original(img_path)
123     x = load_fine_tune_googlenet_v3(img)
124     extract_features_batch(15, x, 3)
125     extract_features_with_layers([1, 4, 7])
126     extract_features_with_layers([1, 4, 7, 10, 11, 14, 17])


总结

还有一些网站做的关于 CNN 的可视化做的非常不错,譬如这个网站:http://shixialiu.com/publications/cnnvis/demo/,大家可以在训练的时候采取不同的卷积核尺寸和个数对照来看训练的中间过程。

相关文章
|
机器学习/深度学习 算法 定位技术
Baumer工业相机堡盟工业相机如何通过YoloV8深度学习模型实现裂缝的检测识别(C#代码UI界面版)
本项目基于YOLOv8模型与C#界面,结合Baumer工业相机,实现裂缝的高效检测识别。支持图像、视频及摄像头输入,具备高精度与实时性,适用于桥梁、路面、隧道等多种工业场景。
1595 27
|
机器学习/深度学习 数据可视化 算法
深度学习模型结构复杂、参数众多,如何更直观地深入理解你的模型?
深度学习模型虽应用广泛,但其“黑箱”特性导致可解释性不足,尤其在金融、医疗等敏感领域,模型决策逻辑的透明性至关重要。本文聚焦深度学习可解释性中的可视化分析,介绍模型结构、特征、参数及输入激活的可视化方法,帮助理解模型行为、提升透明度,并推动其在关键领域的安全应用。
1205 0
|
机器学习/深度学习 存储 PyTorch
Neural ODE原理与PyTorch实现:深度学习模型的自适应深度调节
Neural ODE将神经网络与微分方程结合,用连续思维建模数据演化,突破传统离散层的限制,实现自适应深度与高效连续学习。
1318 3
Neural ODE原理与PyTorch实现:深度学习模型的自适应深度调节
|
机器学习/深度学习 数据采集 人工智能
深度学习实战指南:从神经网络基础到模型优化的完整攻略
🌟 蒋星熠Jaxonic,AI探索者。深耕深度学习,从神经网络到Transformer,用代码践行智能革命。分享实战经验,助你构建CV、NLP模型,共赴二进制星辰大海。
|
机器学习/深度学习 数据采集 并行计算
多步预测系列 | LSTM、CNN、Transformer、TCN、串行、并行模型集合研究(Python代码实现)
多步预测系列 | LSTM、CNN、Transformer、TCN、串行、并行模型集合研究(Python代码实现)
1263 2
|
机器学习/深度学习 数据采集 运维
基于WOA-CNN-BiLSTM-Attention、CNN-BiLSTM-Attention、WOA-CNN-BiLSTM、CNN-BiLSTM、BiLSTM、CNN6模型单变量时序预测一键对比研究
基于WOA-CNN-BiLSTM-Attention、CNN-BiLSTM-Attention、WOA-CNN-BiLSTM、CNN-BiLSTM、BiLSTM、CNN6模型单变量时序预测一键对比研究
425 7
|
机器学习/深度学习 人工智能 自然语言处理
AI 基础知识从 0.3 到 0.4——如何选对深度学习模型?
本系列文章从机器学习基础出发,逐步深入至深度学习与Transformer模型,探讨AI关键技术原理及应用。内容涵盖模型架构解析、典型模型对比、预训练与微调策略,并结合Hugging Face平台进行实战演示,适合初学者与开发者系统学习AI核心知识。
993 15
|
机器学习/深度学习 数据采集 传感器
【WOA-CNN-LSTM】基于鲸鱼算法优化深度学习预测模型的超参数研究(Matlab代码实现)
【WOA-CNN-LSTM】基于鲸鱼算法优化深度学习预测模型的超参数研究(Matlab代码实现)
830 0
|
机器学习/深度学习 计算机视觉
基于CNN和大气散射模型的图像去雾
基于CNN和大气散射模型的图像去雾
|
机器学习/深度学习 算法 物联网
基于WOA-CNN-LSTM-Attention、CNN-LSTM-Attention、WOA-CNN-LSTM、CNN-LSTM、LSTM、CNN6模型多变量时序预测一键对比研究(Matlab代码)
基于WOA-CNN-LSTM-Attention、CNN-LSTM-Attention、WOA-CNN-LSTM、CNN-LSTM、LSTM、CNN6模型多变量时序预测一键对比研究(Matlab代码)
524 0

热门文章

最新文章