Logo elodees  elodees

Une IA bien-veillante pour un monde meilleur













Seuls les caractères alphabétiques accentués ou non ainsi que l'espace sont acceptés

Logo IA




Visualiseur CNN





Pas encore de compte ?

Inscrivez-vous pour accéder à tous les contenus




Testé sous Anaconda et Python 3.7

import keras
import tensorflow as tf
import matplotlib.pyplot as plt
 
# Importing CIFAR10 dataset.
 
(train_img, train_class), (test_img, test_class) = tf.keras.datasets.cifar10.load_data()
 
# Rescaling dataset between 0 and 1, and getting a look at the data.
 
X_train_CNN = train_img/255.0
X_test_CNN = test_img/255.0
print(train_img.shape, end="\n\n")
print(train_img[5], end="\n\n")
print(X_train_CNN[5], end="\n\n")
 
#Convert classes to one-hot form.
Y_train_CNN = keras.utils.np_utils.to_categorical(train_class, num_classes=10)
Y_test_CNN = keras.utils.np_utils.to_categorical(test_class, num_classes=10)
print(Y_train_CNN.shape, end = "\n\n")
print(train_class[5], end="\n\n")
print(Y_train_CNN[5], end="\n\n")
 
def create_cnn_classifier(input_shape):
    """
    This creates a cnn model for the CIFAR10 classfication.
    """
 
    inputs = keras.Input(shape=input_shape, name="inputs")
    conv_layer_1 = keras.layers.Conv2D(16, 3, name="conv_layer_1")(inputs)
    act_layer_1 = keras.layers.ReLU(name = "act_layer_1")(conv_layer_1)
    pool_layer_1 = keras.layers.MaxPool2D(2, 2, name="pool_layer_1")(act_layer_1)
    conv_layer_2 = keras.layers.Conv2D(32, 3, name="conv_layer_2")(pool_layer_1)
    act_layer_2 = keras.layers.ReLU(name="act_layer_2")(conv_layer_2)
    pool_layer_2 = keras.layers.MaxPool2D(2, 2, name="pool_layer_2")(act_layer_2)
    conv_layer_3 = keras.layers.Conv2D(64, 3, name="conv_layer_3")(pool_layer_2)
    act_layer_3 = keras.layers.ReLU(name="act_layer_3")(conv_layer_3)
    pool_layer_3 = keras.layers.MaxPool2D(2, 2, name="pool_layer_3")(act_layer_3)
    flatten_layer = keras.layers.Flatten(name="flatten_layer")(pool_layer_3)
    outputs = keras.layers.Dense(10, activation="softmax", name="outputs")(flatten_layer)
 
    model = keras.Model(inputs, outputs)
 
    return model
 
# A look at the CNN thus made.
 
cnn_model = create_cnn_classifier(X_train_CNN.shape[1:])
cnn_model.summary()
 
cnn_model.compile(optimizer=keras.optimizers.Adam(), loss=keras.losses.categorical_crossentropy, metrics=[keras.metrics.CategoricalAccuracy()])
cnn_model.fit(X_train_CNN, Y_train_CNN, batch_size=32, epochs=10, validation_data=(X_test_CNN, Y_test_CNN))
 
def deconv_layer_1(model_in, input_shape):
    """
    Deconvolution to check shape.
    """
    input_layer = model_in.input
    conv_out = model_in.get_layer("pool_layer_1").output
    upsample_1 = keras.layers.UpSampling2D(2, name="upsample_1")(conv_out)
    relu_1 = keras.layers.ReLU(name="relu_1")(upsample_1)
    deconv_1 = keras.layers.Conv2DTranspose(16, 3, name="deconv_1")(relu_1)
    final_conv = keras.layers.Conv2D(3, 1, activation="sigmoid", name="final_conv")(deconv_1)
 
    model = keras.Model(input_layer, final_conv)
 
    for layer in model.layers:
        if layer.name not in ["upsample_1", "relu_1", "deconv_1", "final_conv"]:
            layer.trainable=False
 
    return model
 
deconv_model_1 = deconv_layer_1(cnn_model, X_train_CNN.shape[1:])
deconv_model_1.summary()
 
deconv_model_1.compile(optimizer=keras.optimizers.Adam(), loss=keras.losses.binary_crossentropy)
deconv_model_1.fit(X_train_CNN, X_train_CNN, batch_size=32, epochs = 10, validation_data=(X_test_CNN, X_test_CNN))
 
# Example reconstruction of filters
 
fig, ax = plt.subplots(2,2, figsize=(20, 20))
ax[0,0].imshow(X_test_CNN[83])
ax[0,1].imshow(deconv_model_1.predict(X_test_CNN[83:84]).reshape(X_test_CNN.shape[1:]))
ax[1,0].imshow(X_test_CNN[7])
ax[1,1].imshow(deconv_model_1.predict(X_test_CNN[7:8]).reshape(X_test_CNN.shape[1:]))
 
 


CNNVisualizer - GitHub



Image gratuite et libre de droits fournie par pexel.com








Testé sous Anaconda et Python 3.7

import torch
import torch.nn as nn
from torchvision import models
import matplotlib.pyplot as plt
import os
import time
 
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
 
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')     
# device = torch.device('cpu')
print(torch.cuda.memory_allocated(0))    
print(device)
 
model = models.vgg16(pretrained=True)
for param in model.parameters():
    param.requires_grad = False
 
model_children = list(model.children())[0]
print(model_children)
 
conv_layers = []
layer_names = []
n_layers = 0
selected_types = {nn.Conv2d, nn.MaxPool2d, nn.ReLU}
for child in model_children:
    if type(child) in selected_types:
        n_layers += 1
        conv_layers.append(child.to(device))
        layer_names.append(str(child))
 
#print the conv layers
print("Total no. of layers: ", n_layers)
for layer in conv_layers:
    print(layer)
 
def getFeatureMaps(conv_layers, img, device=device):
    f_maps = []
    img = img.to(device)
    for layer in conv_layers:
        img = layer(img)
        f_maps.append(img.to('cpu').numpy())
        #print(torch.cuda.memory_allocated(0))
 
    return f_maps
 
img = plt.imread("img1.jpg")
print(img.shape)
plt.imshow(img)
 
def preprocess(img):
    img = torch.tensor(img, dtype = torch.float32)
    img_dims = img.shape
    img = img.view(-1,img_dims[2], img_dims[0], img_dims[1])
    return img
 
img = preprocess(img)
start_time = time.time()
output = getFeatureMaps(conv_layers, img)
print(time.time() - start_time)
print(len(output))
 
output[6].shape
print(output[6])
 
plt.imshow(output[13][0][0])
 
fig = plt.figure(figsize = (15,15))
n_rows = 5
n_cols = 5
n_layer = 10
ix = 1
for i in range(n_rows*n_cols):
    fig.add_subplot(n_rows, n_cols, ix)
    plt.imshow(output[n_layer][0][i])
    ix+=1
 
x = torch.tensor([2.,3.,4.], requires_grad= True)
 


CNN-Visualizer - GitHub



Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com








Visualisez les activations intermédiaires où cartes de fonctionnalités d'un CNN pour comprendre ce que les convnets apprennent.



Testé sous Anaconda et Python 3.7

import keras
 
from tensorflow.keras.models import load_model
 
model = load_model('cats_and_dogs_small_2.h5')
model.summary()
 
img_path = 'Pembroke_Corgi.png'
 
# We preprocess the image into a 4D tensor
from keras.preprocessing import image
import numpy as np
 
img = image.load_img(img_path, target_size=(150, 150))
img_tensor = image.img_to_array(img)
img_tensor = np.expand_dims(img_tensor, axis=0)
# 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()
 
plt.imsave('img_tensor-01.jpg', img_tensor[0], cmap='viridis')
 
from tensorflow.keras import models
 
# Extracts the outputs of the top 8 layers:
layer_outputs = [layer.output for layer in model.layers[:8]]
# Creates a model that will return these outputs, given the model input:
activation_model = models.Model(inputs=model.input, outputs=layer_outputs)
 
# This will return a list of 8 Numpy arrays, one array per layer activation
activations = activation_model.predict(img_tensor)
 
first_layer_activation = activations[0]
print(first_layer_activation.shape)
 
plt.matshow(first_layer_activation[0, :, :, 7], cmap='viridis')
plt.show()
 
plt.imsave('first_layer_activation-01.jpg', first_layer_activation[0, :, :, 7], cmap='viridis')
 
plt.matshow(first_layer_activation[0, :, :, 26], cmap='viridis')
plt.show()
 
plt.imsave('first_layer_activation-02.jpg', first_layer_activation[0, :, :, 26], cmap='viridis')
 
# These are the names of the layers, so can have them as part of our plot
layer_names = []
for layer in model.layers[:8]:
    layer_names.append(layer.name)
 
images_per_row = 16
 
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.savefig(layer_name+'.png', format='png')
 
plt.show()
 


intermediate-activations - GitHub



Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com









Visualiser les filtres et les cartes de caractéristiques dans les réseaux de neurones convolutifs (CNN).



Testé sous Anaconda et Python 3.7

from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg16 import preprocess_input
from matplotlib import pyplot
from numpy import expand_dims
from matplotlib import pyplot as plt
import sys
 
model = VGG16()
 
filters, biases = model.layers[1].get_weights()
 
f_min, f_max = filters.min(), filters.max()
filters = (filters - f_min) / (f_max - f_min)
 
filters, biases = model.layers[1].get_weights()
 
f_min, f_max = filters.min(), filters.max()
filters = (filters - f_min) / (f_max - f_min)
 
n_filters, ix = 64, 1
 
cpt = 1
 
for i in range(n_filters):
  f = filters[:, :, :, i]
 
  ix=1
  pyplot.figure(figsize=(10,5))
  for j in range(3):
    pyplot.subplot(1,3,ix)
    pyplot.title(f"{f[:, :, j]}",fontsize=10)
    pyplot.imshow(f[:, :, j], cmap='gray')
 
    ix += 1
 
  pyplot.tight_layout()
 
  plt.savefig('Results/filters-%s.jpg' % (cpt), bbox_inches='tight')
  cpt +=1
 
  pyplot.show()
 
model = VGG16()
 
model = Model(inputs=model.layers[0].input, outputs=model.layers[1].output)
img = load_img('bird.jpg', target_size=(224, 224))
img = img_to_array(img)
img = expand_dims(img, axis=0)
img = preprocess_input(img)
feature_maps = model.predict(img)
 
square = 8
ix = 1
pyplot.figure(figsize=(10,5))
for _ in range(square):
    for _ in range(square):
        ax = pyplot.subplot(square, square, ix)
        ax.set_xticks([])
        ax.set_yticks([])
        pyplot.imshow(feature_maps[0, :, :, ix-1], cmap='gray')
        ix += 1
 
plt.savefig('Results/filters-%s.jpg' % (cpt), bbox_inches='tight')
cpt +=1
 
pyplot.show()
 
img = load_img('bird.jpg', target_size=(224, 224))
img = img_to_array(img)
img = expand_dims(img, axis=0)
img = preprocess_input(img)
feature_maps = model.predict(img)
 
pyplot.figure(figsize=(15,20))
for i in range(feature_maps.shape[-1]):
  pyplot.subplot(8,8,i+1)
  pyplot.title(f"{i}")
  pyplot.imshow(feature_maps[0, :, :, i], cmap='gray')
  pyplot.axis('off')
 
pyplot.tight_layout()
 
plt.savefig('Results/filters-%s.jpg' % (cpt), bbox_inches='tight')
cpt +=1
 
pyplot.show()
 
img = load_img('bird.jpg', target_size=(224, 224))
img = img_to_array(img)
img = expand_dims(img, axis=0)
img = preprocess_input(img)
feature_maps = model.predict(img)
 
row = 16
col = 4
index_feature_map = 0
for i in range(row):
  pyplot.figure(figsize=(15,7))
  for j in range(col):
    pyplot.subplot(1,col,j+1)
    pyplot.title(f"{index_feature_map}")
    pyplot.imshow(feature_maps[0, :, :, index_feature_map], cmap='gray')
    pyplot.axis('off')
    index_feature_map += 1
  pyplot.tight_layout()
 
  plt.savefig('Results/filters-%s.jpg' % (cpt), bbox_inches='tight')
  cpt +=1
 
  pyplot.show()
 
model = VGG16()
 
ixs = [2, 5, 9, 13, 17]
outputs = [model.layers[i].output for i in ixs]
model = Model(inputs=model.inputs, outputs=outputs)
 
img = load_img('bird.jpg', target_size=(224, 224))
img = img_to_array(img)
img = expand_dims(img, axis=0)
img = preprocess_input(img)
feature_maps = model.predict(img)
 
square = 8
for fmap in feature_maps:
    # plot all 64 maps in an 8x8 squares
    ix = 1
    for _ in range(square):
        for _ in range(square):
            ax = pyplot.subplot(square, square, ix)
            ax.set_xticks([])
            ax.set_yticks([])
            pyplot.imshow(fmap[0, :, :, ix-1], cmap='gray')
            ix += 1
 
    plt.savefig('Results/filters-%s.jpg' % (cpt), bbox_inches='tight')
    cpt += 1
 
    pyplot.show()
 
for index,fmap in enumerate(feature_maps):
 
  pyplot.figure(figsize=(15,15))
  for i in range(fmap.shape[-1]):
    if i == 64:
      break
    pyplot.subplot(8,8,i+1)
    pyplot.title(f"{i}")
    pyplot.imshow(fmap[0, :, :, i], cmap='gray')
    pyplot.axis('off')
 
  pyplot.tight_layout()
 
  plt.savefig('Results/filters-%s.jpg' % (cpt), bbox_inches='tight')
  cpt +=1
 
  pyplot.show()
 
for index,fmap in enumerate(feature_maps):
 
  pyplot.figure(figsize=(3,3))
  for i in range(fmap.shape[-1]):
    if i == 25:
      pyplot.title(f"{i}")
      pyplot.imshow(fmap[0, :, :, i], cmap='gray')
      pyplot.axis('off')
 
  pyplot.tight_layout()
 
  plt.savefig('Results/filters-%s.jpg' % (cpt), bbox_inches='tight')
  cpt +=1
 
  pyplot.show()
 


visualize-filters-and-feature-maps-in-cnn - GitHub



Image gratuite et libre de droits fournie par pexel.com


Filtres



Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com



Cartes des caractéristiques qui sortent de la couche convolutive



Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com









Visualisation et compréhension des réseaux convolutionnels.



Testé sous Anaconda et Python 3.7

import matplotlib.pyplot as plt
from matplotlib import pyplot
from PIL import Image
import numpy as np
 
import torch
from torch.autograd import Variable
from torchvision import models, transforms
 
def load_image(path):
    image = Image.open(path)
    plt.imshow(image)
    plt.title("Original image")
    return image
 
scene_1 = load_image("dog.png")
 
def to_grayscale(image):
    image = torch.sum(image, dim=0)
    image = torch.div(image, image.shape[0])
    return image
 
def normalize(image):
    normalize = transforms.Normalize(
    mean=[0.485, 0.456, 0.406],
    std=[0.229, 0.224, 0.225]
    )
    preprocess = transforms.Compose([
    transforms.Resize((224,224)),
    transforms.ToTensor(),
    normalize
    ])
    image = Variable(preprocess(image).unsqueeze(0))
    return image
 
vgg = models.vgg16(pretrained=True)
 
print(vgg)
 
scene_2 = normalize(scene_1)
 
modulelist = list(vgg.features.modules())
 
# Output of various layers
 
def layer_outputs(image):
    outputs = []
    names = []
    for layer in modulelist[1:]:
        image = layer(image)
        outputs.append(image)
        names.append(str(layer))
 
    output_im = []
    for i in outputs:
        i = i.squeeze(0)
        temp = to_grayscale(i)
        output_im.append(temp.data.cpu().numpy())
 
    plt.rcParams["figure.figsize"] = (1200, 1500)
 
    pyplot.figure(figsize=(20,20))
 
    for i in range(len(output_im)):
 
        pyplot.subplot(8,4,i+1)
        pyplot.title(names[i].partition('(')[0], fontsize=30)
        pyplot.imshow(output_im[i])
        pyplot.axis('off')
 
    pyplot.tight_layout()
 
    plt.savefig('layer_outputs.jpg', bbox_inches='tight')
 
    pyplot.show()
 
layer_outputs(scene_2)
 
cpt = 1
 
# Output of each filter separately at given layer
 
def filter_outputs(image, layer_to_visualize):
    if layer_to_visualize < 0:
        layer_to_visualize += 31
    output = None
    name = None
    for count, layer in enumerate(modulelist[1:]):
        image = layer(image)
        if count == layer_to_visualize: 
            output = image
            name = str(layer)
 
    filters = []
    output = output.data.squeeze()
    for i in range(output.shape[0]):
        filters.append(output[i,:,:])
 
    plt.rcParams["figure.figsize"] = (10, 10)
 
    for i in range(int(np.sqrt(len(filters))) * int(np.sqrt(len(filters)))):
 
        pyplot.subplot(int(np.sqrt(len(filters))),int(np.sqrt(len(filters))),i+1)
        pyplot.imshow(filters[i].cpu())
        pyplot.axis('off')
 
    pyplot.tight_layout()
 
    plt.savefig('filters-%s.jpg' % (cpt), bbox_inches='tight')
 
    pyplot.show()
 
filter_outputs(scene_2, 0)
 
cpt += 1
 
filter_outputs(scene_2, -1)
 
cpt = 1
 
# Visualize weights
 
def visualize_weights(image, layer):
    weight_used = []
    for w in vgg.features.children():
        if isinstance(w, torch.nn.modules.conv.Conv2d):
            weight_used.append(w.weight.data)
 
    filters = []
    for i in range(weight_used[layer].shape[0]):
        filters.append(weight_used[layer][i,:,:,:].sum(dim=0))
        filters[i].div(weight_used[layer].shape[1])
 
    fig = plt.figure()
 
    plt.rcParams["figure.figsize"] = (10, 10)
 
    for i in range(int(np.sqrt(weight_used[layer].shape[0])) * int(np.sqrt(weight_used[layer].shape[0]))):
 
        pyplot.subplot(int(np.sqrt(weight_used[layer].shape[0])),int(np.sqrt(weight_used[layer].shape[0])),i+1)
        pyplot.imshow(filters[i].cpu())
        pyplot.axis('off')
 
    pyplot.tight_layout()
 
    plt.savefig('weights-%s.jpg' % (cpt), bbox_inches='tight')
 
    pyplot.show()
 
# First conv layer filters
visualize_weights(scene_2, 0)
 
cpt += 1
 
# Last conv layer filters
visualize_weights(scene_2, -1)
 


visualization-and-understanding-convolutional-networks - GitHub



Image gratuite et libre de droits fournie par pexel.com


Sortie de différentes couches.



Image gratuite et libre de droits fournie par pexel.com


Sortie de chaque filtre séparément à une couche donnée.



Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com


Visualiser les poids.



Image gratuite et libre de droits fournie par pexel.com

Image gratuite et libre de droits fournie par pexel.com








Testé sous Anaconda et Python 3.7

import torch.nn as nn
import torchvision.models as models
from collections import OrderedDict
import matplotlib.pyplot as plt
from math import sqrt, ceil
import numpy as np
import torch
from torch.autograd import Variable
from PIL import Image
from functools import partial
import sys
import cv2
 
class VGG16_Conv(nn.Module):
 
    def __init__(self, n_classes = 1000):   # ImageNet class categories
        super(VGG16_Conv, self).__init__()
 
        self.features = nn.Sequential(
            # conv1
            nn.Conv2d(3, 64, 3, padding = 1),
            nn.ReLU(),
            nn.Conv2d(64, 64, 3, padding = 1),
            nn.ReLU(),
            nn.MaxPool2d(2, stride = 2, return_indices = True),
            # conv2
            nn.Conv2d(64, 128, 3, padding = 1),
            nn.ReLU(),
            nn.Conv2d(128, 128, 3, padding = 1),
            nn.ReLU(),
            nn.MaxPool2d(2, stride = 2, return_indices = True),
            # conv3
            nn.Conv2d(128, 256, 3, padding = 1),
            nn.ReLU(),
            nn.Conv2d(256, 256, 3, padding = 1),
            nn.ReLU(),
            nn.Conv2d(256, 256, 3, padding = 1),
            nn.ReLU(),
            nn.MaxPool2d(2, stride = 2, return_indices = True),
            # conv4
            nn.Conv2d(256, 512, 3, padding = 1),
            nn.ReLU(),
            nn.Conv2d(512, 512, 3, padding = 1),
            nn.ReLU(),
            nn.Conv2d(512, 512, 3, padding = 1),
            nn.ReLU(),
            nn.MaxPool2d(2, stride = 2, return_indices = True),
            # conv5
            nn.Conv2d(512, 512, 3, padding = 1),
            nn.ReLU(),
            nn.Conv2d(512, 512, 3, padding = 1),
            nn.ReLU(),
            nn.Conv2d(512, 512, 3, padding = 1),
            nn.ReLU(),
            nn.MaxPool2d(2, stride = 2, return_indices = True)
        )
 
        self.classifier = nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),  # 224x244 image pooled down to 7x7 from features
            nn.ReLU(),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(),
            nn.Dropout(),
            nn.Linear(4096, n_classes)
        )
 
        self.feat_maps = OrderedDict()  # store all (conv) feature maps
 
        self.pool_locs = OrderedDict() # store all max locations for pooling layers
 
        # index of convolutional layers
        self.conv_layer_indices = [0, 2, 5, 7, 10, 12, 14, 17, 19, 21, 24, 26, 28]
 
        self.init_weights() # initialize weights
 
    # initialize weights using pre-trained vgg16 on ImageNet
    def init_weights(self):
        vgg16_pretrained = models.vgg16(pretrained = True)
        for idx, layer in enumerate(vgg16_pretrained.features): # feature component
            if isinstance(layer, nn.Conv2d):
                self.features[idx].weight.data = layer.weight.data
                self.features[idx].bias.data = layer.bias.data
 
        for idx, layer in enumerate(vgg16_pretrained.classifier):   # classifier component
            if isinstance(layer, nn.Linear):
                self.classifier[idx].weight.data = layer.weight.data
                self.classifier[idx].bias.data = layer.bias.data
 
    def forward(self, x):
        for idx, layer in enumerate(self.features): # pass self.features
            if isinstance(layer, nn.MaxPool2d):
                x, locs = layer(x)
            else:
                x = layer(x)
 
        x = x.view(x.size()[0], -1) # reshape to (1, 512 * 7 * 7)
 
        output = self.classifier(x) # pass self.classifier
 
        return output
 
    # store all feature maps and max pooling locations during forward pass
    def store_feat_maps(self):
 
        def hook(module, inp, output, key):
            if isinstance(module, nn.MaxPool2d):
                self.feat_maps[key] = output[0]
                self.pool_locs[key] = output[1]
            else:
                self.feat_maps[key] = output
 
        for idx, layer in enumerate(self._modules.get('features')):    # _modules returns an OrderedDict
            layer.register_forward_hook(partial(hook, key = idx))
 
class VGG16_Deconv(nn.Module):
 
    def __init__(self):
        super(VGG16_Deconv, self).__init__()
 
        self.features = nn.Sequential(
            # deconv1
            nn.MaxUnpool2d(2, stride = 2),
            nn.ReLU(),
            nn.Conv2d(512, 512, 3, padding = 1),
            nn.ReLU(),
            nn.Conv2d(512, 512, 3, padding = 1),
            nn.ReLU(),
            nn.Conv2d(512, 512, 3, padding = 1),
            # deconv2
            nn.MaxUnpool2d(2, stride = 2),
            nn.ReLU(),
            nn.ConvTranspose2d(512, 512, 3, padding = 1),
            nn.ReLU(),
            nn.ConvTranspose2d(512, 512, 3, padding = 1),
            nn.ReLU(),
            nn.ConvTranspose2d(512, 256, 3, padding = 1),
            # deconv3
            nn.MaxUnpool2d(2, stride = 2),
            nn.ReLU(),
            nn.ConvTranspose2d(256, 256, 3, padding = 1),
            nn.ReLU(),
            nn.ConvTranspose2d(256, 256, 3, padding = 1),
            nn.ReLU(),
            nn.ConvTranspose2d(256, 128, 3, padding = 1),
            # deconv4
            nn.MaxUnpool2d(2, stride = 2),
            nn.ReLU(),
            nn.ConvTranspose2d(128, 128, 3, padding = 1),
            nn.ReLU(),
            nn.ConvTranspose2d(128, 64, 3, padding = 1),
            # deconv5
            nn.MaxUnpool2d(2, stride = 2),
            nn.ReLU(),
            nn.ConvTranspose2d(64, 64, 3, padding = 1),
            nn.ReLU(),
            nn.ConvTranspose2d(64, 3, 3, padding = 1)
        )
 
        # forward idx : backward idx
        self.conv2deconv_indices = {0:30, 2:28, 5:25, 7:23, 10:20, 12:18, 14:16, 17:13, 19:11, 21:9, 24:6, 26:4, 28:2}
        # forward idx : backward idx; not align
        self.conv2deconv_bias_indices = {0:28, 2:25, 5:23, 7:20, 10:18, 12:16, 14:13, 17:11, 19:9, 21:6, 24:4, 26:2}
        # forwardidx : backward idx
        self.relu2relu_indices = {1:29, 3:27, 6:24, 8:22, 11:19, 13:17, 15:15, 18:12, 20:10, 22:8, 25:5, 27:3, 29:1}
        # backward idx : forward idx
        self.unpool2pool_indices = {26:4, 21:9, 14:16, 7:23, 0:30}
 
        self.init_weights()  # initialize weights
 
    # initialize weights using pre-trained vgg16 on ImageNet
    def init_weights(self):
        vgg16_pretrained = models.vgg16(pretrained = True)
        for idx, layer in enumerate(vgg16_pretrained.features): # feature component
            if isinstance(layer, nn.Conv2d):
                self.features[self.conv2deconv_indices[idx]].weight.data = layer.weight.data
                if idx in self.conv2deconv_bias_indices:    # bias in first backward layer is randomly set
                    self.features[self.conv2deconv_bias_indices[idx]].bias.data = layer.bias.data
 
    def forward(self, x, layer, activation_idx, pool_locs):
        if layer in self.conv2deconv_indices:
            start_idx = self.conv2deconv_indices[layer]
        elif layer in self.relu2relu_indices:
            start_idx = self.relu2relu_indices[layer]
        else:
            print('No such Conv2d or RelU layer!')
            sys.exit(0)
 
        for idx in range(start_idx, len(self.features)):
            if isinstance(self.features[idx], nn.MaxUnpool2d):
                x = self.features[idx](x, pool_locs[self.unpool2pool_indices[idx]])
            else:
                x = self.features[idx](x)
 
        return x
 
# transform and normalize a deconvolutional output image
def tn_deconv_img(deconv_output):
    img = deconv_output.data.numpy()[0].transpose(1, 2, 0)  # (H, W, C)
    # normalize
    img = (img - img.min()) / (img.max() - img.min()) * 255
    img = img.astype(np.uint8)
 
    return img
 
# visualize a feature map in a grid
def vis_grid(feat_map): # feat_map: (C, H, W, 1)
    (C, H, W, B) = feat_map.shape
    cnt = int(ceil(sqrt(C)))
    G = np.ones((cnt * H + cnt, cnt * W + cnt, B), feat_map.dtype)  # additional cnt for black cutting-lines
    G *= np.min(feat_map)
 
    n = 0
    for row in range(cnt):
        for col in range(cnt):
            if n < C:
                # additional cnt for black cutting-lines
                G[row * H + row : (row + 1) * H + row, col * W + col 
                  : (col + 1) * W + col, :] = feat_map[n, :, :, :]
                n += 1
 
    # normalize to [0, 1]
    G = (G - G.min()) / (G.max() - G.min())
    return G
 
# visualize a layer (a feature map represented by a grid)
def vis_layer(feat_map_grid):
    plt.figure(figsize=(20, 20))
    plt.imshow(feat_map_grid[:, :, 0], cmap="gray")   # feat_map_grid: (ceil(sqrt(C)) * H, ceil(sqrt(C)) * W, 1)
    plt.show()
 
    plt.imsave('feat-map-grid-01.jpg', feat_map_grid[:, :, 0], cmap="gray")
 
# image loading and preprocessing
def load_image(filename):
    return Image.open(filename)
 
def preprocess(img):
    img = np.asarray(img.resize((224, 224))) # resize to 224 * 224 (W * H), np.asarray returns (H, W, C)
    img = img.transpose(2, 0, 1)    # reshape to (C, H, W)
    img = img[np.newaxis, :, :, :]  # add one dim to (1, C, H, W)
 
    return Variable(torch.FloatTensor(img.astype(float)))
 
img_file = 'dog.png'
 
# load an image
img = load_image(img_file)
 
# preprocess an image, return a pytorch Variable
input_img = preprocess(img)
 
vgg16_conv = VGG16_Conv(1000)   # ImageNet class categories, build vgg16 forward network
_ = vgg16_conv.eval()   # evaluation mode
 
vgg16_conv.store_feat_maps() # store all feature maps and max pooling locations during forward pass
 
conv_output = vgg16_conv(input_img)
 
vgg16_deconv = VGG16_Deconv()   # build vgg16 backward network
_ = vgg16_deconv.eval()
 
# choose a layer to visualize
layer = 0
 
# only transpose convolve from Conv2d or ReLU layers
if (layer not in vgg16_conv.conv_layer_indices) and (layer - 1 not in vgg16_conv.conv_layer_indices):
    print('Select a Conv2D or Relu layer')
 
feat_map = vgg16_conv.feat_maps[layer].data.numpy().transpose(1, 2, 3, 0) # (1, C, H, W) -> (C, H, W, 1)
 
# visualize all feature maps in selected layer
feat_map_grid = vis_grid(feat_map)  # represent a feature map in a grid
vis_layer(feat_map_grid)    # visualize a feature map
 
# number of activations in the selected layer
n_activation = feat_map.shape[0]
print(n_activation)
 
# choose an activation to visualize
activation_idx = 10
print(activation_idx)
 
# visualize selected feature map
plt.imshow(feat_map[activation_idx, :, :, 0], cmap="gray")
plt.show()
 
plt.imsave('feat-map-01.jpg', feat_map[activation_idx, :, :, 0], cmap="gray")
 
# visualize selected activation in selected layer
new_feat_map = vgg16_conv.feat_maps[layer].clone()
 
# set all activations to zero, except for the selected one
if activation_idx == 0:
    new_feat_map[:, 1:, :, :] = 0
else:
    new_feat_map[:, :activation_idx, :, :] = 0
    if activation_idx != vgg16_conv.feat_maps[layer].shape[1] - 1:
        new_feat_map[:, activation_idx + 1:, :, :] = 0
 
deconv_output = vgg16_deconv(new_feat_map, layer, activation_idx, vgg16_conv.pool_locs)
 
# transform and normalize a deconvolutional image
img = tn_deconv_img(deconv_output)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 
# heatmap = cv2.applyColorMap(cv2.resize(img, (img.shape[1], img.shape[0])), cv2.COLORMAP_JET)
plt.imshow(cv2.resize(img, (img.shape[1], img.shape[0])), cmap="gray")
plt.show()
 
plt.imsave('deconvolutional-image-01.jpg', cv2.resize(img, (img.shape[1], img.shape[0])), cmap="gray")
 


visualization-and-understanding-convolutional-networks - GitHub



Image gratuite et libre de droits fournie par pexel.com


Carte des fonctionnalités.



Image gratuite et libre de droits fournie par pexel.com


Visualiser une image de la carte des fonctionnalités.



Image gratuite et libre de droits fournie par pexel.com


Déconvolution de l'image de la carte des fonctionnalités.

Image gratuite et libre de droits fournie par pexel.com


Image gratuite et libre de droits fournie par pexel.com












Bienvenu, je m’appelle Eric Soupet et je suis l'administrateur du site elodees.com. elodees.com est un état de l'art de l'Intelligence Artificielle et se veut collaboratif, vous pouvez dès à présent proposer du contenu tels que des articles, des événements, des tutoriels, ... alors n'hésitez pas !

Crédit des images de la plate-forme : Pixabay - Pixabay License | Pexels - Pexels License