在每一层可视化Keras CNN最终训练的过滤器 [英] Visualising Keras CNN final trained filters at each layer
问题描述
有人问了同样的问题:在keras cnn中可视化学习的过滤器.但是它没有答案,所以我又问了一次. 我知道Keras在每一层都有默认的滤镜,然后对其进行修改和调整.进行所有修改之后,我想看看这些过滤器(32或64或任何数字)的外观.我知道当发生新图像的预测时,这些过滤器将被一对一地应用以预测图像.但是这些经过训练的过滤器的外观如何?我浏览了多个博客和帖子,标题为"Visualise keras过滤器"左右.但是我不知道如何在我的情况下应用它们.我已经训练了一个keras CNN模型并将其保存到.hdf5文件.请帮忙!.我想查看每一层的所有过滤器.
the same question was asked by someone :visualize learned filters in keras cnn. But it has no answers, so I asked it again. I know that Keras has default filters at each layer which are then modified and adjusted. After all modification, I want to see how these filters (32 or 64 or any number) look. I know that when prediction of new image happens, these filters are applied one-by-one to predict the image. But how these TRAINED filters look? I went through several blogs and posts which titles "Visualise keras filters" or so. But I don't know how to apply them in my case. I have trained a keras CNN model and save it to .hdf5 file. Please help!. I want to see all filters at each layer.
推荐答案
这很容易做到:
import numpy as np
model = load_model('your_model.hdf5')
#Select a convolutional layer
layer = model.layers[1]
#Get weights
kernels, biases = layer.get_weights()
#Normalize kernels into [0, 1] range for proper visualization
kernels = (kernels - np.min(kernels, axis=3)) / (np.max(kernels, axis=3) - np.min(kernels, axis=3))
#Weights are usually (width, height, channels, num_filters)
#Save weight images
import cv2
for i in range(kernels.shape[3]):
filter = kernels[:, :, :, i]
cv2.imwrite('filter-{}.png'.format(i), filter)
使用此代码,您将获得一堆PNG文件,每个过滤器一个.您可以进行其他类型的可视化处理,例如使用matplotlib.
With this code you will get a bunch of PNG files, one for each filter. You can do other kinds of visualizations like using matplotlib.
这篇关于在每一层可视化Keras CNN最终训练的过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!