问题
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:
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.
来源:https://stackoverflow.com/questions/54959454/visualising-keras-cnn-final-trained-filters-at-each-layer