Posted By


benjamin on 10/29/09

Tagged


Statistics


Viewed 766 times
Favorited by 0 user(s)

svmlight-wrapper.m


/ Published in: MatLab
Save to your folder(s)

please leave comments on my blog. you need awk installed (obviously). Files are stored in the "/tmp/" directory, if you are on windows you might want to change that to the current directory (".").


Copy this code and paste it in your HTML
  1. function Y=svmlight(training,test,params)
  2. % (very) simple wrapper for svmlight
  3. % write matrices in sparse format to data file that can be used by svmlight.
  4. % Columns are variables, rows are observations.
  5. % It is assumed that the first column of the matrix is the target. Targets are elements of {-1,1}.
  6. %
  7. % These steps are made:
  8. % 1. output matlab matrix to text file
  9. % 2. format text file for svm (awk)
  10. % 3. create classification model (svm_learn)
  11. % 4. apply classification model (svm_classify)
  12. %
  13. % All files are written in the /tmp/ directory, if you are on windows you might want to change that to the current directory ("."). Obviously you need awk installed for this function to work. Assumes svm-light perf is installed in the svmlight subdirectory (change path if necessary).
  14. %
  15. % Example:
  16. % Y=svmlight(data(traininds,:),data(testinds,:),'-c 1 -w 3 -l 10 ');
  17. % (if you set parameters for svmlight don't forget to include the learning options!)
  18. %
  19. % (c) Benjamin Auffarth, 2008
  20. % licensed under CC-by-sa (creative commons attribution share-alike)
  21. if nargin<3
  22. params='-c 1 -# 1 -w 3 -l 10 ';
  23. end
  24. trainfile=sparse_write(training);
  25. [s,w]=system(['./svmlight/svm_perf_learn ' params trainfile '.svm2 ' trainfile '.model']);
  26. if s
  27. disp('error in executing smv-light!');w,
  28. error('svm_perf_learn not found or returned error');
  29. end
  30. testfile=sparse_write(test);
  31. [s,w]=system(['./svmlight/svm_perf_classify -v 0 ' testfile '.svm2 ' trainfile '.model ' testfile '.dat']);
  32. if s
  33. disp('error in executing smv-light!');w,
  34. error('svm_perf_classify not found or returned error');
  35. end
  36. Y=dlmread([testfile '.dat']);
  37. end
  38.  
  39. function fname=sparse_write(M)
  40. [a,fname]=system('date +/tmp/_svm_%F_-%H:%M_%S%N');
  41. fname=fname(1:end-1); % get rid of newline character
  42. dlmwrite([fname '.svm1'],M,'delimiter',' ');
  43. system(['awk -F" " ''{printf $1" "; for (i=2;i<=NF;i++) {printf i-1":"$i " "}; print ""}'' ' fname '.svm1 > ' fname '.svm2']);
  44. end

URL: http://www.myoutsourcedbrain.com/2008/11/matlab-svmlight-interface.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.