Wednesday, February 28, 2007

Wrapper for svmpredict.exe

% predictions = libsvmpredict(test_set, model, varargin)
% options:
% -b probability_estimates: whether to predict probability estimates, 0 or
% 1 (default 0); for one-class SVM only 0 is supported
% NOTE1: This function actually executes LibSVM's svmpredict tool. For more
% info check out:
% NOTE2: Although LibSVM supports more types of labels, this wrapper is
% limited to integer labels only.
% NOTE3: This function assumes that svmpredict.exe is located in a directory
% that lies in your system's PATH.
function predictions = libsvmpredict(test_set, model, varargin)
if isempty(varargin)
options = struct([]);
options = varargin{1};

% Dump the test set to a temporary file
testfile = tempname;
fid = fopen(testfile, 'wt');
dumpData = zeros(size(test_set,1), 2*size(test_set,2) + 1);
format = '%d %d:%f';
for i=1:size(test_set, 2)
dumpData(:, 2*i) = repmat(i, size(test_set,1), 1);
dumpData(:, 2*i+1) = test_set(:, i);
if i < size(test_set,2)
format = sprintf('%s %%d:%%f', format);
format = sprintf('%s\n', format);
fprintf(fid, format, dumpData');

% Dump the model to a temporary file
modelfile = tempname;
fid = fopen(modelfile, 'wt');
fprintf(fid, model');

% Run svmpredict with the given model and write the predictions to a temporary
% file
predictionsfile = tempname;
command = 'svmpredict';

if isfield(options, 'b')
command = sprintf('%s -b %d', options.b);

dos(sprintf('%s %s %s %s', command, testfile, modelfile, predictionsfile), '-echo');

% Load the predictions temporary file and return its content
predictions = dlmread(predictionsfile);


No comments: