function [sv,model]=readmodel(infile,nfeature) % Usage: [sv,model]=readmodel(infile,nfeature) % convert libsvm formatted data file into regular format % infile: ascii string of input file name % nfeature: feature space dimension % nclass: number of classes % if nclasses = 0 means it is a model file and the parameters % encodes both classes and the lagrange multiplier alpha_i % call lineparse.m % (C) 2001 by Yu Hen Hu % created: 10/11/2001 fid=fopen(infile,'r'); line=1; sv=[]; % support vectors line =fgetl(fid); % gets the first line readsv=0; while line~=-1, % if not end of file % parse into tokens linelen=length(line); % # of ch in line % 1. read tokens i=1; k=0; clear token; token{1}=[]; while k < linelen, k=k+1; if line(k)~=' ', token{i}=[token{i} line(k)]; elseif line(k)==' ', % if it is a space delimiter i=i+1; token{i}=[]; % prepare to read the next token end end % while k loop % for some reason, sometimes we read one extra empty token since % the last char of a line is a space. In this case, the empty token % will remove it. ltoken=length(token); if isempty(token{ltoken}), ltoken=ltoken-1; end % now do parsing use switch statements % define a data structure model if readsv==0, % read headers switch token{1} % token is an ASCII string case 'svm_type', model.svm_type = token{2}; case 'kernel_type', model.kernel_type= token{2}; case 'degree' model.degree=str2num(token{2}); case 'nr_class', model.nclass = str2num(token{2}); case 'total_sv', model.nsv = str2num(token{2}); case 'rho', model.rho = str2num(token{2}); case 'SV', readsv=1; end elseif readsv==1, % start reading support vectors tmp=str2num(token{1}); alpha=abs(tmp); label=[[tmp>0] [tmp<0]]; feature=zeros(1,nfeature); for i=2:ltoken, idx=[]; findidx=0; ftoken=[]; for k=1:length(token{i}), if token{i}(k)==':', findidx=1; else if findidx==0, idx=[idx token{i}(k)], elseif findidx==1, ftoken=[ftoken token{i}(k)]; end end end % for k feature(round(str2num(idx)))=str2num(ftoken); end % for i=2:ltoken sv=[sv; alpha feature label]; end % read the next line line =fgetl(fid); % gets the next line end st=fclose('all');