Load VGG16 model (instead of my own trained model)
Visualize filters & feature maps
https://brainlicht.de/projects/CNN_Visualize_Filters_featureMaps/subpage.html
In [79]:
import os
import pathlib
import numpy as np
import pylab as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import model_from_json
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import Model
#Write twice, because sometimes it does not work the first time, especially if you are switching back to notebook
%matplotlib notebook
%matplotlib notebook
In [106]:
from tensorflow.keras.applications.vgg16 import VGG16
# load the model
loaded_model_vgg16 = VGG16()
loaded_model_vgg16.summary()
In [12]:
current_working_dir = os.getcwd()
files = os.listdir(os.path.join(current_working_dir, 'CatsAndDogs','model','best_model_v2'))
for f in files:
if f.endswith('h5'):
modelfname = f
if f.endswith('json'):
modelstruct = f
print(modelfname)
print(modelstruct)
In [13]:
# load json and create model
json_file = open(pathlib.Path(os.path.join(current_working_dir, 'CatsAndDogs','model','best_model_v2',modelstruct)), 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights(pathlib.Path(os.path.join(
current_working_dir, 'CatsAndDogs', 'model', 'best_model_v2', modelfname)
)
)
print("Loaded model from disk")
print(loaded_model.summary())
# evaluate loaded model on test data
#loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
In [45]:
new_img_size = loaded_model.input_shape[1:3]
new_img_size
Out[45]:
In [43]:
class_names = ['Cat', 'Dog']
In [47]:
img_name = r"Coronavirus-and-Cats-Science-Roundup-Catipilla.jpg"
img_file_path = os.path.join(current_working_dir, 'CatsAndDogs','online_test_images',img_name)
#img_file_path = r"/CatsAndDogs/online_test_images/Coronavirus-and-Cats-Science-Roundup-Catipilla.jpg"
img = keras.preprocessing.image.load_img( img_file_path, target_size=new_img_size)
img_array = keras.preprocessing.image.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) # Create batch axis
predicted_class = loaded_model.predict_classes(img_array)[0]
predictions = loaded_model.predict(img_array)
score = predictions[0]
print("Prediction: ",class_names[predicted_class[0]])
print("Score: ", np.round(score,2))
plt.figure()
plt.imshow(img)
plt.title(class_names[i])
plt.axis("off")
Out[47]:
In [88]:
print("Total layers: ", len(loaded_model.layers))
print("Convolutional layers: Name, shape")
for i,layer in enumerate(loaded_model.layers):
# check for convolutional layer
if 'conv' not in layer.name:
continue
# get filter weights
filters, biases = layer.get_weights()
print("Index: ", i, "| Name of the layer: ", layer.name, "| Shape: ", filters.shape)
In [82]:
# retrieve weights from the second hidden layer
filters, biases = loaded_model.layers[3].get_weights()
# normalize filter values to 0-1 so we can visualize them
f_min, f_max = filters.min(), filters.max()
filters = (filters - f_min) / (f_max - f_min)
# plot first few filters
n_filters, ix = 16, 1
plt.figure()
for i in range(n_filters):
# get the filter
f = filters[:, :, :, i]
# plot each channel separately
for j in range(3):
# specify subplot and turn of axis
ax = plt.subplot(n_filters, 3, ix)
ax.set_xticks([])
ax.set_yticks([])
# plot filter channel in grayscale
plt.imshow(f[:, :, j], cmap='gray')
ix += 1
# show the figure
plt.show()
In [87]:
# Example image
plt.figure()
plt.imshow(img)
plt.axis("off")
plt.title("Input image (original)")
Out[87]:
In [104]:
print("Total layers: ", len(loaded_model.layers))
print("Convolutional layers: Name, shape")
for i,layer in enumerate(loaded_model.layers):
# check for convolutional layer
if 'conv' not in layer.name:
continue
# get filter weights
filters, biases = layer.get_weights()
print("Index: ", i, "| Name of the layer: ", layer.name, "| Shape: ", filters.shape)
In [105]:
# redefine model to output right after the last hidden layer
layer_idx = 3
submodel = Model(inputs=loaded_model.inputs, outputs=loaded_model.layers[layer_idx].output)
In [86]:
# get feature map for first hidden layer
feature_maps = submodel.predict(img_array)
# plot all 64 maps in an 8x8 squares
square = 4
ix = 1
plt.figure()
for _ in range(square):
for _ in range(square):
# specify subplot and turn of axis
ax = plt.subplot(square, square, ix)
ax.set_xticks([])
ax.set_yticks([])
# plot filter channel in grayscale
plt.imshow(feature_maps[0, :, :, ix-1], cmap='gray')
ix += 1
# show the figure
plt.show()
In [89]:
print("Total layers: ", len(loaded_model.layers))
print("Convolutional layers: Name, shape")
for i,layer in enumerate(loaded_model.layers):
# check for convolutional layer
if 'conv' not in layer.name:
continue
# get filter weights
filters, biases = layer.get_weights()
print("Index: ", i, "| Name of the layer: ", layer.name, "| Shape: ", filters.shape)
In [93]:
# redefine model to output right after the last hidden layer
layer_idx = 15
submodel = Model(inputs=loaded_model.inputs, outputs=loaded_model.layers[layer_idx].output)
In [95]:
# get feature map for first hidden layer
feature_maps = submodel.predict(img_array)
# plot all 64 maps in an 8x8 squares
square = 8
ix = 1
plt.figure(figsize=(10,10))
for _ in range(square):
for _ in range(square):
# specify subplot and turn of axis
ax = plt.subplot(square, square, ix)
ax.set_xticks([])
ax.set_yticks([])
# plot filter channel in grayscale
plt.imshow(feature_maps[0, :, :, ix-1], cmap='gray')
ix += 1
# show the figure
plt.show()
In [98]:
print("Total layers: ", len(loaded_model.layers))
print("Convolutional layers: Name, shape")
for i,layer in enumerate(loaded_model.layers):
# check for convolutional layer
if 'conv' not in layer.name:
continue
# get filter weights
filters, biases = layer.get_weights()
print("Index: ", i, "| Name of the layer: ", layer.name, "| Shape: ", filters.shape)
In [100]:
# redefine model to output right after the last hidden layer
layer_idx = 19
submodel = Model(inputs=loaded_model.inputs, outputs=loaded_model.layers[layer_idx].output)
In [102]:
# get feature map for first hidden layer
feature_maps = submodel.predict(img_array)
# plot all 64 maps in an 8x8 squares
square = 16
ix = 1
plt.figure(figsize=(10,10))
for _ in range(square):
for _ in range(square):
# specify subplot and turn of axis
ax = plt.subplot(square, square, ix)
ax.set_xticks([])
ax.set_yticks([])
# plot filter channel in grayscale
plt.imshow(feature_maps[0, :, :, ix-1], cmap='gray')
ix += 1
# show the figure
plt.show()
In [103]:
print(feature_maps.shape)
In [ ]:
In [ ]:
No hay comentarios:
Publicar un comentario