extract the gradient of a trained network with respect to the input in matlab

To extract the gradient of a trained network with respect to the input in MATLAB, you can use the dlgradient function. Here's an example:

main.m
% Load the trained network
net = alexnet;

% Load an image
im = imread('peppers.png');

% Resize and preprocess the image
im = imresize(im, net.Layers(1).InputSize(1:2));
im = im2single(im);
im = im - net.Layers(1).Mean;

% Convert the image to a dlarray
X = dlarray(im, 'SSCB');

% Forward pass through the network to get the output
Y = predict(net, X);

% Calculate the gradient of the output with respect to the input
[dLdX, dLdW] = dlgradient(Y, X);

% Convert the gradient back to an array
grad = extractdata(dLdX);

% Display the gradient
imshow(mat2gray(grad(:,:,1)));
576 chars
26 lines

In this example, we load the pretrained AlexNet network and an example image, preprocess the image, and then perform a forward pass through the network to get the output. We then use the dlgradient function to calculate the gradient of the output with respect to the input, which is the image. We convert the gradient back to an array using the extractdata function, and then display it using the imshow function.

Note that the dlgradient function requires the deep learning toolbox in MATLAB.

gistlibby LogSnag