0
votes

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.

1
How is your case different from the blog posts you mention? Its just a matter of getting a convolutional layer weights (with the get_weights function) and visualize them. - Dr. Snoopy
By "visualising" I mean "plotting them as images". Can you suggest a link for that? Or can you tell me how can I use github.com/jacobgil/keras-filter-visualization in my case. I have a .hdf5 file and how should I use the viz.py given in the Readme.md file at the above link - Yusuf
Moreover what I understand by IMG in viz.py usage, it is that it uses a image and project the filters on it and displays the image. Right? But I want to see the filters, not the image after projection of filters on it - Yusuf
The way my case differs is that I want to see the filters and not the image after effects of filter on it - Yusuf

1 Answers

0
votes

This is quite easy to do:

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)

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.