%% Visualize Only the Most Important Features
% Use imageLIME to determine the most important features in an image and isolate them from the unimportant features.
% Import the pretrained network SqueezeNet.

net = squeezenet;

% Import the image and resize to match the input size for the network.

X = imread("sherlock.jpg");
inputSize = net.Layers(1).InputSize(1:2);
X = imresize(X,inputSize);

% Classify the image to get the class label.

label = classify(net,X)

% Compute the map of the feature importance and also obtain the map of the features and the feature importance. Set the image segmentation method to 'grid', the number of features to 64, and the number of synthetic images to 3072.

[scoreMap,featureMap,featureImportance]  = imageLIME(net,X,label,'Segmentation','grid','NumFeatures',64,'NumSamples',3072);

% Plot the result over the original image with transparency to see which areas of the image affect the classification score.

figure
imshow(X)
hold on
imagesc(scoreMap,'AlphaData',0.5)
colormap jet
colorbar

% Use the feature importance to find the indices of the most important five features.

numTopFeatures = 5;
[~,idx] = maxk(featureImportance,numTopFeatures);

% Use the map of the features to mask out the image so only the most important five features are visible. Display the masked image.

mask = ismember(featureMap,idx);
maskedImg = uint8(mask).*X;
figure
imshow(maskedImg);

% Copyright 2020 The MathWorks, Inc.