tensorfolw与kears卷积特征图可视化

Tensorflow

MINIST数据集

            fig2, ax2 = plt.subplots(figsize=(2, 2))
            ax2.imshow(np.reshape(mnist.train.images[11], (28, 28)))
            plt.show()

            # # 第一层的卷积输出的特征图
            input_image = mnist.train.images[11:12]
            conv1_16 = sess.run(h_con1, feed_dict={x: input_image})  # [1, 28, 28 ,16]
            conv1_transpose = sess.run(tf.transpose(conv1_16, [3, 0, 1, 2]))
            fig3, ax3 = plt.subplots(nrows=1, ncols=16, figsize=(16, 1))
            for i in range(16):
                ax3[i].imshow(conv1_transpose[i][0])  # tensor的切片[row, column]

            plt.title('Conv1 16x28x28')
            plt.show()

            # 第一层池化后的特征图
            pool1_16 = sess.run(p_pool1, feed_dict={x: input_image})  # [1, 14, 14, 16]
            pool1_transpose = sess.run(tf.transpose(pool1_16, [3, 0, 1, 2]))
            fig4, ax4 = plt.subplots(nrows=1, ncols=16, figsize=(16, 1))
            for i in range(16):
                ax4[i].imshow(pool1_transpose[i][0])

            plt.title('Pool1 16x14x14')
            plt.show()

            # 第二层卷积输出特征图
            conv2_32 = sess.run(h_con2, feed_dict={x: input_image})  # [1, 14, 14, 32]
            conv2_transpose = sess.run(tf.transpose(conv2_32, [3, 0, 1, 2]))
            fig5, ax5 = plt.subplots(nrows=1, ncols=32, figsize=(32, 1))
            for i in range(32):
                ax5[i].imshow(conv2_transpose[i][0])
            plt.title('Conv2 32x14x14')
            plt.show()

            #第二层池化后的特征图
            pool2_32 = sess.run(p_pool2, feed_dict={x: input_image})  # [1, 7, 7, 32]
            pool2_transpose = sess.run(tf.transpose(pool2_32, [3, 0, 1, 2]))
            fig6, ax6 = plt.subplots(nrows=1, ncols=32, figsize=(32, 1))
            plt.title('Pool2 32x7x7')
            for i in range(32):
                ax6[i].imshow(pool2_transpose[i][0])

            plt.show()

Kears

import numpy as np
from keras.models import load_model
model = load_model('face_model.h5')
img_path = 'G:/PythonN/Graduation/face/1/19.jpg'

# We preprocess the image into a 4D tensor
from keras.preprocessing import image

img = image.load_img(img_path, target_size=(100, 100))
img_tensor = image.img_to_array(img)
img_tensor = np.expand_dims(img_tensor, axis=0)
# Remember that the model was trained on inputs
# that were preprocessed in the following way:
img_tensor /= 255.
# Its shape is (1, 150, 150, 3)
print(img_tensor.shape)
import matplotlib.pyplot as plt

plt.imshow(img_tensor[0])
plt.show()
from keras import models
layer_outputs = [layer.output for layer in model.layers[:7]]
# Creates a model that will return these outputs, given the model input:
activation_model = models.Model(inputs=model.input, outputs=layer_outputs)
activations = activation_model.predict(img_tensor)
# These are the names of the layers, so can have them as part of our plot
layer_names = []
for layer in model.layers[:7]:
    layer_names.append(layer.name)

images_per_row = 16

# Now let's display our feature maps
for layer_name, layer_activation in zip(layer_names, activations):
    # This is the number of features in the feature map
    n_features = layer_activation.shape[-1]

    # The feature map has shape (1, size, size, n_features)
    size = layer_activation.shape[1]

    # We will tile the activation channels in this matrix
    n_cols = n_features // images_per_row
    display_grid = np.zeros((size * n_cols, images_per_row * size))

    # We'll tile each filter into this big horizontal grid
    for col in range(n_cols):
        for row in range(images_per_row):
            channel_image = layer_activation[0,
                            :, :,
                            col * images_per_row + row]
            # Post-process the feature to make it visually palatable
            channel_image -= channel_image.mean()
            channel_image /= channel_image.std()
            channel_image *= 64
            channel_image += 128
            channel_image = np.clip(channel_image, 0, 255).astype('uint8')
            display_grid[col * size: (col + 1) * size,
            row * size: (row + 1) * size] = channel_image

    # Display the grid
    scale = 1. / size
    plt.figure(figsize=(scale * display_grid.shape[1],
                        scale * display_grid.shape[0]))
    plt.title(layer_name)
    plt.grid(False)
    plt.imshow(display_grid, aspect='auto', cmap='viridis')

plt.show()

Kears部分转载自https://nbviewer.jupyter.org/github/fchollet/deep-learning-with-python-notebooks/blob/master/5.4-visualizing-what-convnets-learn.ipynb

Tensorflow部分转载自https://blog.csdn.net/u014281392/article/details/74316028

 

你可能感兴趣的:(tensorfolw与kears卷积特征图可视化)