liblinear_test_multicore.m 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. function [predicted_label, accuracy, scores] =liblinear_test_multicore ( labels_test, feat_test, svmmodel, settings )
  2. %
  3. % BRIEF
  4. % A simple wrapper to provide testing of 1-vs-all-classification for LIBLINEAR.
  5. % No further settings are adjustable currently.
  6. %
  7. % INPUT
  8. % labels_test -- multi-class labels (#samples x 1)
  9. % feat_test -- features for test images (#samples x # dimensions)
  10. % svmmodel -- cell ( #classes x 1 ), every model entry is obtained via
  11. % svmtrain of the corresponding 1-vs-all-problem
  12. % settings -- struct for configuring the svm classification, e.g., via
  13. % 'b_verbose' ...
  14. %
  15. % OUTPUT:
  16. %
  17. %
  18. % date: 30-04-2014 ( dd-mm-yyyy )
  19. % last modified: 22-10-2015
  20. % author: Alexander Freytag, Chirstoph Käding
  21. if ( nargin < 4 )
  22. settings = [];
  23. end
  24. libsvm_options = '';
  25. % outputs for training
  26. if ( ~ getFieldWithDefault ( settings, 'b_verbose', false ) )
  27. libsvm_options = sprintf('%s -q', libsvm_options);
  28. end
  29. % add multithreading
  30. i_numThreads = getFieldWithDefault ( settings, 'i_numThreads', 2);
  31. libsvm_options = sprintf('%s -n %d', libsvm_options, i_numThreads);
  32. i_numClasses = size ( svmmodel,1);
  33. i_numSamples = size( labels_test,1);
  34. b_weightBalancing = getFieldWithDefault ( settings, 'b_weightBalancing', false);
  35. if ( ~b_weightBalancing )
  36. [predicted_label,~,scores] = predict( labels_test, feat_test, svmmodel, libsvm_options );
  37. else
  38. scores = zeros( i_numSamples, i_numClasses );
  39. % classify with everyone-against-all model
  40. for k=1:i_numClasses
  41. yBin = 2*double( labels_test == svmmodel{k}.uniqueLabel )-1;
  42. [~,~,scores(:,k)] = predict( yBin, feat_test, svmmodel{k}, libsvm_options );
  43. %Q: Why the sign of predicted labels and decision values are sometimes reversed?
  44. %Please see the answer in LIBSVM faq.
  45. %To correctly obtain decision values, you need to check the array
  46. %label
  47. %in the model.
  48. scores(:,k) = scores(:,k) .* repmat( svmmodel{k}.Label(1), [i_numSamples,1] ) ;
  49. end
  50. %# predict the class with the highest score
  51. [~,predicted_label] = max(scores,[],2);
  52. end
  53. % accuracy
  54. accuracy = sum(predicted_label == labels_test) ./ numel(labels_test) ;
  55. end