# compute top N error with Matlab in Caffe

Top-N error rate is usually applied to measure how successfully a set of images with the same class name is classified by a pre-trained Caffe model. First, we have to figure out the meaning of Top-N error rate: Top-N error rate indicates the fraction of image number that does not appear in the top N predicted results by the pre-trained model. According to this definition, we have analysis all the predicted results for each image, when it comes to maltab, several functions are helpful: find(), sort() and length().

Note that, I first compute the image number from the image_list file, which builds on the fact that the ASCII code of '\n' is 10. Besides, I use sort( mat, 2) to guarantee the sorting process is row-majored. The returned sorted matrix is in largest-in-right format. The combination of length() and find() ensures to return the number of top-N images that successfully classified.

The function classification_demo() is a pre-implemented function in Caffe. It accepts an image and a flag indicating whether to compute on CPU or GPU, and returns a row vector indicating the probability of the image being classified to each class. Of course, it also allows to process multiple images at the same time by concatenating each image in row-majored forms.

There are something needed to be careful. Matlab stores image in RGB order, column-major. However, caffe requires BGR, row-majored data input. That is, we have to pre-process the input image with the following code: