keras CNN卷积核可视化,热度图教程


Posted in Python onJune 22, 2020

卷积核可视化

import matplotlib.pyplot as plt
import numpy as np
from keras import backend as K
from keras.models import load_model

# 将浮点图像转换成有效图像
def deprocess_image(x):
 # 对张量进行规范化
 x -= x.mean()
 x /= (x.std() + 1e-5)
 x *= 0.1
 x += 0.5
 x = np.clip(x, 0, 1)
 # 转化到RGB数组
 x *= 255
 x = np.clip(x, 0, 255).astype('uint8')
 return x

# 可视化滤波器
def kernelvisual(model, layer_target=1, num_iterate=100):
 # 图像尺寸和通道
 img_height, img_width, num_channels = K.int_shape(model.input)[1:4]
 num_out = K.int_shape(model.layers[layer_target].output)[-1]

 plt.suptitle('[%s] convnet filters visualizing' % model.layers[layer_target].name)

 print('第%d层有%d个通道' % (layer_target, num_out))
 for i_kernal in range(num_out):
  input_img = model.input
  # 构建一个损耗函数,使所考虑的层的第n个滤波器的激活最大化,-1层softmax层
  if layer_target == -1:
   loss = K.mean(model.output[:, i_kernal])
  else:
   loss = K.mean(model.layers[layer_target].output[:, :, :, i_kernal]) # m*28*28*128
  # 计算图像对损失函数的梯度
  grads = K.gradients(loss, input_img)[0]
  # 效用函数通过其L2范数标准化张量
  grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5)
  # 此函数返回给定输入图像的损耗和梯度
  iterate = K.function([input_img], [loss, grads])
  # 从带有一些随机噪声的灰色图像开始
  np.random.seed(0)
  # 随机图像
  # input_img_data = np.random.randint(0, 255, (1, img_height, img_width, num_channels)) # 随机
  # input_img_data = np.zeros((1, img_height, img_width, num_channels)) # 零值
  input_img_data = np.random.random((1, img_height, img_width, num_channels)) * 20 + 128. # 随机灰度
  input_img_data = np.array(input_img_data, dtype=float)
  failed = False
  # 运行梯度上升
  print('####################################', i_kernal + 1)
  loss_value_pre = 0
  # 运行梯度上升num_iterate步
  for i in range(num_iterate):
   loss_value, grads_value = iterate([input_img_data])
   if i % int(num_iterate/5) == 0:
    print('Iteration %d/%d, loss: %f' % (i, num_iterate, loss_value))
    print('Mean grad: %f' % np.mean(grads_value))
    if all(np.abs(grads_val) < 0.000001 for grads_val in grads_value.flatten()):
     failed = True
     print('Failed')
     break
    if loss_value_pre != 0 and loss_value_pre > loss_value:
     break
    if loss_value_pre == 0:
     loss_value_pre = loss_value
    # if loss_value > 0.99:
    #  break
   input_img_data += grads_value * 1 # e-3
  img_re = deprocess_image(input_img_data[0])
  if num_channels == 1:
   img_re = np.reshape(img_re, (img_height, img_width))
  else:
   img_re = np.reshape(img_re, (img_height, img_width, num_channels))
  plt.subplot(np.ceil(np.sqrt(num_out)), np.ceil(np.sqrt(num_out)), i_kernal + 1)
  plt.imshow(img_re) # , cmap='gray'
  plt.axis('off')

 plt.show()

运行

model = load_model('train3.h5')
kernelvisual(model,-1) # 对最终输出可视化
kernelvisual(model,6) # 对第二个卷积层可视化

keras CNN卷积核可视化,热度图教程

keras CNN卷积核可视化,热度图教程

热度图

import cv2
import matplotlib.pyplot as plt
import numpy as np
from keras import backend as K
from keras.preprocessing import image

def heatmap(model, data_img, layer_idx, img_show=None, pred_idx=None):
 # 图像处理
 if data_img.shape.__len__() != 4:
  # 由于用作输入的img需要预处理,用作显示的img需要原图,因此分开两个输入
  if img_show is None:
   img_show = data_img
  # 缩放
  input_shape = K.int_shape(model.input)[1:3]  # (28,28)
  data_img = image.img_to_array(image.array_to_img(data_img).resize(input_shape))
  # 添加一个维度->(1, 224, 224, 3)
  data_img = np.expand_dims(data_img, axis=0)
 if pred_idx is None:
  # 预测
  preds = model.predict(data_img)
  # 获取最高预测项的index
  pred_idx = np.argmax(preds[0])
 # 目标输出估值
 target_output = model.output[:, pred_idx]
 # 目标层的输出代表各通道关注的位置
 last_conv_layer_output = model.layers[layer_idx].output
 # 求最终输出对目标层输出的导数(优化目标层输出),代表目标层输出对结果的影响
 grads = K.gradients(target_output, last_conv_layer_output)[0]
 # 将每个通道的导数取平均,值越高代表该通道影响越大
 pooled_grads = K.mean(grads, axis=(0, 1, 2))
 iterate = K.function([model.input], [pooled_grads, last_conv_layer_output[0]])
 pooled_grads_value, conv_layer_output_value = iterate([data_img])
 # 将各通道关注的位置和各通道的影响乘起来
 for i in range(conv_layer_output_value.shape[-1]):
  conv_layer_output_value[:, :, i] *= pooled_grads_value[i]

 # 对各通道取平均得图片位置对结果的影响
 heatmap = np.mean(conv_layer_output_value, axis=-1)
 # 规范化
 heatmap = np.maximum(heatmap, 0)
 heatmap /= np.max(heatmap)
 # plt.matshow(heatmap)
 # plt.show()
 # 叠加图片
 # 缩放成同等大小
 heatmap = cv2.resize(heatmap, (img_show.shape[1], img_show.shape[0]))
 heatmap = np.uint8(255 * heatmap)
 # 将热图应用于原始图像.由于opencv热度图为BGR,需要转RGB
 superimposed_img = img_show + cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)[:,:,::-1] * 0.4
 # 截取转uint8
 superimposed_img = np.minimum(superimposed_img, 255).astype('uint8')
 return superimposed_img, heatmap
 # 显示图片
 # plt.imshow(superimposed_img)
 # plt.show()
 # 保存为文件
 # superimposed_img = img + cv2.applyColorMap(heatmap, cv2.COLORMAP_JET) * 0.4
 # cv2.imwrite('ele.png', superimposed_img)

# 生成所有卷积层的热度图
def heatmaps(model, data_img, img_show=None):
 if img_show is None:
  img_show = np.array(data_img)
 # Resize
 input_shape = K.int_shape(model.input)[1:3] # (28,28,1)
 data_img = image.img_to_array(image.array_to_img(data_img).resize(input_shape))
 # 添加一个维度->(1, 224, 224, 3)
 data_img = np.expand_dims(data_img, axis=0)
 # 预测
 preds = model.predict(data_img)
 # 获取最高预测项的index
 pred_idx = np.argmax(preds[0])
 print("预测为:%d(%f)" % (pred_idx, preds[0][pred_idx]))
 indexs = []
 for i in range(model.layers.__len__()):
  if 'conv' in model.layers[i].name:
   indexs.append(i)
 print('模型共有%d个卷积层' % indexs.__len__())
 plt.suptitle('heatmaps for each conv')
 for i in range(indexs.__len__()):
  ret = heatmap(model, data_img, indexs[i], img_show=img_show, pred_idx=pred_idx)
  plt.subplot(np.ceil(np.sqrt(indexs.__len__()*2)), np.ceil(np.sqrt(indexs.__len__()*2)), i*2 + 1)\
   .set_title(model.layers[indexs[i]].name)
  plt.imshow(ret[0])
  plt.axis('off')
  plt.subplot(np.ceil(np.sqrt(indexs.__len__()*2)), np.ceil(np.sqrt(indexs.__len__()*2)), i*2 + 2)\
   .set_title(model.layers[indexs[i]].name)
  plt.imshow(ret[1])
  plt.axis('off')
 plt.show()

运行

from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input

model = VGG16(weights='imagenet')
data_img = image.img_to_array(image.load_img('elephant.png'))
# VGG16预处理:RGB转BGR,并对每一个颜色通道去均值中心化
data_img = preprocess_input(data_img)
img_show = image.img_to_array(image.load_img('elephant.png'))

heatmaps(model, data_img, img_show)

elephant.png

keras CNN卷积核可视化,热度图教程

keras CNN卷积核可视化,热度图教程

结语

踩坑踩得我脚疼

以上这篇keras CNN卷积核可视化,热度图教程就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
pycharm 使用心得(六)进行简单的数据库管理
Jun 06 Python
如何解决django配置settings时遇到Could not import settings 'conf.local'
Nov 18 Python
python实现矩阵乘法的方法
Jun 28 Python
Python获取暗黑破坏神3战网前1000命位玩家的英雄技能统计
Jul 04 Python
Python中Django发送带图片和附件的邮件
Mar 31 Python
详解Python 模拟实现生产者消费者模式的实例
Aug 10 Python
在python中实现将一张图片剪切成四份的方法
Dec 05 Python
Pytorch根据layers的name冻结训练方式
Jan 06 Python
python实现发送带附件的邮件代码分享
Sep 22 Python
Python ConfigParser模块的使用示例
Oct 12 Python
关于python scrapy中添加cookie踩坑记录
Nov 17 Python
教你用Python matplotlib库制作简单的动画
Jun 11 Python
python实现斗地主分牌洗牌
Jun 22 #Python
解决Keras使用GPU资源耗尽的问题
Jun 22 #Python
Keras - GPU ID 和显存占用设定步骤
Jun 22 #Python
Python 基于jwt实现认证机制流程解析
Jun 22 #Python
python中format函数如何使用
Jun 22 #Python
Tensorflow与Keras自适应使用显存方式
Jun 22 #Python
python数据类型强制转换实例详解
Jun 22 #Python
You might like
apache+codeigniter 通过.htcaccess做动态二级域名解析
2012/07/01 PHP
一个经典的PHP验证码类分享
2014/11/18 PHP
thinkPHP框架实现的无限回复评论功能示例
2018/06/09 PHP
PNG背景在不同浏览器下的应用
2009/06/22 Javascript
jQuery ajax在GBK编码下表单提交终极解决方案(非二次编码方法)
2010/10/20 Javascript
js生成随机数之random函数随机示例
2013/12/20 Javascript
jquery.post用法示例代码
2014/01/03 Javascript
js 数组操作之pop,push,unshift,splice,shift
2014/01/29 Javascript
Javascript的setTimeout()使用闭包特性时需要注意的问题
2014/09/23 Javascript
Jquery实现地铁线路指示灯提示牌效果的方法
2015/03/02 Javascript
js实现分享到随页面滚动而滑动效果的方法
2015/04/10 Javascript
KnockoutJS 3.X API 第四章之数据控制流component绑定
2016/10/10 Javascript
JavaScript实现垂直向上无缝滚动特效代码
2016/11/23 Javascript
bootstrap 表单验证使用方法
2017/01/11 Javascript
NodeJS自定义模块写法(详解)
2017/06/27 NodeJs
使用JavaScript实现alert的实例代码
2017/07/06 Javascript
vue 插件的方法代码详解
2019/06/06 Javascript
vue.js实现数据库的JSON数据输出渲染到html页面功能示例
2019/08/03 Javascript
解决layer.msg 不居中 ifram中的问题
2019/09/05 Javascript
Python的dict字典结构操作方法学习笔记
2016/05/07 Python
Windows中使用wxPython和py2exe开发Python的GUI程序的实例教程
2016/07/11 Python
Python使用django搭建web开发环境
2017/06/09 Python
python中退出多层循环的方法
2018/11/27 Python
基于Python批量生成指定尺寸缩略图代码实例
2019/11/20 Python
Pytorch之卷积层的使用详解
2019/12/31 Python
Python3通过chmod修改目录或文件权限的方法示例
2020/06/08 Python
使用OpenCV实现道路车辆计数的使用方法
2020/07/15 Python
20佳惊艳的HTML5应用程序示例分享
2011/05/03 HTML / CSS
酒店实习个人鉴定
2013/12/07 职场文书
政治思想表现评语
2014/05/04 职场文书
大学生英文求职信范文
2015/03/19 职场文书
2015年教师学期工作总结
2015/04/30 职场文书
公司档案管理制度
2015/08/05 职场文书
《时代广场的蟋蟀》读后感:真挚友情,温暖世界!
2020/01/08 职场文书
MySQL分区以及建索引的方法总结
2022/04/13 MySQL
德生TECSUN S-2000使用手册文字版
2022/05/10 无线电