Search code examples
matlabdeep-learningclassificationfigure

Display all predictions and their percentages in the title of a figure


Im working on a project in deep learning. I have two variables for storing predictions and their percentages. This is done using a for loop for every image in a cell array C. Both predictions and percentages are stored in separate column vectors which Ill need for later use

for i=1:size(C)

img=im2uint8(C{i});
img2=imresize(img,[224 224]);
[prediction,pred_val] = classify(n_net,img2)
predictions(i,:)=prediction;
pred_vals(i,:)=pred_val;
figure
imshow(img2)

title(sprintf("%s %s",[labels,num2str(100*pravdepodobnost_predikciesnimky(i,:))]));
end

Now, I want to display all of the predictions and percentages, so lets say the network predicts that image consists of 80%ocean and 20% people, so the title in the figure displays both predictions not just the dominant one. Which is the best way to do this?

Edit: here is a sample for clarification (the titles and labels are in my native language):

labels=string(categories(scenes_training.Labels)') %creates 1x2 string array
labels = 
"Pobrežie"    "Ulica"

After one iteration from the for loop above I get this:

prediction = categorical
 Ulica

pred_vals = 1×2 single row vector    
0.0046    0.9954

And (after modification) a figure

So my goal is to write the title like this:

Pobrežie 0.45644 %; Ulica 99.5436 %


Solution

  • Given the variables described above then you can use sprintf to do what you want.

    % Use the dummy data from above
    labels = ["Pobrežie", "Ulica"];
    pred_vals = [0.0046, 0.9954];
    % now format a string to use as a title
    img_title=sprintf("%s %s%%; ", [labels', num2str(100*pred_vals')]');
    %img_title now equals "Pobrežie  0.46%; Ulica 99.54%; "
    

    Basically sprintf will cycle through all values it is supplied with, repeating the string format until it is done. You can use this to list the contents of a matrix of data. Putting the data in a matrix and transposing it is just a way of interleaving the names and the values.

    The nested transposing in the sprintf input arguments is just to persuade matlab to deal correctly with the different value types - it is a little hacky but then MATLAB often is. If I can find a nicer way then I'll update the answer.

    If you don't want the final "; " at the end of the string, then you can trim that off with a subsiquent step.