|
| 1 | +print('visualize convnet') |
| 2 | + |
| 3 | +from hack import hack |
| 4 | +hack() |
| 5 | + |
| 6 | +from keras.models import load_model |
| 7 | +model = load_model('cats_and_dogs_small.h5') |
| 8 | + |
| 9 | +# model.summary() |
| 10 | + |
| 11 | +img_path = '../catsdogssmall/test/cats/cat.1700.jpg' |
| 12 | + |
| 13 | +from keras.preprocessing import image |
| 14 | +import numpy as np |
| 15 | + |
| 16 | +img = image.load_img(img_path, target_size=(150, 150)) |
| 17 | + |
| 18 | +img_tensor = image.img_to_array(img) |
| 19 | +img_tensor = np.expand_dims(img_tensor, axis=0) |
| 20 | +img_tensor /= 255. |
| 21 | + |
| 22 | +print(img_tensor.shape) |
| 23 | + |
| 24 | +import matplotlib.pyplot as plt |
| 25 | + |
| 26 | +# plt.imshow(img_tensor[0]) |
| 27 | +# plt.show() |
| 28 | + |
| 29 | +from keras import models |
| 30 | + |
| 31 | +layer_outputs = [layer.output for layer in model.layers[:8]] |
| 32 | +activation_model = models.Model(inputs=model.input, outputs=layer_outputs) |
| 33 | + |
| 34 | +activations = activation_model.predict(img_tensor) |
| 35 | + |
| 36 | +# first_layer_activation = activations[1] |
| 37 | +# print(first_layer_activation.shape) |
| 38 | + |
| 39 | +# plt.matshow(first_layer_activation[0, :, :, 7], cmap='viridis') |
| 40 | +# plt.show() |
| 41 | + |
| 42 | +layer_names = [] |
| 43 | +for layer in model.layers[:8]: |
| 44 | + layer_names.append(layer.name) |
| 45 | + |
| 46 | +images_per_row = 16 |
| 47 | + |
| 48 | +for layer_name, layer_activation in zip(layer_names, activations): |
| 49 | + n_features = layer_activation.shape[-1] |
| 50 | + |
| 51 | + size = layer_activation.shape[1] |
| 52 | + |
| 53 | + n_cols = n_features // images_per_row |
| 54 | + display_grid = np.zeros((size * n_cols, images_per_row * size)) |
| 55 | + |
| 56 | + for col in range (n_cols): |
| 57 | + for row in range(images_per_row): |
| 58 | + channel_image = layer_activation[0, :, :, col * images_per_row + row] |
| 59 | + |
| 60 | + channel_image -= channel_image.mean() |
| 61 | + channel_image /= (channel_image.std() + 0.00001) # so it's not zero ever! |
| 62 | + channel_image *= 64 |
| 63 | + channel_image += 128 |
| 64 | + channel_image = np.clip(channel_image, 0, 255).astype('uint8') |
| 65 | + display_grid[col * size : (col + 1) * size, |
| 66 | + row * size : (row + 1) * size] = channel_image |
| 67 | + |
| 68 | + scale = 1./ size |
| 69 | + plt.figure(figsize=(scale * display_grid.shape[1], |
| 70 | + scale * display_grid.shape[0])) |
| 71 | + |
| 72 | + plt.title(layer_name) |
| 73 | + plt.grid(False) |
| 74 | + plt.imshow(display_grid, aspect='auto', cmap='viridis') |
| 75 | + |
| 76 | +plt.show() |
| 77 | + |
| 78 | + |
0 commit comments