Guest User

Untitled

a guest
Feb 20th, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.09 KB | None | 0 0
  1. % This script is the complete automation of SVM.
  2. % 2005-8 Daniel Drucker
  3. %
  4.  
  5. if ~isvarname('expr'), error('This script must be run from a valid svmprep file which defines ''expr'', the experiment constants. See the source of this script for details.'); end
  6.  
  7. %{
  8. % This script must be called by a valid svmprep file which looks something like the following:
  9.  
  10. addpath('/ajet/ddrucker/experiments/matlablib','/usr/local/spm2');
  11. expr.username = 'ddrucker' ;% VoxBo username, needed to wait for jobs
  12. expr.subjects = {'J122507C' 'D061207D'} ;% subject identifiers
  13. expr.num_classes = 16 ;% number of classes
  14. expr.num_exemplars = 5 ;% number of exemplars
  15. expr.base_path = '/ajet/ddrucker/experiments/SVMtest/TrainingCubes/' ;% base folder of SVM directory; everything will happen under here
  16. expr.roi_path = '/ajet/ddrucker/blob1_data/ROIs/' ;% where ROIs masks are to be found. this may be left undefined (it will not be used) if you only specify 'whole' or 'backhalf' as an ROI.
  17. expr.persubjectroi = false ;% should ROIs have SUBJECTID_ prepended to them?
  18. expr.subjinit = true ;% use initials instead of full subject id for ROIs?
  19. expr.cleanup = true ;% if false, we don't clean up at the end. default is true
  20. expr.local = false ;% if true, do everything locally instead of using voxbo
  21. %expr.rois={'V1' 'V2V3d' 'V2V3v' 'V4'};
  22. expr.rois={'whole' 'backhalf'};
  23.  
  24. svmfast;
  25. %}
  26.  
  27. svmlearncmd = '/ajet/ddrucker/experiments/matlablib/svm/svml/svm_learn_h2o -v 1 -x 1 ';
  28.  
  29. % Folder Conventions
  30. runlabel = datestr(now,'yymmddHHMM') ;% used to distinguish between different runs of the same script
  31. paths.traincub_suffix = '_TrainingCubes/' ;% where the cubs to train from will be found (suffix on subject)
  32. paths.hyperplane = ['work_' runlabel '/'] ;% where train/test/wei files will be saved
  33. paths.wmap = [expr.base_path 'wmaps/'] ;% where wmap cub files will be saved
  34. paths.decision = [expr.base_path 'decisions/'] ;% where decisions will be saved
  35. paths.accuracy = [expr.base_path 'accuracies/'] ;% where accuracies will be saved
  36.  
  37. % Cub File Conventions
  38. paths.cub_prefix = 'MDS_' ;% cubs to train from start with this
  39.  
  40. % Train, Test, Model, Prediction Conventions
  41. paths.train_prefix = 'train_' ;
  42. paths.model_prefix = 'predmodel_' ;
  43. paths.result_prefix = 'result_' ;
  44.  
  45. % W-Map Files
  46. paths.wmap_suffix = '_wmap' ;
  47. paths.wmap_average_file = '_wmap_average_smooth' ;
  48.  
  49. % some calculated values
  50. dimcub = size(readcub([expr.base_path expr.subjects{1} paths.traincub_suffix paths.cub_prefix '1.1.cub'])) ;% dimensions of the cub file
  51. numvoxels = prod(dimcub) ;% total number of voxels in the cub
  52. numsubjects = length(expr.subjects) ;
  53. numdecisions = expr.num_classes^2 - expr.num_classes ;
  54. ind = [ones(1,expr.num_exemplars), -ones(1,expr.num_exemplars)]' ;% indices for writing training/test files
  55. if ~isfield(expr,'persubjectroi'), expr.persubjectroi = false; end ;% are ROIs prefixed by subject id?
  56. if ~isfield(expr,'subjinit' ), expr.subjinit = true ; end
  57. if ~isfield(expr,'cleanup' ), expr.cleanup = true ; end ;% remove the intermediate files?
  58.  
  59. %% Data preparation
  60.  
  61. % load all the cubes and write them out in SVMlight format
  62. num_cubes_read = 0;
  63. num_cubes_to_read = numsubjects * expr.num_classes * expr.num_exemplars;
  64. p=progressbar();
  65. for subject = 1:numsubjects
  66. for stim = 1:expr.num_classes
  67. for exm = 1:expr.num_exemplars
  68. num_cubes_read = num_cubes_read + 1;
  69. setStatus(p, num_cubes_read/num_cubes_to_read)
  70. fprintf('Reading %d of %d ...\n',num_cubes_read,num_cubes_to_read);
  71. cubs{subject,stim,exm} = readcub([expr.base_path expr.subjects{subject} paths.traincub_suffix paths.cub_prefix num2str(stim) '.' num2str(exm) '.cub']);
  72. end
  73. end
  74. end
  75.  
  76. num_files_written = 0;
  77. num_files_to_write = numdecisions / 2 * numsubjects * length(expr.rois);
  78. p=progressbar();
  79. for roi = 1:length(expr.rois)
  80.  
  81. if ~expr.persubjectroi
  82. % mask should have nonzero values where you want to look
  83. switch expr.rois{roi}
  84. case 'whole'
  85. mask = ones(dimcub); % whole brain
  86. case 'backhalf'
  87. mask = ones(dimcub);
  88. mask(:,33:end,:) = 0; % back half of brain
  89. otherwise
  90. mask = readcub([expr.roi_path expr.rois{roi} '.cub']);
  91. end
  92. mask_indices = find(mask == 0);
  93. end
  94.  
  95. for subject = 1:numsubjects
  96. if expr.persubjectroi
  97. if expr.subjinit
  98. subjid = subjinit(expr.subjects{subject});
  99. else
  100. subjid = expr.subjects{subject};
  101. end
  102. mask = readcub([expr.roi_path subjid '_' expr.rois{roi} '.cub']);
  103. mask_indices = find(mask == 0);
  104. end
  105.  
  106. volpathdest = [expr.base_path expr.subjects{subject} paths.traincub_suffix paths.hyperplane];
  107. mkdirifneeded(volpathdest);
  108.  
  109. for stimpair = nchoosek(1:expr.num_classes,2)'
  110. out = zeros(2*expr.num_exemplars,numvoxels);
  111.  
  112. % vectorize the data cub file
  113. stimcount = 0;
  114. for stim = stimpair'
  115. for exm = 1:expr.num_exemplars
  116. stimcount = stimcount + 1;
  117. cubout = cubs{subject,stim,exm};
  118. cubout(mask_indices) = 0;
  119. out(stimcount,:) = cubout(:)';
  120. end
  121. end
  122.  
  123. % write a training file for each pairwise decision
  124. trainfile = [volpathdest expr.rois{roi} paths.train_prefix expr.subjects{subject} '_' num2str(stimpair(1)) 'v' num2str(stimpair(2)) '.dat'];
  125. svmlwrite(trainfile, out, ind);
  126. num_files_written = num_files_written + 1;
  127. setStatus(p, num_files_written/num_files_to_write)
  128. fprintf('Writing %d of %d ...\n',num_files_written,num_files_to_write);
  129. end
  130. end
  131. end
  132.  
  133.  
  134. %% Model Creation in Voxbo - create the hyperplane.
  135. p=progressbar();
  136. num_jobs_added = 0;
  137. num_jobs = num_files_to_write;
  138. seqname = ['SVM' runlabel];
  139. if ~expr.local
  140. system(['vbbatch -f ' seqname]);
  141. end
  142. for roi = 1:length(expr.rois)
  143. for subject = 1:numsubjects
  144. volpathdest = [expr.base_path expr.subjects{subject} paths.traincub_suffix paths.hyperplane];
  145. for stimpair = nchoosek(1:expr.num_classes,2)'
  146. trainfile = [volpathdest expr.rois{roi} paths.train_prefix expr.subjects{subject} '_' num2str(stimpair(1)) 'v' num2str(stimpair(2)) '.dat'];
  147. modelfile = [volpathdest expr.rois{roi} paths.model_prefix expr.subjects{subject} '_' num2str(stimpair(1)) 'v' num2str(stimpair(2)) '.dat'];
  148. resultfile = [volpathdest expr.rois{roi} paths.result_prefix expr.subjects{subject} '_' num2str(stimpair(1)) 'v' num2str(stimpair(2)) '.out'];
  149. if expr.local
  150. system([svmlearncmd ' ' trainfile ' ' modelfile ' | grep Leave | grep error | cut -f2 -d= > ' resultfile]);
  151. else
  152. system(['vbbatch -e -- -m 15 -p 2 -sn ' seqname ' -a ' seqname ' -c "' svmlearncmd ' ' trainfile ' ' modelfile ' | grep Leave | grep error | cut -f2 -d= > ' resultfile '" x > /dev/null']);
  153. end
  154. num_jobs_added = num_jobs_added + 1;
  155. setStatus(p, num_jobs_added/num_jobs)
  156. if expr.local
  157. fprintf('Running job %d of %d ...\n',num_jobs_added,num_jobs);
  158. else
  159. fprintf('Submitting job %d of %d ...\n',num_jobs_added,num_jobs);
  160. end
  161. end
  162. end
  163. end
  164. if ~expr.local
  165. [status,seqnumber] = system(['vbbatch -e -- -s ' seqname ' |cut -c23-27']);
  166. seqnumber = str2num(seqnumber); %#ok<ST2NM>
  167. fprintf('Sequence number is %d.\n', seqnumber);
  168. % waiting for Voxbo to finish model creation
  169. status = -1;
  170. while status ~= 0
  171. [status,result] = system(['vq -s ' num2str(seqnumber)]);
  172. switch status
  173. case 1
  174. fprintf('Sequence running...\n');
  175. case 5
  176. fprintf('Waiting to run...\n');
  177. case {3,4}
  178. error('Sequence killed or gone bad, exiting.');
  179. case 6
  180. fprintf('Couldn''t get sequence status, still looking...\n');
  181. end
  182. pause(20);
  183. end
  184. fprintf('Sequence complete.\n');
  185. end
  186. %% W-Map Creation
  187. % use the modelfile written by svm_learn to assess the w-value at
  188. % each voxel; output a cub file of the same size as the original
  189. % displaying these values.
  190.  
  191. mkdirifneeded(paths.wmap);
  192.  
  193. map = zeros(dimcub);
  194. num_files_written = 0;
  195. num_files_to_write = length(expr.rois)*numsubjects;
  196. p = progressbar();
  197. for roi = 1:length(expr.rois)
  198. for subject = 1:numsubjects
  199.  
  200. out=zeros(numvoxels,1);
  201.  
  202. volpathdest = [expr.base_path expr.subjects{subject} paths.traincub_suffix paths.hyperplane ];
  203.  
  204. for stimpair = nchoosek(1:expr.num_classes,2)'
  205. weitoread = [volpathdest expr.rois{roi} paths.model_prefix expr.subjects{subject} '_' num2str(stimpair(1)) 'v' num2str(stimpair(2)) '.dat.wei'];
  206. image = svmlreadwei(weitoread,false);
  207. image(end+1:numvoxels) = 0; % svmlight truncates trailing zeros; we put them back so we can reshape it correctly
  208. out = out + image;
  209. end
  210.  
  211. % create per-subject z-transformed w-map. note that we are constructing wmap
  212. % that is the AVERAGE of several z-transformed maps, and NOT z-transforming the AVERAGE map.
  213. % this means that a final w-value of N at some voxel corresponds to an AVERAGE z-score of N.
  214. wmapfile= [paths.wmap expr.rois{roi} '_' expr.subjects{subject} paths.wmap_suffix ];
  215. writecubfast(wmapfile,abs(ztransform(reshape(out,dimcub))));
  216. system(['vbsmooth -o ' wmapfile '_smoothed.cub ' wmapfile '.cub']);
  217.  
  218. % For the cross-roi w-map, read in the smoothed map and add it to the total.
  219. map = map + readcub([wmapfile '_smoothed.cub']);
  220. num_files_written = num_files_written + 1;
  221. setStatus(p, num_files_written / num_files_to_write)
  222. fprintf('roi %d of %d / subject %d of %d ...\n', roi, length(expr.rois), subject, numsubjects);
  223. end
  224.  
  225. map = ztransform(map);
  226. writecubfast([paths.wmap expr.rois{roi} paths.wmap_average_file],map);
  227. end
  228.  
  229.  
  230. %% get the leave-one-out percentages
  231.  
  232. mkdirifneeded(paths.decision);
  233.  
  234. for roi = 1:length(expr.rois)
  235. accuracy_roi = zeros(expr.num_classes);
  236. for subject = 1:numsubjects
  237. volpathdest = [expr.base_path expr.subjects{subject} paths.traincub_suffix paths.hyperplane ];
  238. accuracy_subject = zeros(expr.num_classes);
  239. for stimpair = nchoosek(1:expr.num_classes,2)'
  240. accuracy_subject(stimpair(1),stimpair(2)) = 100 - load([volpathdest expr.rois{roi} paths.result_prefix expr.subjects{subject} '_' num2str(stimpair(1)) 'v' num2str(stimpair(2)) '.out']);
  241. end
  242. csvwrite([paths.decision expr.rois{roi} '_' expr.subjects{subject} '_accuracy'], accuracy_subject);
  243. csvwrite([paths.decision expr.rois{roi} '_' expr.subjects{subject} '_accuracy_total'], mean(sim2vec(accuracy_subject')));
  244. accuracy_roi = accuracy_roi + accuracy_subject;
  245. end
  246. csvwrite([paths.decision expr.rois{roi} '_avg_accuracy'], accuracy_roi / numsubjects);
  247. csvwrite([paths.decision expr.rois{roi} '_avg_accuracy_total'], mean(sim2vec((accuracy_roi / numsubjects)')));
  248.  
  249. end
  250.  
  251.  
  252. %% Cleaning Up
  253. % This deletes all the testfile, trainfile, modelfile, and predfile but leaves the outputs.
  254.  
  255. if expr.cleanup
  256. fprintf('Cleaning up\n');
  257. for subject=1:numsubjects
  258. for exemplar=1:expr.num_exemplars
  259. system(['rm -rf ' expr.base_path expr.subjects{subject} paths.traincub_suffix paths.hyperplane]);
  260. end
  261. end
  262. else
  263. fprintf('NOT cleaning up after myself.\n');
  264. end
  265. fprintf('DONE!\n');
Add Comment
Please, Sign In to add comment