liblinear_test.m 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. function [predicted_label, accuracy, scores] =liblinear_test ( 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. % author: Alexander Freytag
  20. if ( nargin < 4 )
  21. settings = [];
  22. end
  23. libsvm_options = '';
  24. % outputs for training
  25. if ( ~ getFieldWithDefault ( settings, 'b_verbose', false ) )
  26. libsvm_options = sprintf('%s -q', libsvm_options);
  27. end
  28. i_numClasses = size ( svmmodel,1);
  29. i_numSamples = size( labels_test,1);
  30. b_weightBalancing = getFieldWithDefault ( settings, 'b_weightBalancing', false);
  31. if ( ~b_weightBalancing )
  32. [predicted_label,~,scores] = predict( labels_test, feat_test, svmmodel, libsvm_options );
  33. else
  34. scores = zeros( i_numSamples, i_numClasses );
  35. % classify with everyone-against-all model
  36. for k=1:i_numClasses
  37. yBin = 2*double( labels_test == svmmodel{k}.uniqueLabel )-1;
  38. [~,~,scores(:,k)] = predict( yBin, feat_test, svmmodel{k}, libsvm_options );
  39. %Q: Why the sign of predicted labels and decision values are sometimes reversed?
  40. %Please see the answer in LIBSVM faq.
  41. %To correctly obtain decision values, you need to check the array
  42. %label
  43. %in the model.
  44. scores(:,k) = scores(:,k) .* repmat( svmmodel{k}.Label(1), [i_numSamples,1] ) ;
  45. end
  46. %# predict the class with the highest score
  47. [~,predicted_label] = max(scores,[],2);
  48. end
  49. % accuracy
  50. accuracy = sum(predicted_label == labels_test) ./ numel(labels_test) ;
  51. end