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

卷积核可视化

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) # 对第二个卷积层可视化

热度图

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卷积核可视化,热度图教程就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 使用Keras画神经网络准确性图教程

    1.在搭建网络开始时,会调用到 keras.models的Sequential()方法,返回一个model参数表示模型 2.model参数里面有个fit()方法,用于把训练集传进网络.fit()返回一个参数,该参数包含训练集和验证集的准确性acc和错误值loss,用这些数据画成图表即可. 如: history=model.fit(x_train, y_train, batch_size=32, epochs=5, validation_split=0.25) #获取数据 #########画图

  • keras绘制acc和loss曲线图实例

    我就废话不多说了,大家还是直接看代码吧! #加载keras模块 from __future__ import print_function import numpy as np np.random.seed(1337) # for reproducibility import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense,

  • keras训练曲线,混淆矩阵,CNN层输出可视化实例

    训练曲线 def show_train_history(train_history, train_metrics, validation_metrics): plt.plot(train_history.history[train_metrics]) plt.plot(train_history.history[validation_metrics]) plt.title('Train History') plt.ylabel(train_metrics) plt.xlabel('Epoch')

  • Keras官方中文文档:性能评估Metrices详解

    能评估 使用方法 性能评估模块提供了一系列用于模型性能评估的函数,这些函数在模型编译时由metrics关键字设置 性能评估函数类似与目标函数, 只不过该性能的评估结果讲不会用于训练. 可以通过字符串来使用域定义的性能评估函数 model.compile(loss='mean_squared_error', optimizer='sgd', metrics=['mae', 'acc']) 也可以自定义一个Theano/TensorFlow函数并使用之 from keras import metri

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

    卷积核可视化 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)

  • Python数据分析:手把手教你用Pandas生成可视化图表的教程

    大家都知道,Matplotlib 是众多 Python 可视化包的鼻祖,也是Python最常用的标准可视化库,其功能非常强大,同时也非常复杂,想要搞明白并非易事.但自从Python进入3.0时代以后,pandas的使用变得更加普及,它的身影经常见于市场分析.爬虫.金融分析以及科学计算中. 作为数据分析工具的集大成者,pandas作者曾说,pandas中的可视化功能比plt更加简便和功能强大.实际上,如果是对图表细节有极高要求,那么建议大家使用matplotlib通过底层图表模块进行编码.当然,我

  • R语言绘制数据可视化小提琴图画法示例

    目录 Step1. 绘图数据的准备 Step2. 绘图数据的读取 Step3. 绘图所需package的安装.调用 Step4. 绘图 小提琴图之前已经画过了,不过最近小仙又看到一种貌美的画法,决定复刻一下.文献中看到的图如下: Step1. 绘图数据的准备 首先要把你想要绘图的数据调整成R语言可以识别的格式,建议大家在excel中保存成csv格式.作图数据如下: Step2. 绘图数据的读取 data<-read.csv("your file path", header = T

  • R语言绘制数据可视化小提琴图Violin plot with dot画法

    目录 Step1.绘图数据的准备 Step2.绘图数据的读取 Step3.绘图所需package的安装.调用 Step4.绘图 小提琴图之前已经画过了,不过最近小仙又看到一种貌美的画法,决定复刻一下.文献中看到的图如下: Step1. 绘图数据的准备 首先要把你想要绘图的数据调整成R语言可以识别的格式,建议大家在excel中保存成csv格式.作图数据如下: Step2. 绘图数据的读取 data<-read.csv("your file path", header = T) #注

  • python+opencv3生成一个自定义纯色图教程

    一. 图像在计算机中存储为矩阵.矩阵上一个点表示一个像素.若矩阵由一系列0-255的整数值组成,则表现为灰度图.便于理解,以下贴出代码: import cv2 import numpy as np img = np.ones((3,3),dtype=np.uint8)#random.random()方法后面不能加数据类型 #img = np.random.random((3,3)) #生成随机数都是小数无法转化颜色,无法调用cv2.cvtColor函数 img[0,0]=100 img[0,1]

  • Python搭建Keras CNN模型破解网站验证码的实现

    在本项目中,将会用Keras来搭建一个稍微复杂的CNN模型来破解以上的验证码.验证码如下: 利用Keras可以快速方便地搭建CNN模型,本项目搭建的CNN模型如下: 将数据集分为训练集和测试集,占比为8:2,该模型训练的代码如下: # -*- coding: utf-8 -*- import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from matplotlib im

  • Python实现Keras搭建神经网络训练分类模型教程

    我就废话不多说了,大家还是直接看代码吧~ 注释讲解版: # Classifier example import numpy as np # for reproducibility np.random.seed(1337) # from keras.datasets import mnist from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Act

  • keras 回调函数Callbacks 断点ModelCheckpoint教程

    整理自keras:https://keras-cn.readthedocs.io/en/latest/other/callbacks/ 回调函数Callbacks 回调函数是一个函数的合集,会在训练的阶段中所使用.你可以使用回调函数来查看训练模型的内在状态和统计.你可以传递一个列表的回调函数(作为 callbacks 关键字参数)到 Sequential 或 Model 类型的 .fit() 方法.在训练时,相应的回调函数的方法就会被在各自的阶段被调用. Callback keras.callb

  • Python 绘制可视化折线图

    1. 用 Numpy ndarray 作为数据传入 ply import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(1000) y = np.random.standard_normal(10) print "y = %s"% y x = range(len(y)) print "x=%s"% x plt.plot(y) plt.show()

随机推荐