| 1 | /********************************************************************** |
| 2 | jlsvm_lib.cc: classify raster image using Support Vector Machine |
| 3 | Author(s): [email protected] |
| 4 | Copyright (C) 2016-2020 European Union (Joint Research Centre) |
| 5 | |
| 6 | This file is part of jiplib. |
| 7 | |
| 8 | jiplib is free software: you can redistribute it and/or modify |
| 9 | it under the terms of the GNU General Public License as published by |
| 10 | the Free Software Foundation, either version 3 of the License, or |
| 11 | (at your option) any later version. |
| 12 | |
| 13 | jiplib is distributed in the hope that it will be useful, |
| 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 | GNU General Public License for more details. |
| 17 | |
| 18 | You should have received a copy of the GNU General Public License |
| 19 | along with jiplib. If not, see <https://www.gnu.org/licenses/>. |
| 20 | ***********************************************************************/ |
| 21 | #include <stdlib.h> |
| 22 | #include <vector> |
| 23 | #include <map> |
| 24 | #include <memory> |
| 25 | #include <algorithm> |
| 26 | #include "Jim.h" |
| 27 | #include "VectorOgr.h" |
| 28 | #include "base/Optionjl.h" |
| 29 | #include "base/PosValue.h" |
| 30 | #include "algorithms/ConfusionMatrix.h" |
| 31 | #include "algorithms/StatFactory.h" |
| 32 | #include "algorithms/svm.h" |
| 33 | #include "apps/AppFactory.h" |
| 34 | |
| 35 | namespace svm{ |
| 36 | enum SVM_TYPE {C_SVC=0, nu_SVC=1,one_class=2, epsilon_SVR=3, nu_SVR=4}; |
| 37 | enum KERNEL_TYPE {linear=0,polynomial=1,radial=2,sigmoid=3}; |
| 38 | } |
| 39 | |
| 40 | #define Malloc(type,n) (type *)malloc((n)*sizeof(type)) |
| 41 | |
| 42 | using namespace std; |
| 43 | using namespace app; |
| 44 | |
| 45 | // OGRErr VectorOgr::trainSVM(app::AppFactory& app){ |
| 46 | std::string VectorOgr::trainSVM(app::AppFactory& app){ |
| 47 | confusionmatrix::ConfusionMatrix cm; |
| 48 | |
| 49 | //--------------------------- command line options ------------------------------------ |
| 50 | // Optionjl<std::string> model_opt("model", "model", "Model filename to save trained classifier."); |
| 51 | // Optionjl<std::string> tlayer_opt("tln", "tln", "Sample layer name(s)"); |
| 52 | // Optionjl<std::string> attribute_opt("af", "af", "Attribute filter"); |
| 53 | Optionjl<std::string> label_opt("label", "label", "Attribute name for class label in training vector file.","label"); |
| 54 | Optionjl<unsigned int> balance_opt("bal", "balance", "Balance the input data to this number of samples for each class", 0); |
| 55 | Optionjl<bool> random_opt("random", "random", "Randomize training data for balancing", true, 2); |
| 56 | Optionjl<unsigned int> minSize_opt("min", "min", "If number of training pixels is less then min, do not take this class into account (0: consider all classes)", 0); |
| 57 | // Optionjl<unsigned int> band_opt("b", "band", "Band index (starting from 0, either use band option or use start to end)"); |
| 58 | // Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number"); |
| 59 | // Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number"); |
| 60 | Optionjl<std::string> bandNames_opt("bn", "bandname", "Band name(s) to use. Leave empty to use all bands"); |
| 61 | Optionjl<double> offset_opt("offset", "offset", "Offset value for each spectral band input features: refl[band]=(DN[band]-offset[band])/scale[band]", 0.0); |
| 62 | Optionjl<double> scale_opt("scale", "scale", "Scale value for each spectral band input features: refl=(DN[band]-offset[band])/scale[band] (use 0 if scale min and max in each band to -1.0 and 1.0)", 0.0); |
| 63 | Optionjl<unsigned short> cv_opt("cv", "cv", "N-fold cross validation mode",0); |
| 64 | Optionjl<std::string> cmformat_opt("cmf","cmf","Format for confusion matrix (ascii or latex)","ascii"); |
| 65 | Optionjl<std::string> svm_type_opt("svmt", "svmtype", "Type of SVM (C_SVC, nu_SVC,one_class, epsilon_SVR, nu_SVR)","C_SVC"); |
| 66 | Optionjl<std::string> kernel_type_opt("kt", "kerneltype", "Type of kernel function (linear,polynomial,radial,sigmoid) ","radial"); |
| 67 | Optionjl<unsigned short> kernel_degree_opt("kd", "kd", "Degree in kernel function",3); |
| 68 | Optionjl<float> gamma_opt("g", "gamma", "Gamma in kernel function",1.0); |
| 69 | Optionjl<float> coef0_opt("c0", "coef0", "Coef0 in kernel function",0); |
| 70 | Optionjl<float> ccost_opt("cc", "ccost", "The parameter C of C_SVC, epsilon_SVR, and nu_SVR",1000); |
| 71 | Optionjl<float> nu_opt("nu", "nu", "The parameter nu of nu_SVC, one_class SVM, and nu_SVR",0.5); |
| 72 | Optionjl<float> epsilon_loss_opt("eloss", "eloss", "The epsilon in loss function of epsilon_SVR",0.1); |
| 73 | Optionjl<int> cache_opt("cache", "cache", "Cache memory size in MB",100); |
| 74 | Optionjl<float> epsilon_tol_opt("etol", "etol", "The tolerance of termination criterion",0.001); |
| 75 | Optionjl<bool> shrinking_opt("shrink", "shrink", "Whether to use the shrinking heuristics",false); |
| 76 | Optionjl<bool> prob_est_opt("pe", "probest", "Whether to train a SVC or SVR model for probability estimates",true,2); |
| 77 | // Optionjl<bool> weight_opt("wi", "wi", "Set the parameter C of class i to weight*C, for C_SVC",true); |
| 78 | Optionjl<std::string> classname_opt("c", "class", "List of class names."); |
| 79 | Optionjl<short> classvalue_opt("r", "reclass", "List of class values (use same order as in class opt)."); |
| 80 | Optionjl<short> verbose_opt("v", "verbose", "Verbose level",0,2); |
| 81 | |
| 82 | // band_opt.setHide(1); |
| 83 | // bstart_opt.setHide(1); |
| 84 | // bend_opt.setHide(1); |
| 85 | minSize_opt.setHide(1); |
| 86 | svm_type_opt.setHide(1); |
| 87 | kernel_type_opt.setHide(1); |
| 88 | kernel_degree_opt.setHide(1); |
| 89 | coef0_opt.setHide(1); |
| 90 | nu_opt.setHide(1); |
| 91 | epsilon_loss_opt.setHide(1); |
| 92 | cache_opt.setHide(1); |
| 93 | epsilon_tol_opt.setHide(1); |
| 94 | shrinking_opt.setHide(1); |
| 95 | prob_est_opt.setHide(1); |
| 96 | random_opt.setHide(1); |
| 97 | verbose_opt.setHide(2); |
| 98 | |
| 99 | bool doProcess;//stop process when program was invoked with help option (-h --help) |
| 100 | try{ |
| 101 | doProcess=label_opt.retrieveOption(app); |
| 102 | // doProcess=model_opt.retrieveOption(app); |
| 103 | // tlayer_opt.retrieveOption(app); |
| 104 | // attribute_opt.retrieveOption(app); |
| 105 | balance_opt.retrieveOption(app); |
| 106 | random_opt.retrieveOption(app); |
| 107 | minSize_opt.retrieveOption(app); |
| 108 | // band_opt.retrieveOption(app); |
| 109 | // bstart_opt.retrieveOption(app); |
| 110 | // bend_opt.retrieveOption(app); |
| 111 | bandNames_opt.retrieveOption(app); |
| 112 | offset_opt.retrieveOption(app); |
| 113 | scale_opt.retrieveOption(app); |
| 114 | cv_opt.retrieveOption(app); |
| 115 | cmformat_opt.retrieveOption(app); |
| 116 | svm_type_opt.retrieveOption(app); |
| 117 | kernel_type_opt.retrieveOption(app); |
| 118 | kernel_degree_opt.retrieveOption(app); |
| 119 | gamma_opt.retrieveOption(app); |
| 120 | coef0_opt.retrieveOption(app); |
| 121 | ccost_opt.retrieveOption(app); |
| 122 | nu_opt.retrieveOption(app); |
| 123 | epsilon_loss_opt.retrieveOption(app); |
| 124 | cache_opt.retrieveOption(app); |
| 125 | epsilon_tol_opt.retrieveOption(app); |
| 126 | shrinking_opt.retrieveOption(app); |
| 127 | prob_est_opt.retrieveOption(app); |
| 128 | classname_opt.retrieveOption(app); |
| 129 | classvalue_opt.retrieveOption(app); |
| 130 | verbose_opt.retrieveOption(app); |
| 131 | // memory_opt.retrieveOption(app); |
| 132 | |
| 133 | if(!doProcess){ |
| 134 | cout << endl; |
| 135 | std::ostringstream helpStream; |
| 136 | helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl; |
| 137 | throw(helpStream.str());//help was invoked, stop processing |
| 138 | } |
| 139 | |
| 140 | std::map<std::string, svm::SVM_TYPE> svmMap; |
| 141 | |
| 142 | svmMap["C_SVC"]=svm::C_SVC; |
| 143 | svmMap["nu_SVC"]=svm::nu_SVC; |
| 144 | svmMap["one_class"]=svm::one_class; |
| 145 | svmMap["epsilon_SVR"]=svm::epsilon_SVR; |
| 146 | svmMap["nu_SVR"]=svm::nu_SVR; |
| 147 | |
| 148 | std::map<std::string, svm::KERNEL_TYPE> kernelMap; |
| 149 | |
| 150 | kernelMap["linear"]=svm::linear; |
| 151 | kernelMap["polynomial"]=svm::polynomial; |
| 152 | kernelMap["radial"]=svm::radial; |
| 153 | kernelMap["sigmoid;"]=svm::sigmoid; |
| 154 | |
| 155 | // if(model_opt.empty()){ |
| 156 | // std::string errorString="Error: filename to save model is empty"; |
| 157 | // throw(errorString); |
| 158 | // } |
| 159 | |
| 160 | unsigned int nclass=0; |
| 161 | unsigned int nband=0; |
| 162 | struct svm_model* theModel=NULL; |
| 163 | svm_parameter param; |
| 164 | svm_problem prob; |
| 165 | svm_node * x_space; |
| 166 | |
| 167 | map<string,Vector2d<float> > trainingMap; |
| 168 | vector< Vector2d<float> > trainingPixels;//[class][sample][band] |
| 169 | map<string,short> classValueMap; |
| 170 | vector<std::string> nameVector; |
| 171 | if(classname_opt.size()){ |
| 172 | assert(classname_opt.size()==classvalue_opt.size()); |
| 173 | for(unsigned int iclass=0;iclass<classname_opt.size();++iclass) |
| 174 | classValueMap[classname_opt[iclass]]=classvalue_opt[iclass]; |
| 175 | } |
| 176 | // setAttributeFilter(attribute_opt[0]); |
| 177 | sortByLabel(trainingMap,label_opt[0],bandNames_opt); |
| 178 | |
| 179 | //convert trainingMap to trainingPixels, removing small classes (< minSize_opt[0]) |
| 180 | map<string,Vector2d<float> >::iterator mapit=trainingMap.begin(); |
| 181 | while(mapit!=trainingMap.end()){ |
| 182 | //delete small classes |
| 183 | if((mapit->second).size()<minSize_opt[0]){ |
| 184 | trainingMap.erase(mapit); |
| 185 | continue; |
| 186 | } |
| 187 | trainingPixels.push_back(mapit->second); |
| 188 | if(verbose_opt[0]>1) |
| 189 | std::cout << mapit->first << ": " << (mapit->second).size() << " samples" << std::endl; |
| 190 | ++mapit; |
| 191 | } |
| 192 | nclass=trainingPixels.size(); |
| 193 | if(classname_opt.size()) |
| 194 | assert(nclass==classname_opt.size()); |
| 195 | nband=trainingPixels[0][0].size(); |
| 196 | if(verbose_opt[0]>0){ |
| 197 | std::cout << "nclass: " << nclass << std::endl; |
| 198 | std::cout << "nband: " << nband << std::endl; |
| 199 | } |
| 200 | //balance training data |
| 201 | if(balance_opt[0]>0){ |
| 202 | while(balance_opt.size()<nclass) |
| 203 | balance_opt.push_back(balance_opt.back()); |
| 204 | if(random_opt[0]) |
| 205 | srand(time(NULL)); |
| 206 | int totalSamples=0; |
| 207 | for(short iclass=0;iclass<nclass;++iclass){ |
| 208 | if(trainingPixels[iclass].size()>balance_opt[iclass]){ |
| 209 | while(trainingPixels[iclass].size()>balance_opt[iclass]){ |
| 210 | int index=rand()%trainingPixels[iclass].size(); |
| 211 | trainingPixels[iclass].erase(trainingPixels[iclass].begin()+index); |
| 212 | } |
| 213 | } |
| 214 | else{ |
| 215 | int oldsize=trainingPixels[iclass].size(); |
| 216 | for(int isample=trainingPixels[iclass].size();isample<balance_opt[iclass];++isample){ |
| 217 | int index = rand()%oldsize; |
| 218 | trainingPixels[iclass].push_back(trainingPixels[iclass][index]); |
| 219 | } |
| 220 | } |
| 221 | totalSamples+=trainingPixels[iclass].size(); |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | statfactory::StatFactory stat; |
| 226 | vector<double> offset; |
| 227 | vector<double> scale; |
| 228 | //set scale and offset |
| 229 | offset.resize(nband); |
| 230 | scale.resize(nband); |
| 231 | for(int iband=0;iband<nband;++iband){ |
| 232 | offset[iband]=(offset_opt.size()==1)?offset_opt[0]:offset_opt[iband]; |
| 233 | scale[iband]=(scale_opt.size()==1)?scale_opt[0]:scale_opt[iband]; |
| 234 | //search for min and maximum |
| 235 | if(scale[iband]<=0){ |
| 236 | float theMin=trainingPixels[0][0][iband]; |
| 237 | float theMax=trainingPixels[0][0][iband]; |
| 238 | for(short iclass=0;iclass<nclass;++iclass){ |
| 239 | for(int isample=0;isample<trainingPixels[iclass].size();++isample){ |
| 240 | if(theMin>trainingPixels[iclass][isample][iband]) |
| 241 | theMin=trainingPixels[iclass][isample][iband]; |
| 242 | if(theMax<trainingPixels[iclass][isample][iband]) |
| 243 | theMax=trainingPixels[iclass][isample][iband]; |
| 244 | } |
| 245 | } |
| 246 | offset[iband]=theMin+(theMax-theMin)/2.0; |
| 247 | scale[iband]=(theMax-theMin)/2.0; |
| 248 | } |
| 249 | } |
| 250 | // map<string,Vector2d<float> >::iterator mapit=trainingMap.begin(); |
| 251 | |
| 252 | mapit=trainingMap.begin(); |
| 253 | bool doSort=true; |
| 254 | while(mapit!=trainingMap.end()){ |
| 255 | nameVector.push_back(mapit->first); |
| 256 | if(classValueMap.size()){ |
| 257 | //check if name in training is covered by classname_opt (values can not be 0) |
| 258 | if(classValueMap[mapit->first]>0){ |
| 259 | if(cm.getClassIndex(type2string<short>(classValueMap[mapit->first]))<0){ |
| 260 | cm.pushBackClassName(type2string<short>(classValueMap[mapit->first]),doSort); |
| 261 | } |
| 262 | } |
| 263 | else{ |
| 264 | std::string errorString="Error: names in classname option are not complete, please check names in training vector and make sure classvalue is > 0"; |
| 265 | throw(errorString); |
| 266 | } |
| 267 | } |
| 268 | else |
| 269 | cm.pushBackClassName(mapit->first,doSort); |
| 270 | ++mapit; |
| 271 | } |
| 272 | if(classname_opt.empty()){ |
| 273 | //std::cerr << "Warning: no class name and value pair provided for all " << nclass << " classes, using string2type<int> instead!" << std::endl; |
| 274 | for(int iclass=0;iclass<nclass;++iclass){ |
| 275 | if(verbose_opt[0]) |
| 276 | std::cout << iclass << " " << cm.getClass(iclass) << " -> " << string2type<short>(cm.getClass(iclass)) << std::endl; |
| 277 | classValueMap[cm.getClass(iclass)]=string2type<short>(cm.getClass(iclass)); |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | //todo: fill x_space directly from mapPixels (not going through trainingPixels)? |
| 282 | //Calculate features of training set |
| 283 | vector< Vector2d<float> > trainingFeatures(nclass); |
| 284 | for(short iclass=0;iclass<nclass;++iclass){ |
| 285 | int nctraining=0; |
| 286 | if(verbose_opt[0]>=1) |
| 287 | std::cout << "calculating features for class " << iclass << std::endl; |
| 288 | if(random_opt[0]) |
| 289 | srand(time(NULL)); |
| 290 | nctraining=trainingPixels[iclass].size(); |
| 291 | if(nctraining<=0) |
| 292 | nctraining=1; |
| 293 | assert(nctraining<=trainingPixels[iclass].size()); |
| 294 | if(verbose_opt[0]>1) |
| 295 | std::cout << "nctraining (class " << iclass << "): " << nctraining << std::endl; |
| 296 | trainingFeatures[iclass].resize(nctraining); |
| 297 | for(int isample=0;isample<nctraining;++isample){ |
| 298 | //scale pixel values according to scale and offset!!! |
| 299 | for(int iband=0;iband<nband;++iband){ |
| 300 | float value=trainingPixels[iclass][isample][iband]; |
| 301 | trainingFeatures[iclass][isample].push_back((value-offset[iband])/scale[iband]); |
| 302 | } |
| 303 | } |
| 304 | assert(trainingFeatures[iclass].size()==nctraining); |
| 305 | } |
| 306 | |
| 307 | unsigned int nFeatures=trainingFeatures[0][0].size(); |
| 308 | unsigned int ntraining=0; |
| 309 | for(short iclass=0;iclass<nclass;++iclass) |
| 310 | ntraining+=trainingFeatures[iclass].size(); |
| 311 | prob.l=ntraining; |
| 312 | prob.y = Malloc(double,prob.l); |
| 313 | prob.x = Malloc(struct svm_node *,prob.l); |
| 314 | x_space = Malloc(struct svm_node,(nFeatures+1)*ntraining); |
| 315 | unsigned long int spaceIndex=0; |
| 316 | int lIndex=0; |
| 317 | for(short iclass=0;iclass<nclass;++iclass){ |
| 318 | for(int isample=0;isample<trainingFeatures[iclass].size();++isample){ |
| 319 | prob.x[lIndex]=&(x_space[spaceIndex]); |
| 320 | for(int ifeature=0;ifeature<nFeatures;++ifeature){ |
| 321 | x_space[spaceIndex].index=ifeature+1; |
| 322 | x_space[spaceIndex].value=trainingFeatures[iclass][isample][ifeature]; |
| 323 | ++spaceIndex; |
| 324 | } |
| 325 | x_space[spaceIndex++].index=-1; |
| 326 | prob.y[lIndex]=iclass; |
| 327 | ++lIndex; |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | //set SVM parameters through command line options |
| 332 | param.svm_type = svmMap[svm_type_opt[0]]; |
| 333 | param.kernel_type = kernelMap[kernel_type_opt[0]]; |
| 334 | param.degree = kernel_degree_opt[0]; |
| 335 | param.gamma = (gamma_opt[0]>0)? gamma_opt[0] : 1.0/nFeatures; |
| 336 | param.coef0 = coef0_opt[0]; |
| 337 | param.nu = nu_opt[0]; |
| 338 | param.cache_size = cache_opt[0]; |
| 339 | param.C = ccost_opt[0]; |
| 340 | param.eps = epsilon_tol_opt[0]; |
| 341 | param.p = epsilon_loss_opt[0]; |
| 342 | param.shrinking = (shrinking_opt[0])? 1 : 0; |
| 343 | param.probability = (prob_est_opt[0])? 1 : 0; |
| 344 | param.nr_weight = 0;//not used: I use priors and balancing |
| 345 | param.weight_label = NULL; |
| 346 | param.weight = NULL; |
| 347 | param.verbose=(verbose_opt[0]>1)? true:false; |
| 348 | |
| 349 | //checking parameters |
| 350 | svm_check_parameter(&prob,¶m); |
| 351 | //parameters ok, training |
| 352 | theModel=svm_train(&prob,¶m); |
| 353 | //SVM is now trained |
| 354 | if(cv_opt[0]>1){ |
| 355 | //Cross validating |
| 356 | double *target = Malloc(double,prob.l); |
| 357 | svm_cross_validation(&prob,¶m,cv_opt[0],target); |
| 358 | assert(param.svm_type != EPSILON_SVR&¶m.svm_type != NU_SVR);//only for regression |
| 359 | for(int i=0;i<prob.l;i++){ |
| 360 | string refClassName=nameVector[prob.y[i]]; |
| 361 | string className=nameVector[target[i]]; |
| 362 | if(classValueMap.size()) |
| 363 | cm.incrementResult(type2string<short>(classValueMap[refClassName]),type2string<short>(classValueMap[className]),1.0); |
| 364 | else |
| 365 | cm.incrementResult(cm.getClass(prob.y[i]),cm.getClass(target[i]),1.0); |
| 366 | } |
| 367 | free(target); |
| 368 | } |
| 369 | // *NOTE* Because svm_model contains pointers to svm_problem, you can |
| 370 | // not free the memory used by svm_problem if you are still using the |
| 371 | // svm_model produced by svm_train(). |
| 372 | if(cv_opt[0]>1){ |
| 373 | assert(cm.nReference()); |
| 374 | cm.setFormat(cmformat_opt[0]); |
| 375 | cm.reportSE95(false); |
| 376 | std::cout << cm << std::endl; |
| 377 | } |
| 378 | |
| 379 | // svm_save_model(model_opt[0],theModel,offset, scale, classValueMap, nameVector, bandNames_opt); |
| 380 | std::ostringstream outputStream; |
| 381 | svm_serialize_model(outputStream,theModel,offset, scale, classValueMap, nameVector, bandNames_opt); |
| 382 | svm_destroy_param(¶m); |
| 383 | free(prob.y); |
| 384 | free(prob.x); |
| 385 | free(x_space); |
| 386 | svm_free_and_destroy_model(&theModel); |
| 387 | // return OGRERR_NONE; |
| 388 | return outputStream.str(); |
| 389 | } |
| 390 | catch(std::string errorString){ |
| 391 | std::cerr << errorString << std::endl; |
| 392 | // return(OGRERR_FAILURE); |
| 393 | throw; |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | /** |
| 398 | * @param app application specific option arguments |
| 399 | * @return output classified raster dataset |
| 400 | **/ |
| 401 | shared_ptr<Jim> Jim::classifySVM(app::AppFactory& app){ |
| 402 | try{ |
| 403 | shared_ptr<Jim> imgWriter=createImg(); |
| 404 | classifySVM(*imgWriter, app); |
| 405 | return(imgWriter); |
| 406 | } |
| 407 | catch(string helpString){ |
| 408 | cerr << helpString << endl; |
| 409 | throw; |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | /** |
| 414 | * @param app application specific option arguments |
| 415 | * @return output classified raster dataset |
| 416 | **/ |
| 417 | // shared_ptr<Jim> Jim::svm(app::AppFactory& app){ |
| 418 | // try{ |
| 419 | // shared_ptr<Jim> imgWriter=createImg(); |
| 420 | // svm(*imgWriter, app); |
| 421 | // return(imgWriter); |
| 422 | // } |
| 423 | // catch(string helpString){ |
| 424 | // cerr << helpString << endl; |
| 425 | // return(0); |
| 426 | // } |
| 427 | // } |
| 428 | |
| 429 | |
| 430 | /** |
| 431 | * @param imgWriter output classified raster dataset |
| 432 | * @param app application specific option arguments |
| 433 | * @return CE_None if successful, CE_Failure if failed |
| 434 | **/ |
| 435 | void Jim::classifySVM(Jim& imgWriter, app::AppFactory& app){ |
| 436 | vector<double> priors; |
| 437 | |
| 438 | //--------------------------- command line options ------------------------------------ |
| 439 | Optionjl<std::string> model_opt("model", "model", "Model filename for trained classifier."); |
| 440 | Optionjl<unsigned int> band_opt("b", "band", "Band index (starting from 0). The band order must correspond to the band names defined in the model. Leave empty to use all bands"); |
| 441 | // Optionjl<std::string> bandNames_opt("bn", "bandname", "Band name(s) to use. Leave empty to use all bands"); |
| 442 | Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number"); |
| 443 | Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number"); |
| 444 | // Optionjl<double> offset_opt("offset", "offset", "Offset value for each spectral band input features: refl[band]=(DN[band]-offset[band])/scale[band]", 0.0); |
| 445 | // Optionjl<double> scale_opt("scale", "scale", "Scale value for each spectral band input features: refl=(DN[band]-offset[band])/scale[band] (use 0 if scale min and max in each band to -1.0 and 1.0)", 0.0); |
| 446 | Optionjl<double> priors_opt("prior", "prior", "Prior probabilities for each class (e.g., -p 0.3 -p 0.3 -p 0.2 ). Used for input only", 0.0); |
| 447 | Optionjl<string> priorimg_opt("pim", "priorimg", "Prior probability image (multi-band img with band for each class","",2); |
| 448 | Optionjl<string> extent_opt("e", "extent", "Only classify within extent from polygons in vector file"); |
| 449 | Optionjl<string> eoption_opt("eo","eo", "special extent options controlling rasterization: ATTRIBUTE|CHUNKYSIZE|ALL_TOUCHED|BURN_VALUE_FROM|MERGE_ALG, e.g., -eo ATTRIBUTE=fieldname"); |
| 450 | Optionjl<string> mask_opt("m", "mask", "Only classify within specified mask. For raster mask, set nodata values with the option msknodata."); |
| 451 | Optionjl<short> msknodata_opt("msknodata", "msknodata", "Mask value(s) not to consider for classification. Values will be taken over in classification image.", 0); |
| 452 | Optionjl<double> srcnodata_opt("srcnodata", "srcnodata", "Nodata value in source",0); |
| 453 | Optionjl<unsigned short> dstnodata_opt("dstnodata", "dstnodata", "Nodata value to put where image is masked as nodata", 0); |
| 454 | // Optionjl<unsigned short> nodata_opt("nodata", "nodata", "Nodata value to put where image is masked as nodata", 0); |
| 455 | Optionjl<string> colorTable_opt("ct", "ct", "Color table in ASCII format having 5 columns: id R G B ALFA (0: transparent, 255: solid)"); |
| 456 | Optionjl<string> prob_opt("prob", "prob", "Probability image."); |
| 457 | Optionjl<string> entropy_opt("entropy", "entropy", "Entropy image (measure for uncertainty of classifier output","",2); |
| 458 | // Optionjl<string> classname_opt("c", "class", "List of class names."); |
| 459 | // Optionjl<short> classvalue_opt("r", "reclass", "List of class values (use same order as in class opt)."); |
| 460 | Optionjl<short> verbose_opt("v", "verbose", "Verbose level",0,2); |
| 461 | |
| 462 | extent_opt.setHide(1); |
| 463 | eoption_opt.setHide(1); |
| 464 | band_opt.setHide(1); |
| 465 | bstart_opt.setHide(1); |
| 466 | bend_opt.setHide(1); |
| 467 | prob_opt.setHide(1); |
| 468 | priorimg_opt.setHide(1); |
| 469 | // offset_opt.setHide(1); |
| 470 | // scale_opt.setHide(1); |
| 471 | verbose_opt.setHide(2); |
| 472 | |
| 473 | bool doProcess;//stop process when program was invoked with help option (-h --help) |
| 474 | try{ |
| 475 | doProcess=model_opt.retrieveOption(app); |
| 476 | colorTable_opt.retrieveOption(app); |
| 477 | extent_opt.retrieveOption(app); |
| 478 | eoption_opt.retrieveOption(app); |
| 479 | mask_opt.retrieveOption(app); |
| 480 | msknodata_opt.retrieveOption(app); |
| 481 | srcnodata_opt.retrieveOption(app); |
| 482 | dstnodata_opt.retrieveOption(app); |
| 483 | // nodata_opt.retrieveOption(app); |
| 484 | // Advanced options |
| 485 | band_opt.retrieveOption(app); |
| 486 | // bandNames_opt.retrieveOption(app); |
| 487 | bstart_opt.retrieveOption(app); |
| 488 | bend_opt.retrieveOption(app); |
| 489 | prob_opt.retrieveOption(app); |
| 490 | priorimg_opt.retrieveOption(app); |
| 491 | // offset_opt.retrieveOption(app); |
| 492 | // scale_opt.retrieveOption(app); |
| 493 | priors_opt.retrieveOption(app); |
| 494 | entropy_opt.retrieveOption(app); |
| 495 | // classname_opt.retrieveOption(app); |
| 496 | // classvalue_opt.retrieveOption(app); |
| 497 | verbose_opt.retrieveOption(app); |
| 498 | // memory_opt.retrieveOption(app); |
| 499 | |
| 500 | if(!doProcess){ |
| 501 | cout << endl; |
| 502 | std::ostringstream helpStream; |
| 503 | helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl; |
| 504 | throw(helpStream.str());//help was invoked, stop processing |
| 505 | } |
| 506 | |
| 507 | if(entropy_opt[0]=="") |
| 508 | entropy_opt.clear(); |
| 509 | if(priorimg_opt[0]=="") |
| 510 | priorimg_opt.clear(); |
| 511 | |
| 512 | if(model_opt.empty()){ |
| 513 | string errorString="Error: no model filename provided"; |
| 514 | throw(errorString); |
| 515 | } |
| 516 | |
| 517 | VectorOgr extentReader; |
| 518 | Jim maskReader; |
| 519 | |
| 520 | double ulx=0; |
| 521 | double uly=0; |
| 522 | double lrx=0; |
| 523 | double lry=0; |
| 524 | |
| 525 | if(extent_opt.size()){ |
| 526 | if(mask_opt.size()){ |
| 527 | string errorString="Error: can only either mask or extent, not both"; |
| 528 | throw(errorString); |
| 529 | } |
| 530 | std::vector<std::string> layernames; |
| 531 | layernames.clear(); |
| 532 | extentReader.open(extent_opt[0],layernames,true); |
| 533 | // readLayer = extentReader.getDataSource()->GetLayer(0); |
| 534 | extentReader.getExtent(ulx,uly,lrx,lry); |
| 535 | maskReader.open(this->nrOfCol(),this->nrOfRow(),1,GDT_Float64); |
| 536 | double gt[6]; |
| 537 | this->getGeoTransform(gt); |
| 538 | maskReader.setGeoTransform(gt); |
| 539 | maskReader.setProjection(this->getProjection()); |
| 540 | // vector<double> burnValues(1,1);//burn value is 1 (single band) |
| 541 | // maskReader.rasterizeBuf(extentReader); |
| 542 | maskReader.d_rasterizeBuf(extentReader,dstnodata_opt[0],eoption_opt); |
| 543 | maskReader.GDALSetNoDataValue(dstnodata_opt[0]); |
| 544 | extentReader.close(); |
| 545 | } |
| 546 | |
| 547 | unsigned int totalSamples=0; |
| 548 | struct svm_model* svm; |
| 549 | struct svm_parameter param; |
| 550 | |
| 551 | std::vector<double> offset; |
| 552 | std::vector<double> scale; |
| 553 | map<string,short> classValueMap; |
| 554 | vector<std::string> nameVector; |
| 555 | vector<std::string> bandNames; |
| 556 | |
| 557 | |
| 558 | struct svm_model* theModel=svm_load_model(model_opt[0].c_str(),offset,scale,classValueMap,nameVector,bandNames); |
| 559 | |
| 560 | // std::map<std::string,short>::const_iterator mapit=classValueMap.begin(); |
| 561 | // for(int index=0;index<nameVector.size();++index) |
| 562 | // std::cout << nameVector[index] << std::endl; |
| 563 | unsigned int nclass=theModel->nr_class; |
| 564 | unsigned int nband=bandNames.size()?bandNames.size():offset.size();//todo: find a more elegant way to define number of bands (in model?) |
| 565 | |
| 566 | vector<unsigned long int> ntotalClass(nclass); |
| 567 | |
| 568 | //normalize priors from command line |
| 569 | if(priors_opt.size()>1){//priors from argument list |
| 570 | priors.resize(priors_opt.size()); |
| 571 | double normPrior=0; |
| 572 | for(unsigned short iclass=0;iclass<priors_opt.size();++iclass){ |
| 573 | priors[iclass]=priors_opt[iclass]; |
| 574 | normPrior+=priors[iclass]; |
| 575 | } |
| 576 | //normalize |
| 577 | for(unsigned short iclass=0;iclass<priors_opt.size();++iclass) |
| 578 | priors[iclass]/=normPrior; |
| 579 | } |
| 580 | else{//default: equal priors for each class |
| 581 | if(priors_opt.size()==1){ |
| 582 | priors.resize(nclass); |
| 583 | for(short iclass=0;iclass<nclass;++iclass) |
| 584 | priors[iclass]=1.0/nclass; |
| 585 | } |
| 586 | } |
| 587 | |
| 588 | //convert start and end band options to vector of band indexes |
| 589 | if(bstart_opt.size()){ |
| 590 | if(bend_opt.size()!=bstart_opt.size()){ |
| 591 | string errorstring="Error: options for start and end band indexes must be provided as pairs, missing end band"; |
| 592 | throw(errorstring); |
| 593 | } |
| 594 | band_opt.clear(); |
| 595 | for(int ipair=0;ipair<bstart_opt.size();++ipair){ |
| 596 | if(bend_opt[ipair]<=bstart_opt[ipair]){ |
| 597 | std::ostringstream errorStream; |
| 598 | errorStream << "Error: index for end band (" << bend_opt[ipair] << ") must be smaller then start band (" << bstart_opt[ipair] << ")"; |
| 599 | throw(errorStream.str()); |
| 600 | } |
| 601 | for(unsigned int iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband) |
| 602 | band_opt.push_back(iband); |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | //sort bands |
| 607 | if(band_opt.size()){ |
| 608 | if(nband!=band_opt.size()){ |
| 609 | std::ostringstream errorStream; |
| 610 | errorStream << "Error: number of bands (" << nband << ") does not correspond to number of bands specified (" << band_opt.size() << ")" << std::endl; |
| 611 | throw(errorStream.str()); |
| 612 | } |
| 613 | // std::sort(band_opt.begin(),band_opt.end()); |
| 614 | } |
| 615 | else{ |
| 616 | unsigned short iband=0; |
| 617 | while(band_opt.size()<nrOfBand()) |
| 618 | band_opt.push_back(iband++); |
| 619 | } |
| 620 | |
| 621 | // if(classname_opt.size()){ |
| 622 | // assert(classname_opt.size()==classvalue_opt.size()); |
| 623 | // for(unsigned int iclass=0;iclass<classname_opt.size();++iclass) |
| 624 | // classValueMap[classname_opt[iclass]]=classvalue_opt[iclass]; |
| 625 | // } |
| 626 | |
| 627 | const char* pszMessage; |
| 628 | void* pProgressArg=NULL; |
| 629 | GDALProgressFunc pfnProgress=GDALTermProgress; |
| 630 | float progress=0; |
| 631 | if(!verbose_opt[0]) |
| 632 | MyProgressFunc(progress,pszMessage,pProgressArg); |
| 633 | //-------------------------------- open image file ------------------------------------ |
| 634 | bool inputIsRaster=true; |
| 635 | int nrow=nrOfRow(); |
| 636 | int ncol=nrOfCol(); |
| 637 | if(this->isInit()){ |
| 638 | if(verbose_opt[0]>=1) |
| 639 | std::cout << "opening image" << std::endl; |
| 640 | // imgWriter.open(*this,false); |
| 641 | imgWriter.open(ncol,nrow,1,GDT_Byte); |
| 642 | if(verbose_opt[0]>=1) |
| 643 | std::cout << "set nodata" << std::endl; |
| 644 | imgWriter.GDALSetNoDataValue(dstnodata_opt[0]); |
| 645 | if(verbose_opt[0]>=1) |
| 646 | std::cout << "copyGeoTransform" << std::endl; |
| 647 | imgWriter.copyGeoTransform(*this); |
| 648 | if(verbose_opt[0]>=1) |
| 649 | std::cout << "setProjection" << std::endl; |
| 650 | imgWriter.setProjection(this->getProjection()); |
| 651 | if(colorTable_opt.size()) |
| 652 | imgWriter.setColorTable(colorTable_opt[0],0); |
| 653 | Jim priorReader; |
| 654 | if(priorimg_opt.size()){ |
| 655 | if(verbose_opt[0]>=1) |
| 656 | std::cout << "opening prior image " << priorimg_opt[0] << std::endl; |
| 657 | priorReader.open(priorimg_opt[0]); |
| 658 | assert(priorReader.nrOfCol()==ncol); |
| 659 | assert(priorReader.nrOfRow()==nrow); |
| 660 | } |
| 661 | |
| 662 | vector<char> classOut(ncol);//classified line for writing to image file |
| 663 | |
| 664 | Jim probImage; |
| 665 | Jim entropyImage; |
| 666 | std::string imageType="GTiff"; |
| 667 | |
| 668 | if(prob_opt.size()){ |
| 669 | probImage.open(prob_opt[0],ncol,nrow,nclass,GDT_Byte,imageType); |
| 670 | probImage.GDALSetNoDataValue(dstnodata_opt[0]); |
| 671 | probImage.copyGeoTransform(imgWriter); |
| 672 | probImage.setProjection(this->getProjection()); |
| 673 | } |
| 674 | if(entropy_opt.size()){ |
| 675 | entropyImage.open(entropy_opt[0],ncol,nrow,1,GDT_Byte,imageType); |
| 676 | entropyImage.GDALSetNoDataValue(dstnodata_opt[0]); |
| 677 | entropyImage.copyGeoTransform(imgWriter); |
| 678 | entropyImage.setProjection(this->getProjection()); |
| 679 | } |
| 680 | |
| 681 | if(mask_opt.size()){ |
| 682 | if(verbose_opt[0]>=1) |
| 683 | std::cout << "opening mask image file " << mask_opt[0] << std::endl; |
| 684 | maskReader.open(mask_opt[0]); |
| 685 | } |
| 686 | |
| 687 | for(unsigned int iline=0;iline<nrow;++iline){ |
| 688 | vector<float> buffer(ncol); |
| 689 | vector<short> lineMask; |
| 690 | Vector2d<float> linePrior; |
| 691 | if(priorimg_opt.size()) |
| 692 | linePrior.resize(nclass,ncol);//prior prob for each class |
| 693 | Vector2d<float> hpixel(ncol); |
| 694 | Vector2d<float> probOut(nclass,ncol);//posterior prob for each (internal) class |
| 695 | vector<float> entropy(ncol); |
| 696 | if(band_opt.size()){ |
| 697 | for(unsigned int iband=0;iband<band_opt.size();++iband){ |
| 698 | if(verbose_opt[0]>=2) |
| 699 | std::cout << "reading band " << band_opt[iband] << std::endl; |
| 700 | assert(band_opt[iband]>=0); |
| 701 | assert(band_opt[iband]<nrOfBand()); |
| 702 | readData(buffer,iline,band_opt[iband]); |
| 703 | for(unsigned int icol=0;icol<ncol;++icol) |
| 704 | hpixel[icol].push_back(buffer[icol]); |
| 705 | } |
| 706 | } |
| 707 | else{ |
| 708 | for(unsigned int iband=0;iband<nband;++iband){ |
| 709 | if(verbose_opt[0]>=2) |
| 710 | std::cout << "reading band " << iband << std::endl; |
| 711 | assert(iband>=0); |
| 712 | assert(iband<nrOfBand()); |
| 713 | readData(buffer,iline,iband); |
| 714 | for(unsigned int icol=0;icol<ncol;++icol) |
| 715 | hpixel[icol].push_back(buffer[icol]); |
| 716 | } |
| 717 | } |
| 718 | assert(nband==hpixel[0].size()); |
| 719 | if(verbose_opt[0]>1) |
| 720 | std::cout << "used bands: " << nband << std::endl; |
| 721 | //read prior |
| 722 | if(priorimg_opt.size()){ |
| 723 | for(unsigned int iclass=0;iclass<nclass;++iclass){ |
| 724 | if(verbose_opt.size()>1) |
| 725 | std::cout << "Reading " << priorimg_opt[0] << " band " << iclass << " line " << iline << std::endl; |
| 726 | priorReader.readData(linePrior[iclass],iline,iclass); |
| 727 | } |
| 728 | } |
| 729 | double oldRowMask=-1;//keep track of row mask to optimize number of line readings |
| 730 | //process per pixel |
| 731 | for(int icol=0;icol<ncol;++icol){ |
| 732 | assert(hpixel[icol].size()==nband); |
| 733 | bool doClassify=true; |
| 734 | bool masked=false; |
| 735 | double geox=0; |
| 736 | double geoy=0; |
| 737 | if(maskReader.isInit()){ |
| 738 | //read mask |
| 739 | double colMask=0; |
| 740 | double rowMask=0; |
| 741 | |
| 742 | imgWriter.image2geo(icol,iline,geox,geoy); |
| 743 | maskReader.geo2image(geox,geoy,colMask,rowMask); |
| 744 | colMask=static_cast<int>(colMask); |
| 745 | rowMask=static_cast<int>(rowMask); |
| 746 | if(rowMask>=0&&rowMask<maskReader.nrOfRow()&&colMask>=0&&colMask<maskReader.nrOfCol()){ |
| 747 | if(static_cast<int>(rowMask)!=static_cast<int>(oldRowMask)){ |
| 748 | assert(rowMask>=0&&rowMask<maskReader.nrOfRow()); |
| 749 | // maskReader.readData(lineMask[imask],GDT_Int32,static_cast<int>(rowMask)); |
| 750 | maskReader.readData(lineMask,static_cast<unsigned int>(rowMask)); |
| 751 | oldRowMask=rowMask; |
| 752 | } |
| 753 | short theMask=0; |
| 754 | for(short ivalue=0;ivalue<msknodata_opt.size();++ivalue){ |
| 755 | // if(msknodata_opt[ivalue]>=0){//values set in msknodata_opt are invalid |
| 756 | if(lineMask[colMask]==msknodata_opt[ivalue]){ |
| 757 | theMask=lineMask[colMask]; |
| 758 | masked=true; |
| 759 | break; |
| 760 | } |
| 761 | } |
| 762 | if(masked){ |
| 763 | classOut[icol]=theMask; |
| 764 | continue; |
| 765 | } |
| 766 | } |
| 767 | } |
| 768 | bool valid=false; |
| 769 | for(int iband=0;iband<hpixel[icol].size();++iband){ |
| 770 | if(hpixel[icol][iband]!=srcnodata_opt[0]){ |
| 771 | valid=true; |
| 772 | break; |
| 773 | } |
| 774 | } |
| 775 | if(!valid) |
| 776 | doClassify=false; |
| 777 | for(short iclass=0;iclass<nclass;++iclass) |
| 778 | probOut[iclass][icol]=0; |
| 779 | if(!doClassify){ |
| 780 | classOut[icol]=dstnodata_opt[0]; |
| 781 | continue;//next column |
| 782 | } |
| 783 | //----------------------------------- classification ------------------- |
| 784 | vector<double> result(nclass); |
| 785 | struct svm_node *x; |
| 786 | x = (struct svm_node *) malloc((nband+1)*sizeof(struct svm_node)); |
| 787 | for(int iband=0;iband<nband;++iband){ |
| 788 | x[iband].index=iband+1; |
| 789 | x[iband].value=(hpixel[icol][iband]-offset[iband])/scale[iband]; |
| 790 | } |
| 791 | |
| 792 | x[nband].index=-1;//to end svm feature vector |
| 793 | double predict_label=0; |
| 794 | vector<float> prValues(nclass); |
| 795 | float maxP=0; |
| 796 | // if(!prob_est_opt[0]){ |
| 797 | if(theModel->param.probability>0){ |
| 798 | predict_label = svm_predict(theModel,x); |
| 799 | for(short iclass=0;iclass<nclass;++iclass){ |
| 800 | if(iclass==static_cast<short>(predict_label)) |
| 801 | result[iclass]=1; |
| 802 | else |
| 803 | result[iclass]=0; |
| 804 | } |
| 805 | } |
| 806 | else{ |
| 807 | if(!svm_check_probability_model(theModel)){ |
| 808 | string errorstring="Error: svm probability model check failed"; |
| 809 | throw(errorstring); |
| 810 | } |
| 811 | predict_label = svm_predict_probability(theModel,x,&(result[0])); |
| 812 | } |
| 813 | double normPrior=0; |
| 814 | if(priorimg_opt.size()){ |
| 815 | for(short iclass=0;iclass<nclass;++iclass) |
| 816 | normPrior+=linePrior[iclass][icol]; |
| 817 | } |
| 818 | for(short iclass=0;iclass<nclass;++iclass){ |
| 819 | if(priorimg_opt.size()) |
| 820 | priors[iclass]=linePrior[iclass][icol]/normPrior;//todo: check if correct for all cases... (automatic classValueMap and manual input for names and values) |
| 821 | probOut[iclass][icol]=result[iclass]*priors[iclass]; |
| 822 | } |
| 823 | |
| 824 | //search for max class prob |
| 825 | float max1=0;//max probability |
| 826 | float max2=0;//second max probability |
| 827 | float norm=0; |
| 828 | for(short iclass=0;iclass<nclass;++iclass){ |
| 829 | if(probOut[iclass][icol]>max1){ |
| 830 | max1=probOut[iclass][icol]; |
| 831 | classOut[icol]=classValueMap[nameVector[iclass]]; |
| 832 | } |
| 833 | else if(probOut[iclass][icol]>max2) |
| 834 | max2=probOut[iclass][icol]; |
| 835 | norm+=probOut[iclass][icol]; |
| 836 | } |
| 837 | //normalize probOut and convert to percentage |
| 838 | entropy[icol]=0; |
| 839 | for(short iclass=0;iclass<nclass;++iclass){ |
| 840 | float prv=probOut[iclass][icol]; |
| 841 | prv/=norm; |
| 842 | entropy[icol]-=prv*log(prv)/log(2.0); |
| 843 | prv*=100.0; |
| 844 | |
| 845 | probOut[iclass][icol]=static_cast<short>(prv+0.5); |
| 846 | } |
| 847 | entropy[icol]/=log(static_cast<double>(nclass))/log(2.0); |
| 848 | entropy[icol]=static_cast<short>(100*entropy[icol]+0.5); |
| 849 | free(x); |
| 850 | |
| 851 | if(verbose_opt[0]) |
| 852 | ++ntotalClass[static_cast<short>(classOut[icol])]; |
| 853 | }//icol |
| 854 | //----------------------------------- write output ------------------------------------------ |
| 855 | if(prob_opt.size()){ |
| 856 | for(short iclass=0;iclass<nclass;++iclass) |
| 857 | probImage.writeData(probOut[iclass],iline,iclass); |
| 858 | } |
| 859 | if(entropy_opt.size()){ |
| 860 | entropyImage.writeData(entropy,iline); |
| 861 | } |
| 862 | |
| 863 | imgWriter.writeData(classOut,iline); |
| 864 | if(!verbose_opt[0]){ |
| 865 | progress=static_cast<float>(iline+1.0)/imgWriter.nrOfRow(); |
| 866 | MyProgressFunc(progress,pszMessage,pProgressArg); |
| 867 | } |
| 868 | } |
| 869 | // imgWriter.close(); |
| 870 | if(mask_opt.size()) |
| 871 | maskReader.close(); |
| 872 | if(priorimg_opt.size()) |
| 873 | priorReader.close(); |
| 874 | if(prob_opt.size()) |
| 875 | probImage.close(); |
| 876 | if(entropy_opt.size()) |
| 877 | entropyImage.close(); |
| 878 | } |
| 879 | // svm_destroy_param(¶m); |
| 880 | // svm_destroy_param(¶m); |
| 881 | // free(prob.y); |
| 882 | // free(prob.x); |
| 883 | // free(x_space); |
| 884 | svm_free_and_destroy_model(&theModel); |
| 885 | if(verbose_opt[0]){ |
| 886 | for(unsigned short iclass=0;iclass<nclass;++iclass) |
| 887 | std::cout << iclass << ": " << ntotalClass[iclass]; |
| 888 | std::cout << std::endl; |
| 889 | } |
| 890 | } |
| 891 | catch(string predefinedString){ |
| 892 | std::cout << predefinedString << std::endl; |
| 893 | throw; |
| 894 | } |
| 895 | } |
| 896 | |
| 897 | /** |
| 898 | * @param imgWriter output classified raster dataset |
| 899 | * @param app application specific option arguments |
| 900 | * @return CE_None if successful, CE_Failure if failed |
| 901 | **/ |
| 902 | // CPLErr Jim::svm(Jim& imgWriter, app::AppFactory& app){ |
| 903 | // vector<double> priors; |
| 904 | |
| 905 | // //--------------------------- command line options ------------------------------------ |
| 906 | // Optionjl<string> training_opt("t", "training", "Training vector file. A single vector file contains all training features (must be set as: b0, b1, b2,...) for all classes (class numbers identified by label option). Use multiple training files for bootstrap aggregation (alternative to the bag and bsize options, where a random subset is taken from a single training file)"); |
| 907 | // Optionjl<string> tlayer_opt("tln", "tln", "Training layer name(s)"); |
| 908 | // Optionjl<string> label_opt("label", "label", "Attribute name for class label in training vector file.","label"); |
| 909 | // Optionjl<unsigned int> balance_opt("bal", "balance", "Balance the input data to this number of samples for each class", 0); |
| 910 | // Optionjl<bool> random_opt("random", "random", "Randomize training data for balancing and bagging", true, 2); |
| 911 | // Optionjl<unsigned int> minSize_opt("min", "min", "If number of training pixels is less then min, do not take this class into account (0: consider all classes)", 0); |
| 912 | // Optionjl<unsigned int> band_opt("b", "band", "Band index (starting from 0, either use band option or use start to end)"); |
| 913 | // Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number"); |
| 914 | // Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number"); |
| 915 | // Optionjl<double> offset_opt("offset", "offset", "Offset value for each spectral band input features: refl[band]=(DN[band]-offset[band])/scale[band]", 0.0); |
| 916 | // Optionjl<double> scale_opt("scale", "scale", "Scale value for each spectral band input features: refl=(DN[band]-offset[band])/scale[band] (use 0 if scale min and max in each band to -1.0 and 1.0)", 0.0); |
| 917 | // Optionjl<double> priors_opt("prior", "prior", "Prior probabilities for each class (e.g., -p 0.3 -p 0.3 -p 0.2 ). Used for input only (ignored for cross validation)", 0.0); |
| 918 | // Optionjl<string> priorimg_opt("pim", "priorimg", "Prior probability image (multi-band img with band for each class","",2); |
| 919 | // Optionjl<unsigned short> cv_opt("cv", "cv", "N-fold cross validation mode",0); |
| 920 | // Optionjl<string> cmformat_opt("cmf","cmf","Format for confusion matrix (ascii or latex)","ascii"); |
| 921 | // Optionjl<std::string> svm_type_opt("svmt", "svmtype", "Type of SVM (C_SVC, nu_SVC,one_class, epsilon_SVR, nu_SVR)","C_SVC"); |
| 922 | // Optionjl<std::string> kernel_type_opt("kt", "kerneltype", "Type of kernel function (linear,polynomial,radial,sigmoid) ","radial"); |
| 923 | // Optionjl<unsigned short> kernel_degree_opt("kd", "kd", "Degree in kernel function",3); |
| 924 | // Optionjl<float> gamma_opt("g", "gamma", "Gamma in kernel function",1.0); |
| 925 | // Optionjl<float> coef0_opt("c0", "coef0", "Coef0 in kernel function",0); |
| 926 | // Optionjl<float> ccost_opt("cc", "ccost", "The parameter C of C_SVC, epsilon_SVR, and nu_SVR",1000); |
| 927 | // Optionjl<float> nu_opt("nu", "nu", "The parameter nu of nu_SVC, one_class SVM, and nu_SVR",0.5); |
| 928 | // Optionjl<float> epsilon_loss_opt("eloss", "eloss", "The epsilon in loss function of epsilon_SVR",0.1); |
| 929 | // Optionjl<int> cache_opt("cache", "cache", "Cache memory size in MB",100); |
| 930 | // Optionjl<float> epsilon_tol_opt("etol", "etol", "The tolerance of termination criterion",0.001); |
| 931 | // Optionjl<bool> shrinking_opt("shrink", "shrink", "Whether to use the shrinking heuristics",false); |
| 932 | // Optionjl<bool> prob_est_opt("pe", "probest", "Whether to train a SVC or SVR model for probability estimates",true,2); |
| 933 | // // Optionjl<bool> weight_opt("wi", "wi", "Set the parameter C of class i to weight*C, for C_SVC",true); |
| 934 | // Optionjl<unsigned short> comb_opt("comb", "comb", "How to combine bootstrap aggregation classifiers (0: sum rule, 1: product rule, 2: max rule). Also used to aggregate classes with rc option.",0); |
| 935 | // Optionjl<unsigned short> bag_opt("bag", "bag", "Number of bootstrap aggregations", 1); |
| 936 | // Optionjl<int> bagSize_opt("bagsize", "bagsize", "Percentage of features used from available training features for each bootstrap aggregation (one size for all classes, or a different size for each class respectively", 100); |
| 937 | // Optionjl<string> classBag_opt("cb", "classbag", "Output for each individual bootstrap aggregation"); |
| 938 | // Optionjl<string> extent_opt("e", "extent", "Only classify within extent from polygons in vector file"); |
| 939 | // Optionjl<string> eoption_opt("eo","eo", "special extent options controlling rasterization: ATTRIBUTE|CHUNKYSIZE|ALL_TOUCHED|BURN_VALUE_FROM|MERGE_ALG, e.g., -eo ATTRIBUTE=fieldname"); |
| 940 | // Optionjl<string> mask_opt("m", "mask", "Only classify within specified mask. For raster mask, set nodata values with the option msknodata."); |
| 941 | // Optionjl<short> msknodata_opt("msknodata", "msknodata", "Mask value(s) not to consider for classification. Values will be taken over in classification image.", 0); |
| 942 | // Optionjl<unsigned short> nodata_opt("nodata", "nodata", "Nodata value to put where image is masked as nodata", 0); |
| 943 | // Optionjl<string> colorTable_opt("ct", "ct", "Color table in ASCII format having 5 columns: id R G B ALFA (0: transparent, 255: solid)"); |
| 944 | // Optionjl<string> prob_opt("prob", "prob", "Probability image."); |
| 945 | // Optionjl<string> entropy_opt("entropy", "entropy", "Entropy image (measure for uncertainty of classifier output","",2); |
| 946 | // Optionjl<string> active_opt("active", "active", "Ogr output for active training sample.","",2); |
| 947 | // Optionjl<string> ogrformat_opt("f", "f", "Output ogr format for active training sample","SQLite"); |
| 948 | // Optionjl<unsigned int> nactive_opt("na", "nactive", "Number of active training points",1); |
| 949 | // Optionjl<string> classname_opt("c", "class", "List of class names."); |
| 950 | // Optionjl<short> classvalue_opt("r", "reclass", "List of class values (use same order as in class opt)."); |
| 951 | // Optionjl<short> verbose_opt("v", "verbose", "Verbose level",0,2); |
| 952 | |
| 953 | // extent_opt.setHide(1); |
| 954 | // eoption_opt.setHide(1); |
| 955 | // band_opt.setHide(1); |
| 956 | // bstart_opt.setHide(1); |
| 957 | // bend_opt.setHide(1); |
| 958 | // balance_opt.setHide(1); |
| 959 | // minSize_opt.setHide(1); |
| 960 | // bag_opt.setHide(1); |
| 961 | // bagSize_opt.setHide(1); |
| 962 | // comb_opt.setHide(1); |
| 963 | // classBag_opt.setHide(1); |
| 964 | // prob_opt.setHide(1); |
| 965 | // priorimg_opt.setHide(1); |
| 966 | // offset_opt.setHide(1); |
| 967 | // scale_opt.setHide(1); |
| 968 | // svm_type_opt.setHide(1); |
| 969 | // kernel_type_opt.setHide(1); |
| 970 | // kernel_degree_opt.setHide(1); |
| 971 | // coef0_opt.setHide(1); |
| 972 | // nu_opt.setHide(1); |
| 973 | // epsilon_loss_opt.setHide(1); |
| 974 | // cache_opt.setHide(1); |
| 975 | // epsilon_tol_opt.setHide(1); |
| 976 | // shrinking_opt.setHide(1); |
| 977 | // prob_est_opt.setHide(1); |
| 978 | // entropy_opt.setHide(1); |
| 979 | // active_opt.setHide(1); |
| 980 | // nactive_opt.setHide(1); |
| 981 | // random_opt.setHide(1); |
| 982 | // verbose_opt.setHide(2); |
| 983 | |
| 984 | // bool doProcess;//stop process when program was invoked with help option (-h --help) |
| 985 | // try{ |
| 986 | // doProcess=training_opt.retrieveOption(app); |
| 987 | // cv_opt.retrieveOption(app); |
| 988 | // cmformat_opt.retrieveOption(app); |
| 989 | // tlayer_opt.retrieveOption(app); |
| 990 | // classname_opt.retrieveOption(app); |
| 991 | // classvalue_opt.retrieveOption(app); |
| 992 | // ogrformat_opt.retrieveOption(app); |
| 993 | // colorTable_opt.retrieveOption(app); |
| 994 | // label_opt.retrieveOption(app); |
| 995 | // priors_opt.retrieveOption(app); |
| 996 | // gamma_opt.retrieveOption(app); |
| 997 | // ccost_opt.retrieveOption(app); |
| 998 | // extent_opt.retrieveOption(app); |
| 999 | // eoption_opt.retrieveOption(app); |
| 1000 | // mask_opt.retrieveOption(app); |
| 1001 | // msknodata_opt.retrieveOption(app); |
| 1002 | // nodata_opt.retrieveOption(app); |
| 1003 | // // Advanced options |
| 1004 | // band_opt.retrieveOption(app); |
| 1005 | // bstart_opt.retrieveOption(app); |
| 1006 | // bend_opt.retrieveOption(app); |
| 1007 | // balance_opt.retrieveOption(app); |
| 1008 | // minSize_opt.retrieveOption(app); |
| 1009 | // bag_opt.retrieveOption(app); |
| 1010 | // bagSize_opt.retrieveOption(app); |
| 1011 | // comb_opt.retrieveOption(app); |
| 1012 | // classBag_opt.retrieveOption(app); |
| 1013 | // prob_opt.retrieveOption(app); |
| 1014 | // priorimg_opt.retrieveOption(app); |
| 1015 | // offset_opt.retrieveOption(app); |
| 1016 | // scale_opt.retrieveOption(app); |
| 1017 | // svm_type_opt.retrieveOption(app); |
| 1018 | // kernel_type_opt.retrieveOption(app); |
| 1019 | // kernel_degree_opt.retrieveOption(app); |
| 1020 | // coef0_opt.retrieveOption(app); |
| 1021 | // nu_opt.retrieveOption(app); |
| 1022 | // epsilon_loss_opt.retrieveOption(app); |
| 1023 | // cache_opt.retrieveOption(app); |
| 1024 | // epsilon_tol_opt.retrieveOption(app); |
| 1025 | // shrinking_opt.retrieveOption(app); |
| 1026 | // prob_est_opt.retrieveOption(app); |
| 1027 | // entropy_opt.retrieveOption(app); |
| 1028 | // active_opt.retrieveOption(app); |
| 1029 | // nactive_opt.retrieveOption(app); |
| 1030 | // verbose_opt.retrieveOption(app); |
| 1031 | // random_opt.retrieveOption(app); |
| 1032 | // // memory_opt.retrieveOption(app); |
| 1033 | |
| 1034 | // if(!doProcess){ |
| 1035 | // cout << endl; |
| 1036 | // std::ostringstream helpStream; |
| 1037 | // helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl; |
| 1038 | // throw(helpStream.str());//help was invoked, stop processing |
| 1039 | // } |
| 1040 | |
| 1041 | // if(entropy_opt[0]=="") |
| 1042 | // entropy_opt.clear(); |
| 1043 | // if(active_opt[0]=="") |
| 1044 | // active_opt.clear(); |
| 1045 | // if(priorimg_opt[0]=="") |
| 1046 | // priorimg_opt.clear(); |
| 1047 | |
| 1048 | |
| 1049 | // std::map<std::string, svm::SVM_TYPE> svmMap; |
| 1050 | |
| 1051 | // svmMap["C_SVC"]=svm::C_SVC; |
| 1052 | // svmMap["nu_SVC"]=svm::nu_SVC; |
| 1053 | // svmMap["one_class"]=svm::one_class; |
| 1054 | // svmMap["epsilon_SVR"]=svm::epsilon_SVR; |
| 1055 | // svmMap["nu_SVR"]=svm::nu_SVR; |
| 1056 | |
| 1057 | // std::map<std::string, svm::KERNEL_TYPE> kernelMap; |
| 1058 | |
| 1059 | // kernelMap["linear"]=svm::linear; |
| 1060 | // kernelMap["polynomial"]=svm::polynomial; |
| 1061 | // kernelMap["radial"]=svm::radial; |
| 1062 | // kernelMap["sigmoid;"]=svm::sigmoid; |
| 1063 | |
| 1064 | // if(training_opt.empty()){ |
| 1065 | // string errorString="Error: no training vector dataset provided"; |
| 1066 | // throw(errorString); |
| 1067 | // } |
| 1068 | |
| 1069 | // if(verbose_opt[0]>=1){ |
| 1070 | // if(mask_opt.size()) |
| 1071 | // std::cout << "mask filename: " << mask_opt[0] << std::endl; |
| 1072 | // std::cout << "training vector file: " << std::endl; |
| 1073 | // for(unsigned int ifile=0;ifile<training_opt.size();++ifile) |
| 1074 | // std::cout << training_opt[ifile] << std::endl; |
| 1075 | // std::cout << "verbose: " << verbose_opt[0] << std::endl; |
| 1076 | // } |
| 1077 | // unsigned short nbag=(training_opt.size()>1)?training_opt.size():bag_opt[0]; |
| 1078 | // if(verbose_opt[0]>=1) |
| 1079 | // std::cout << "number of bootstrap aggregations: " << nbag << std::endl; |
| 1080 | |
| 1081 | // ImgReaderOgr extentReader; |
| 1082 | // Jim maskReader; |
| 1083 | // // OGRLayer *readLayer; |
| 1084 | |
| 1085 | // double ulx=0; |
| 1086 | // double uly=0; |
| 1087 | // double lrx=0; |
| 1088 | // double lry=0; |
| 1089 | |
| 1090 | // // bool maskIsVector=false; |
| 1091 | // if(extent_opt.size()){ |
| 1092 | // if(mask_opt.size()){ |
| 1093 | // string errorString="Error: can only either mask or extent, not both"; |
| 1094 | // throw(errorString); |
| 1095 | // } |
| 1096 | // extentReader.open(extent_opt[0]); |
| 1097 | // // readLayer = extentReader.getDataSource()->GetLayer(0); |
| 1098 | // if(!(extentReader.getExtent(ulx,uly,lrx,lry))){ |
| 1099 | // cerr << "Error: could not get extent from " << mask_opt[0] << endl; |
| 1100 | // exit(1); |
| 1101 | // } |
| 1102 | // maskReader.open(this->nrOfCol(),this->nrOfRow(),1,GDT_Float64); |
| 1103 | // double gt[6]; |
| 1104 | // this->getGeoTransform(gt); |
| 1105 | // maskReader.setGeoTransform(gt); |
| 1106 | // maskReader.setProjection(this->getProjection()); |
| 1107 | // // vector<double> burnValues(1,1);//burn value is 1 (single band) |
| 1108 | // // maskReader.rasterizeBuf(extentReader); |
| 1109 | // maskReader.rasterizeBuf(extentReader,nodata_opt[0],eoption_opt); |
| 1110 | // maskReader.GDALSetNoDataValue(nodata_opt[0]); |
| 1111 | // extentReader.close(); |
| 1112 | // } |
| 1113 | |
| 1114 | // ImgWriterOgr activeWriter; |
| 1115 | // if(active_opt.size()){ |
| 1116 | // prob_est_opt[0]=true; |
| 1117 | // ImgReaderOgr trainingReader(training_opt[0]); |
| 1118 | // activeWriter.open(active_opt[0],ogrformat_opt[0]); |
| 1119 | // activeWriter.createLayer(active_opt[0],trainingReader.getProjection(),wkbPoint,NULL); |
| 1120 | // activeWriter.copyFields(trainingReader); |
| 1121 | // } |
| 1122 | // vector<PosValue> activePoints(nactive_opt[0]); |
| 1123 | // for(unsigned int iactive=0;iactive<activePoints.size();++iactive){ |
| 1124 | // activePoints[iactive].value=1.0; |
| 1125 | // activePoints[iactive].posx=0.0; |
| 1126 | // activePoints[iactive].posy=0.0; |
| 1127 | // } |
| 1128 | |
| 1129 | // unsigned int totalSamples=0; |
| 1130 | // unsigned int nactive=0; |
| 1131 | // vector<struct svm_model*> svm(nbag); |
| 1132 | // vector<struct svm_parameter> param(nbag); |
| 1133 | |
| 1134 | // unsigned int nclass=0; |
| 1135 | // unsigned int nband=0; |
| 1136 | // unsigned int startBand=2;//first two bands represent X and Y pos |
| 1137 | |
| 1138 | // //normalize priors from command line |
| 1139 | // if(priors_opt.size()>1){//priors from argument list |
| 1140 | // priors.resize(priors_opt.size()); |
| 1141 | // double normPrior=0; |
| 1142 | // for(unsigned short iclass=0;iclass<priors_opt.size();++iclass){ |
| 1143 | // priors[iclass]=priors_opt[iclass]; |
| 1144 | // normPrior+=priors[iclass]; |
| 1145 | // } |
| 1146 | // //normalize |
| 1147 | // for(unsigned short iclass=0;iclass<priors_opt.size();++iclass) |
| 1148 | // priors[iclass]/=normPrior; |
| 1149 | // } |
| 1150 | |
| 1151 | // //convert start and end band options to vector of band indexes |
| 1152 | // if(bstart_opt.size()){ |
| 1153 | // if(bend_opt.size()!=bstart_opt.size()){ |
| 1154 | // string errorstring="Error: options for start and end band indexes must be provided as pairs, missing end band"; |
| 1155 | // throw(errorstring); |
| 1156 | // } |
| 1157 | // band_opt.clear(); |
| 1158 | // for(int ipair=0;ipair<bstart_opt.size();++ipair){ |
| 1159 | // if(bend_opt[ipair]<=bstart_opt[ipair]){ |
| 1160 | // string errorstring="Error: index for end band must be smaller then start band"; |
| 1161 | // throw(errorstring); |
| 1162 | // } |
| 1163 | // for(unsigned int iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband) |
| 1164 | // band_opt.push_back(iband); |
| 1165 | // } |
| 1166 | // } |
| 1167 | |
| 1168 | // //sort bands |
| 1169 | // if(band_opt.size()) |
| 1170 | // std::sort(band_opt.begin(),band_opt.end()); |
| 1171 | |
| 1172 | // map<string,short> classValueMap; |
| 1173 | // vector<std::string> nameVector; |
| 1174 | // if(classname_opt.size()){ |
| 1175 | // assert(classname_opt.size()==classvalue_opt.size()); |
| 1176 | // for(unsigned int iclass=0;iclass<classname_opt.size();++iclass) |
| 1177 | // classValueMap[classname_opt[iclass]]=classvalue_opt[iclass]; |
| 1178 | // } |
| 1179 | |
| 1180 | // //----------------------------------- Training ------------------------------- |
| 1181 | // confusionmatrix::ConfusionMatrix cm; |
| 1182 | // vector< vector<double> > offset(nbag); |
| 1183 | // vector< vector<double> > scale(nbag); |
| 1184 | // map<string,Vector2d<float> > trainingMap; |
| 1185 | // vector< Vector2d<float> > trainingPixels;//[class][sample][band] |
| 1186 | // vector<string> fields; |
| 1187 | |
| 1188 | // vector<struct svm_problem> prob(nbag); |
| 1189 | // vector<struct svm_node *> x_space(nbag); |
| 1190 | |
| 1191 | // for(int ibag=0;ibag<nbag;++ibag){ |
| 1192 | // //organize training data |
| 1193 | // if(ibag<training_opt.size()){//if bag contains new training pixels |
| 1194 | // trainingMap.clear(); |
| 1195 | // trainingPixels.clear(); |
| 1196 | // if(verbose_opt[0]>=1) |
| 1197 | // std::cout << "reading imageVector file " << training_opt[0] << std::endl; |
| 1198 | // ImgReaderOgr trainingReaderBag(training_opt[ibag]); |
| 1199 | // if(band_opt.size()) |
| 1200 | // //todo: when tlayer_opt is provided, readDataImageOgr does not read any layer |
| 1201 | // totalSamples=trainingReaderBag.readDataImageOgr(trainingMap,fields,band_opt,label_opt[0],tlayer_opt,verbose_opt[0]); |
| 1202 | // else |
| 1203 | // totalSamples=trainingReaderBag.readDataImageOgr(trainingMap,fields,0,0,label_opt[0],tlayer_opt,verbose_opt[0]); |
| 1204 | // if(trainingMap.size()<2){ |
| 1205 | // string errorstring="Error: could not read at least two classes from training file, did you provide class labels in training sample (see option label)?"; |
| 1206 | // throw(errorstring); |
| 1207 | // } |
| 1208 | // trainingReaderBag.close(); |
| 1209 | // //convert map to vector |
| 1210 | // // short iclass=0; |
| 1211 | // if(verbose_opt[0]>1) |
| 1212 | // std::cout << "training pixels: " << std::endl; |
| 1213 | // map<string,Vector2d<float> >::iterator mapit=trainingMap.begin(); |
| 1214 | // while(mapit!=trainingMap.end()){ |
| 1215 | // //delete small classes |
| 1216 | // if((mapit->second).size()<minSize_opt[0]){ |
| 1217 | // trainingMap.erase(mapit); |
| 1218 | // continue; |
| 1219 | // } |
| 1220 | // trainingPixels.push_back(mapit->second); |
| 1221 | // if(verbose_opt[0]>1) |
| 1222 | // std::cout << mapit->first << ": " << (mapit->second).size() << " samples" << std::endl; |
| 1223 | // ++mapit; |
| 1224 | // } |
| 1225 | // if(!ibag){ |
| 1226 | // nclass=trainingPixels.size(); |
| 1227 | // if(classname_opt.size()) |
| 1228 | // assert(nclass==classname_opt.size()); |
| 1229 | // nband=trainingPixels[0][0].size()-2;//X and Y//trainingPixels[0][0].size(); |
| 1230 | // } |
| 1231 | // else{ |
| 1232 | // assert(nclass==trainingPixels.size()); |
| 1233 | // assert(nband==trainingPixels[0][0].size()-2); |
| 1234 | // } |
| 1235 | |
| 1236 | // //do not remove outliers here: could easily be obtained through ogr2ogr -where 'B2<110' output.shp input.shp |
| 1237 | // //balance training data |
| 1238 | // if(balance_opt[0]>0){ |
| 1239 | // while(balance_opt.size()<nclass) |
| 1240 | // balance_opt.push_back(balance_opt.back()); |
| 1241 | // if(random_opt[0]) |
| 1242 | // srand(time(NULL)); |
| 1243 | // totalSamples=0; |
| 1244 | // for(short iclass=0;iclass<nclass;++iclass){ |
| 1245 | // if(trainingPixels[iclass].size()>balance_opt[iclass]){ |
| 1246 | // while(trainingPixels[iclass].size()>balance_opt[iclass]){ |
| 1247 | // int index=rand()%trainingPixels[iclass].size(); |
| 1248 | // trainingPixels[iclass].erase(trainingPixels[iclass].begin()+index); |
| 1249 | // } |
| 1250 | // } |
| 1251 | // else{ |
| 1252 | // int oldsize=trainingPixels[iclass].size(); |
| 1253 | // for(int isample=trainingPixels[iclass].size();isample<balance_opt[iclass];++isample){ |
| 1254 | // int index = rand()%oldsize; |
| 1255 | // trainingPixels[iclass].push_back(trainingPixels[iclass][index]); |
| 1256 | // } |
| 1257 | // } |
| 1258 | // totalSamples+=trainingPixels[iclass].size(); |
| 1259 | // } |
| 1260 | // } |
| 1261 | |
| 1262 | // //set scale and offset |
| 1263 | // offset[ibag].resize(nband); |
| 1264 | // scale[ibag].resize(nband); |
| 1265 | // if(offset_opt.size()>1) |
| 1266 | // assert(offset_opt.size()==nband); |
| 1267 | // if(scale_opt.size()>1) |
| 1268 | // assert(scale_opt.size()==nband); |
| 1269 | // for(int iband=0;iband<nband;++iband){ |
| 1270 | // if(verbose_opt[0]>=1) |
| 1271 | // std::cout << "scaling for band" << iband << std::endl; |
| 1272 | // offset[ibag][iband]=(offset_opt.size()==1)?offset_opt[0]:offset_opt[iband]; |
| 1273 | // scale[ibag][iband]=(scale_opt.size()==1)?scale_opt[0]:scale_opt[iband]; |
| 1274 | // //search for min and maximum |
| 1275 | // if(scale[ibag][iband]<=0){ |
| 1276 | // float theMin=trainingPixels[0][0][iband+startBand]; |
| 1277 | // float theMax=trainingPixels[0][0][iband+startBand]; |
| 1278 | // for(short iclass=0;iclass<nclass;++iclass){ |
| 1279 | // for(int isample=0;isample<trainingPixels[iclass].size();++isample){ |
| 1280 | // if(theMin>trainingPixels[iclass][isample][iband+startBand]) |
| 1281 | // theMin=trainingPixels[iclass][isample][iband+startBand]; |
| 1282 | // if(theMax<trainingPixels[iclass][isample][iband+startBand]) |
| 1283 | // theMax=trainingPixels[iclass][isample][iband+startBand]; |
| 1284 | // } |
| 1285 | // } |
| 1286 | // offset[ibag][iband]=theMin+(theMax-theMin)/2.0; |
| 1287 | // scale[ibag][iband]=(theMax-theMin)/2.0; |
| 1288 | // if(verbose_opt[0]>=1){ |
| 1289 | // std::cout << "Extreme image values for band " << iband << ": [" << theMin << "," << theMax << "]" << std::endl; |
| 1290 | // std::cout << "Using offset, scale: " << offset[ibag][iband] << ", " << scale[ibag][iband] << std::endl; |
| 1291 | // std::cout << "scaled values for band " << iband << ": [" << (theMin-offset[ibag][iband])/scale[ibag][iband] << "," << (theMax-offset[ibag][iband])/scale[ibag][iband] << "]" << std::endl; |
| 1292 | // } |
| 1293 | // } |
| 1294 | // } |
| 1295 | // } |
| 1296 | // else{//use same offset and scale |
| 1297 | // offset[ibag].resize(nband); |
| 1298 | // scale[ibag].resize(nband); |
| 1299 | // for(int iband=0;iband<nband;++iband){ |
| 1300 | // offset[ibag][iband]=offset[0][iband]; |
| 1301 | // scale[ibag][iband]=scale[0][iband]; |
| 1302 | // } |
| 1303 | // } |
| 1304 | |
| 1305 | // if(!ibag){ |
| 1306 | // if(priors_opt.size()==1){//default: equal priors for each class |
| 1307 | // priors.resize(nclass); |
| 1308 | // for(short iclass=0;iclass<nclass;++iclass) |
| 1309 | // priors[iclass]=1.0/nclass; |
| 1310 | // } |
| 1311 | // assert(priors_opt.size()==1||priors_opt.size()==nclass); |
| 1312 | |
| 1313 | // //set bagsize for each class if not done already via command line |
| 1314 | // while(bagSize_opt.size()<nclass) |
| 1315 | // bagSize_opt.push_back(bagSize_opt.back()); |
| 1316 | |
| 1317 | // if(verbose_opt[0]>=1){ |
| 1318 | // std::cout << "number of bands: " << nband << std::endl; |
| 1319 | // std::cout << "number of classes: " << nclass << std::endl; |
| 1320 | // if(priorimg_opt.empty()){ |
| 1321 | // std::cout << "priors:"; |
| 1322 | // for(short iclass=0;iclass<nclass;++iclass) |
| 1323 | // std::cout << " " << priors[iclass]; |
| 1324 | // std::cout << std::endl; |
| 1325 | // } |
| 1326 | // } |
| 1327 | // map<string,Vector2d<float> >::iterator mapit=trainingMap.begin(); |
| 1328 | // bool doSort=true; |
| 1329 | // while(mapit!=trainingMap.end()){ |
| 1330 | // nameVector.push_back(mapit->first); |
| 1331 | // if(classValueMap.size()){ |
| 1332 | // //check if name in training is covered by classname_opt (values can not be 0) |
| 1333 | // if(classValueMap[mapit->first]>0){ |
| 1334 | // if(cm.getClassIndex(type2string<short>(classValueMap[mapit->first]))<0){ |
| 1335 | // cm.pushBackClassName(type2string<short>(classValueMap[mapit->first]),doSort); |
| 1336 | // } |
| 1337 | // } |
| 1338 | // else{ |
| 1339 | // std::cerr << "Error: names in classname option are not complete, please check names in training vector and make sure classvalue is > 0" << std::endl; |
| 1340 | // exit(1); |
| 1341 | // } |
| 1342 | // } |
| 1343 | // else |
| 1344 | // cm.pushBackClassName(mapit->first,doSort); |
| 1345 | // ++mapit; |
| 1346 | // } |
| 1347 | // if(classname_opt.empty()){ |
| 1348 | // //std::cerr << "Warning: no class name and value pair provided for all " << nclass << " classes, using string2type<int> instead!" << std::endl; |
| 1349 | // for(int iclass=0;iclass<nclass;++iclass){ |
| 1350 | // if(verbose_opt[0]) |
| 1351 | // std::cout << iclass << " " << cm.getClass(iclass) << " -> " << string2type<short>(cm.getClass(iclass)) << std::endl; |
| 1352 | // classValueMap[cm.getClass(iclass)]=string2type<short>(cm.getClass(iclass)); |
| 1353 | // } |
| 1354 | // } |
| 1355 | |
| 1356 | // // if(priors_opt.size()==nameVector.size()){ |
| 1357 | // // std::cerr << "Warning: please check if priors are provided in correct order!!!" << std::endl; |
| 1358 | // // for(int iclass=0;iclass<nameVector.size();++iclass) |
| 1359 | // // std::cerr << nameVector[iclass] << " " << priors_opt[iclass] << std::endl; |
| 1360 | // // } |
| 1361 | // }//if(!ibag) |
| 1362 | |
| 1363 | // //Calculate features of training set |
| 1364 | // vector< Vector2d<float> > trainingFeatures(nclass); |
| 1365 | // for(short iclass=0;iclass<nclass;++iclass){ |
| 1366 | // int nctraining=0; |
| 1367 | // if(verbose_opt[0]>=1) |
| 1368 | // std::cout << "calculating features for class " << iclass << std::endl; |
| 1369 | // if(random_opt[0]) |
| 1370 | // srand(time(NULL)); |
| 1371 | // nctraining=(bagSize_opt[iclass]<100)? trainingPixels[iclass].size()/100.0*bagSize_opt[iclass] : trainingPixels[iclass].size();//bagSize_opt[iclass] given in % of training size |
| 1372 | // if(nctraining<=0) |
| 1373 | // nctraining=1; |
| 1374 | // assert(nctraining<=trainingPixels[iclass].size()); |
| 1375 | // if(bagSize_opt[iclass]<100) |
| 1376 | // random_shuffle(trainingPixels[iclass].begin(),trainingPixels[iclass].end()); |
| 1377 | // if(verbose_opt[0]>1) |
| 1378 | // std::cout << "nctraining (class " << iclass << "): " << nctraining << std::endl; |
| 1379 | // trainingFeatures[iclass].resize(nctraining); |
| 1380 | // for(int isample=0;isample<nctraining;++isample){ |
| 1381 | // //scale pixel values according to scale and offset!!! |
| 1382 | // for(int iband=0;iband<nband;++iband){ |
| 1383 | // float value=trainingPixels[iclass][isample][iband+startBand]; |
| 1384 | // trainingFeatures[iclass][isample].push_back((value-offset[ibag][iband])/scale[ibag][iband]); |
| 1385 | // } |
| 1386 | // } |
| 1387 | // assert(trainingFeatures[iclass].size()==nctraining); |
| 1388 | // } |
| 1389 | |
| 1390 | // unsigned int nFeatures=trainingFeatures[0][0].size(); |
| 1391 | // if(verbose_opt[0]>=1) |
| 1392 | // std::cout << "number of features: " << nFeatures << std::endl; |
| 1393 | // unsigned int ntraining=0; |
| 1394 | // for(short iclass=0;iclass<nclass;++iclass) |
| 1395 | // ntraining+=trainingFeatures[iclass].size(); |
| 1396 | // if(verbose_opt[0]>=1) |
| 1397 | // std::cout << "training size over all classes: " << ntraining << std::endl; |
| 1398 | |
| 1399 | // prob[ibag].l=ntraining; |
| 1400 | // prob[ibag].y = Malloc(double,prob[ibag].l); |
| 1401 | // prob[ibag].x = Malloc(struct svm_node *,prob[ibag].l); |
| 1402 | // x_space[ibag] = Malloc(struct svm_node,(nFeatures+1)*ntraining); |
| 1403 | // unsigned long int spaceIndex=0; |
| 1404 | // int lIndex=0; |
| 1405 | // for(short iclass=0;iclass<nclass;++iclass){ |
| 1406 | // for(int isample=0;isample<trainingFeatures[iclass].size();++isample){ |
| 1407 | // prob[ibag].x[lIndex]=&(x_space[ibag][spaceIndex]); |
| 1408 | // for(int ifeature=0;ifeature<nFeatures;++ifeature){ |
| 1409 | // x_space[ibag][spaceIndex].index=ifeature+1; |
| 1410 | // x_space[ibag][spaceIndex].value=trainingFeatures[iclass][isample][ifeature]; |
| 1411 | // ++spaceIndex; |
| 1412 | // } |
| 1413 | // x_space[ibag][spaceIndex++].index=-1; |
| 1414 | // prob[ibag].y[lIndex]=iclass; |
| 1415 | // ++lIndex; |
| 1416 | // } |
| 1417 | // } |
| 1418 | // assert(lIndex==prob[ibag].l); |
| 1419 | |
| 1420 | // //set SVM parameters through command line options |
| 1421 | // param[ibag].svm_type = svmMap[svm_type_opt[0]]; |
| 1422 | // param[ibag].kernel_type = kernelMap[kernel_type_opt[0]]; |
| 1423 | // param[ibag].degree = kernel_degree_opt[0]; |
| 1424 | // param[ibag].gamma = (gamma_opt[0]>0)? gamma_opt[0] : 1.0/nFeatures; |
| 1425 | // param[ibag].coef0 = coef0_opt[0]; |
| 1426 | // param[ibag].nu = nu_opt[0]; |
| 1427 | // param[ibag].cache_size = cache_opt[0]; |
| 1428 | // param[ibag].C = ccost_opt[0]; |
| 1429 | // param[ibag].eps = epsilon_tol_opt[0]; |
| 1430 | // param[ibag].p = epsilon_loss_opt[0]; |
| 1431 | // param[ibag].shrinking = (shrinking_opt[0])? 1 : 0; |
| 1432 | // param[ibag].probability = (prob_est_opt[0])? 1 : 0; |
| 1433 | // param[ibag].nr_weight = 0;//not used: I use priors and balancing |
| 1434 | // param[ibag].weight_label = NULL; |
| 1435 | // param[ibag].weight = NULL; |
| 1436 | // param[ibag].verbose=(verbose_opt[0]>1)? true:false; |
| 1437 | |
| 1438 | // if(verbose_opt[0]>1) |
| 1439 | // std::cout << "checking parameters" << std::endl; |
| 1440 | // svm_check_parameter(&prob[ibag],¶m[ibag]); |
| 1441 | // if(verbose_opt[0]) |
| 1442 | // std::cout << "parameters ok, training" << std::endl; |
| 1443 | // svm[ibag]=svm_train(&prob[ibag],¶m[ibag]); |
| 1444 | // if(verbose_opt[0]>1) |
| 1445 | // std::cout << "SVM is now trained" << std::endl; |
| 1446 | // if(cv_opt[0]>1){ |
| 1447 | // if(verbose_opt[0]>1) |
| 1448 | // std::cout << "Cross validating" << std::endl; |
| 1449 | // double *target = Malloc(double,prob[ibag].l); |
| 1450 | // svm_cross_validation(&prob[ibag],¶m[ibag],cv_opt[0],target); |
| 1451 | // assert(param[ibag].svm_type != EPSILON_SVR&¶m[ibag].svm_type != NU_SVR);//only for regression |
| 1452 | |
| 1453 | // for(int i=0;i<prob[ibag].l;i++){ |
| 1454 | // string refClassName=nameVector[prob[ibag].y[i]]; |
| 1455 | // string className=nameVector[target[i]]; |
| 1456 | // if(classValueMap.size()) |
| 1457 | // cm.incrementResult(type2string<short>(classValueMap[refClassName]),type2string<short>(classValueMap[className]),1.0/nbag); |
| 1458 | // else |
| 1459 | // cm.incrementResult(cm.getClass(prob[ibag].y[i]),cm.getClass(target[i]),1.0/nbag); |
| 1460 | // } |
| 1461 | // free(target); |
| 1462 | // } |
| 1463 | // // *NOTE* Because svm_model contains pointers to svm_problem, you can |
| 1464 | // // not free the memory used by svm_problem if you are still using the |
| 1465 | // // svm_model produced by svm_train(). |
| 1466 | // }//for ibag |
| 1467 | // if(cv_opt[0]>1){ |
| 1468 | // assert(cm.nReference()); |
| 1469 | // cm.setFormat(cmformat_opt[0]); |
| 1470 | // cm.reportSE95(false); |
| 1471 | // std::cout << cm << std::endl; |
| 1472 | // } |
| 1473 | |
| 1474 | // //--------------------------------- end of training ----------------------------------- |
| 1475 | |
| 1476 | // const char* pszMessage; |
| 1477 | // void* pProgressArg=NULL; |
| 1478 | // GDALProgressFunc pfnProgress=GDALTermProgress; |
| 1479 | // float progress=0; |
| 1480 | // if(!verbose_opt[0]) |
| 1481 | // MyProgressFunc(progress,pszMessage,pProgressArg); |
| 1482 | // //-------------------------------- open image file ------------------------------------ |
| 1483 | // // bool inputIsRaster=false; |
| 1484 | // bool inputIsRaster=true; |
| 1485 | // // ImgReaderOgr imgReaderOgr; |
| 1486 | // // //todo: will not work in GDAL v2.0 |
| 1487 | // // try{ |
| 1488 | // // imgReaderOgr.open(input_opt[0]); |
| 1489 | // // imgReaderOgr.close(); |
| 1490 | // // } |
| 1491 | // // catch(string errorString){ |
| 1492 | // // inputIsRaster=true; |
| 1493 | // // } |
| 1494 | // // if(inputIsRaster){ |
| 1495 | // int nrow=nrOfRow(); |
| 1496 | // int ncol=nrOfCol(); |
| 1497 | // if(this->isInit()){ |
| 1498 | // if(verbose_opt[0]>=1) |
| 1499 | // std::cout << "opening image" << std::endl; |
| 1500 | // // imgWriter.open(*this,false); |
| 1501 | // imgWriter.open(ncol,nrow,1,GDT_Byte); |
| 1502 | // imgWriter.GDALSetNoDataValue(nodata_opt[0]); |
| 1503 | // imgWriter.copyGeoTransform(*this); |
| 1504 | // imgWriter.setProjection(this->getProjection()); |
| 1505 | // if(colorTable_opt.size()) |
| 1506 | // imgWriter.setColorTable(colorTable_opt[0],0); |
| 1507 | // Jim priorReader; |
| 1508 | // if(priorimg_opt.size()){ |
| 1509 | // if(verbose_opt[0]>=1) |
| 1510 | // std::cout << "opening prior image " << priorimg_opt[0] << std::endl; |
| 1511 | // priorReader.open(priorimg_opt[0]); |
| 1512 | // assert(priorReader.nrOfCol()==ncol); |
| 1513 | // assert(priorReader.nrOfRow()==nrow); |
| 1514 | // } |
| 1515 | |
| 1516 | // vector<char> classOut(ncol);//classified line for writing to image file |
| 1517 | |
| 1518 | // // assert(nband==imgWriter.nrOfBand()); |
| 1519 | // Jim classImageBag; |
| 1520 | // // Jim imgWriter. |
| 1521 | // Jim probImage; |
| 1522 | // Jim entropyImage; |
| 1523 | |
| 1524 | // string imageType=imgWriter.getImageType(); |
| 1525 | // if(classBag_opt.size()){ |
| 1526 | // classImageBag.open(classBag_opt[0],ncol,nrow,nbag,GDT_Byte,imageType); |
| 1527 | // classImageBag.GDALSetNoDataValue(nodata_opt[0]); |
| 1528 | // classImageBag.copyGeoTransform(imgWriter); |
| 1529 | // classImageBag.setProjection(this->getProjection()); |
| 1530 | // } |
| 1531 | // if(prob_opt.size()){ |
| 1532 | // probImage.open(prob_opt[0],ncol,nrow,nclass,GDT_Byte,imageType); |
| 1533 | // probImage.GDALSetNoDataValue(nodata_opt[0]); |
| 1534 | // probImage.copyGeoTransform(imgWriter); |
| 1535 | // probImage.setProjection(this->getProjection()); |
| 1536 | // } |
| 1537 | // if(entropy_opt.size()){ |
| 1538 | // entropyImage.open(entropy_opt[0],ncol,nrow,1,GDT_Byte,imageType); |
| 1539 | // entropyImage.GDALSetNoDataValue(nodata_opt[0]); |
| 1540 | // entropyImage.copyGeoTransform(imgWriter); |
| 1541 | // entropyImage.setProjection(this->getProjection()); |
| 1542 | // } |
| 1543 | |
| 1544 | // if(mask_opt.size()){ |
| 1545 | // if(verbose_opt[0]>=1) |
| 1546 | // std::cout << "opening mask image file " << mask_opt[0] << std::endl; |
| 1547 | // maskReader.open(mask_opt[0]); |
| 1548 | // } |
| 1549 | |
| 1550 | // for(unsigned int iline=0;iline<nrow;++iline){ |
| 1551 | // vector<float> buffer(ncol); |
| 1552 | // vector<short> lineMask; |
| 1553 | // Vector2d<float> linePrior; |
| 1554 | // if(priorimg_opt.size()) |
| 1555 | // linePrior.resize(nclass,ncol);//prior prob for each class |
| 1556 | // Vector2d<float> hpixel(ncol); |
| 1557 | // Vector2d<float> probOut(nclass,ncol);//posterior prob for each (internal) class |
| 1558 | // vector<float> entropy(ncol); |
| 1559 | // Vector2d<char> classBag;//classified line for writing to image file |
| 1560 | // if(classBag_opt.size()) |
| 1561 | // classBag.resize(nbag,ncol); |
| 1562 | // if(band_opt.size()){ |
| 1563 | // for(unsigned int iband=0;iband<band_opt.size();++iband){ |
| 1564 | // if(verbose_opt[0]==2) |
| 1565 | // std::cout << "reading band " << band_opt[iband] << std::endl; |
| 1566 | // assert(band_opt[iband]>=0); |
| 1567 | // assert(band_opt[iband]<imgWriter.nrOfBand()); |
| 1568 | // readData(buffer,iline,band_opt[iband]); |
| 1569 | // for(unsigned int icol=0;icol<ncol;++icol) |
| 1570 | // hpixel[icol].push_back(buffer[icol]); |
| 1571 | // } |
| 1572 | // } |
| 1573 | // else{ |
| 1574 | // for(unsigned int iband=0;iband<nband;++iband){ |
| 1575 | // if(verbose_opt[0]==2) |
| 1576 | // std::cout << "reading band " << iband << std::endl; |
| 1577 | // assert(iband>=0); |
| 1578 | // assert(iband<imgWriter.nrOfBand()); |
| 1579 | // readData(buffer,iline,iband); |
| 1580 | // for(unsigned int icol=0;icol<ncol;++icol) |
| 1581 | // hpixel[icol].push_back(buffer[icol]); |
| 1582 | // } |
| 1583 | // } |
| 1584 | // assert(nband==hpixel[0].size()); |
| 1585 | // if(verbose_opt[0]>1) |
| 1586 | // std::cout << "used bands: " << nband << std::endl; |
| 1587 | // //read prior |
| 1588 | // if(priorimg_opt.size()){ |
| 1589 | // for(unsigned int iclass=0;iclass<nclass;++iclass){ |
| 1590 | // if(verbose_opt.size()>1) |
| 1591 | // std::cout << "Reading " << priorimg_opt[0] << " band " << iclass << " line " << iline << std::endl; |
| 1592 | // priorReader.readData(linePrior[iclass],iline,iclass); |
| 1593 | // } |
| 1594 | // } |
| 1595 | // double oldRowMask=-1;//keep track of row mask to optimize number of line readings |
| 1596 | // //process per pixel |
| 1597 | // for(int icol=0;icol<ncol;++icol){ |
| 1598 | // assert(hpixel[icol].size()==nband); |
| 1599 | // bool doClassify=true; |
| 1600 | // bool masked=false; |
| 1601 | // double geox=0; |
| 1602 | // double geoy=0; |
| 1603 | // if(maskReader.isInit()){ |
| 1604 | // //read mask |
| 1605 | // double colMask=0; |
| 1606 | // double rowMask=0; |
| 1607 | |
| 1608 | // imgWriter.image2geo(icol,iline,geox,geoy); |
| 1609 | // maskReader.geo2image(geox,geoy,colMask,rowMask); |
| 1610 | // colMask=static_cast<int>(colMask); |
| 1611 | // rowMask=static_cast<int>(rowMask); |
| 1612 | // if(rowMask>=0&&rowMask<maskReader.nrOfRow()&&colMask>=0&&colMask<maskReader.nrOfCol()){ |
| 1613 | // if(static_cast<int>(rowMask)!=static_cast<int>(oldRowMask)){ |
| 1614 | // assert(rowMask>=0&&rowMask<maskReader.nrOfRow()); |
| 1615 | // // maskReader.readData(lineMask[imask],GDT_Int32,static_cast<int>(rowMask)); |
| 1616 | // maskReader.readData(lineMask,static_cast<unsigned int>(rowMask)); |
| 1617 | // oldRowMask=rowMask; |
| 1618 | // } |
| 1619 | // short theMask=0; |
| 1620 | // for(short ivalue=0;ivalue<msknodata_opt.size();++ivalue){ |
| 1621 | // // if(msknodata_opt[ivalue]>=0){//values set in msknodata_opt are invalid |
| 1622 | // if(lineMask[colMask]==msknodata_opt[ivalue]){ |
| 1623 | // theMask=lineMask[colMask]; |
| 1624 | // masked=true; |
| 1625 | // break; |
| 1626 | // } |
| 1627 | // // } |
| 1628 | // // else{//only values set in msknodata_opt are valid |
| 1629 | // // if(lineMask[colMask]!=-msknodata_opt[ivalue]){ |
| 1630 | // // theMask=lineMask[colMask]; |
| 1631 | // // masked=true; |
| 1632 | // // } |
| 1633 | // // else{ |
| 1634 | // // masked=false; |
| 1635 | // // break; |
| 1636 | // // } |
| 1637 | // // } |
| 1638 | // } |
| 1639 | // if(masked){ |
| 1640 | // if(classBag_opt.size()) |
| 1641 | // for(int ibag=0;ibag<nbag;++ibag) |
| 1642 | // classBag[ibag][icol]=theMask; |
| 1643 | // classOut[icol]=theMask; |
| 1644 | // continue; |
| 1645 | // } |
| 1646 | // } |
| 1647 | // bool valid=false; |
| 1648 | // for(int iband=0;iband<hpixel[icol].size();++iband){ |
| 1649 | // if(hpixel[icol][iband]){ |
| 1650 | // valid=true; |
| 1651 | // break; |
| 1652 | // } |
| 1653 | // } |
| 1654 | // if(!valid) |
| 1655 | // doClassify=false; |
| 1656 | // } |
| 1657 | // for(short iclass=0;iclass<nclass;++iclass) |
| 1658 | // probOut[iclass][icol]=0; |
| 1659 | // if(!doClassify){ |
| 1660 | // if(classBag_opt.size()) |
| 1661 | // for(int ibag=0;ibag<nbag;++ibag) |
| 1662 | // classBag[ibag][icol]=nodata_opt[0]; |
| 1663 | // classOut[icol]=nodata_opt[0]; |
| 1664 | // continue;//next column |
| 1665 | // } |
| 1666 | // //----------------------------------- classification ------------------- |
| 1667 | // for(int ibag=0;ibag<nbag;++ibag){ |
| 1668 | // vector<double> result(nclass); |
| 1669 | // struct svm_node *x; |
| 1670 | // x = (struct svm_node *) malloc((nband+1)*sizeof(struct svm_node)); |
| 1671 | // for(int iband=0;iband<nband;++iband){ |
| 1672 | // x[iband].index=iband+1; |
| 1673 | // x[iband].value=(hpixel[icol][iband]-offset[ibag][iband])/scale[ibag][iband]; |
| 1674 | // } |
| 1675 | // x[nband].index=-1;//to end svm feature vector |
| 1676 | // double predict_label=0; |
| 1677 | // vector<float> prValues(nclass); |
| 1678 | // float maxP=0; |
| 1679 | // if(!prob_est_opt[0]){ |
| 1680 | // predict_label = svm_predict(svm[ibag],x); |
| 1681 | // for(short iclass=0;iclass<nclass;++iclass){ |
| 1682 | // if(iclass==static_cast<short>(predict_label)) |
| 1683 | // result[iclass]=1; |
| 1684 | // else |
| 1685 | // result[iclass]=0; |
| 1686 | // } |
| 1687 | // } |
| 1688 | // else{ |
| 1689 | // if(!svm_check_probability_model(svm[ibag])){ |
| 1690 | // string errorstring="Error: svm probability model check failed"; |
| 1691 | // throw(errorstring); |
| 1692 | // } |
| 1693 | // predict_label = svm_predict_probability(svm[ibag],x,&(result[0])); |
| 1694 | // } |
| 1695 | // //calculate posterior prob of bag |
| 1696 | // if(classBag_opt.size()){ |
| 1697 | // //search for max prob within bag |
| 1698 | // maxP=0; |
| 1699 | // classBag[ibag][icol]=0; |
| 1700 | // } |
| 1701 | // double normPrior=0; |
| 1702 | // if(priorimg_opt.size()){ |
| 1703 | // for(short iclass=0;iclass<nclass;++iclass) |
| 1704 | // normPrior+=linePrior[iclass][icol]; |
| 1705 | // } |
| 1706 | // for(short iclass=0;iclass<nclass;++iclass){ |
| 1707 | // if(priorimg_opt.size()) |
| 1708 | // priors[iclass]=linePrior[iclass][icol]/normPrior;//todo: check if correct for all cases... (automatic classValueMap and manual input for names and values) |
| 1709 | // switch(comb_opt[0]){ |
| 1710 | // default: |
| 1711 | // case(0)://sum rule |
| 1712 | // probOut[iclass][icol]+=result[iclass]*priors[iclass];//add probabilities for each bag |
| 1713 | // break; |
| 1714 | // case(1)://product rule |
| 1715 | // probOut[iclass][icol]*=pow(static_cast<float>(priors[iclass]),static_cast<float>(1.0-nbag)/nbag)*result[iclass];//multiply probabilities for each bag |
| 1716 | // break; |
| 1717 | // case(2)://max rule |
| 1718 | // if(priors[iclass]*result[iclass]>probOut[iclass][icol]) |
| 1719 | // probOut[iclass][icol]=priors[iclass]*result[iclass]; |
| 1720 | // break; |
| 1721 | // } |
| 1722 | // if(classBag_opt.size()){ |
| 1723 | // //search for max prob within bag |
| 1724 | // // if(prValues[iclass]>maxP){ |
| 1725 | // // maxP=prValues[iclass]; |
| 1726 | // // classBag[ibag][icol]=iclass; |
| 1727 | // // } |
| 1728 | // if(result[iclass]>maxP){ |
| 1729 | // maxP=result[iclass]; |
| 1730 | // classBag[ibag][icol]=iclass; |
| 1731 | // } |
| 1732 | // } |
| 1733 | // } |
| 1734 | // free(x); |
| 1735 | // }//ibag |
| 1736 | |
| 1737 | // //search for max class prob |
| 1738 | // float maxBag1=0;//max probability |
| 1739 | // float maxBag2=0;//second max probability |
| 1740 | // float normBag=0; |
| 1741 | // for(short iclass=0;iclass<nclass;++iclass){ |
| 1742 | // if(probOut[iclass][icol]>maxBag1){ |
| 1743 | // maxBag1=probOut[iclass][icol]; |
| 1744 | // classOut[icol]=classValueMap[nameVector[iclass]]; |
| 1745 | // } |
| 1746 | // else if(probOut[iclass][icol]>maxBag2) |
| 1747 | // maxBag2=probOut[iclass][icol]; |
| 1748 | // normBag+=probOut[iclass][icol]; |
| 1749 | // } |
| 1750 | // //normalize probOut and convert to percentage |
| 1751 | // entropy[icol]=0; |
| 1752 | // for(short iclass=0;iclass<nclass;++iclass){ |
| 1753 | // float prv=probOut[iclass][icol]; |
| 1754 | // prv/=normBag; |
| 1755 | // entropy[icol]-=prv*log(prv)/log(2.0); |
| 1756 | // prv*=100.0; |
| 1757 | |
| 1758 | // probOut[iclass][icol]=static_cast<short>(prv+0.5); |
| 1759 | // // assert(classValueMap[nameVector[iclass]]<probOut.size()); |
| 1760 | // // assert(classValueMap[nameVector[iclass]]>=0); |
| 1761 | // // probOut[classValueMap[nameVector[iclass]]][icol]=static_cast<short>(prv+0.5); |
| 1762 | // } |
| 1763 | // entropy[icol]/=log(static_cast<double>(nclass))/log(2.0); |
| 1764 | // entropy[icol]=static_cast<short>(100*entropy[icol]+0.5); |
| 1765 | // if(active_opt.size()){ |
| 1766 | // if(entropy[icol]>activePoints.back().value){ |
| 1767 | // activePoints.back().value=entropy[icol];//replace largest value (last) |
| 1768 | // activePoints.back().posx=icol; |
| 1769 | // activePoints.back().posy=iline; |
| 1770 | // std::sort(activePoints.begin(),activePoints.end(),Decrease_PosValue());//sort in descending order (largest first, smallest last) |
| 1771 | // if(verbose_opt[0]) |
| 1772 | // std::cout << activePoints.back().posx << " " << activePoints.back().posy << " " << activePoints.back().value << std::endl; |
| 1773 | // } |
| 1774 | // } |
| 1775 | // }//icol |
| 1776 | // //----------------------------------- write output ------------------------------------------ |
| 1777 | // if(classBag_opt.size()) |
| 1778 | // for(int ibag=0;ibag<nbag;++ibag) |
| 1779 | // classImageBag.writeData(classBag[ibag],iline,ibag); |
| 1780 | // if(prob_opt.size()){ |
| 1781 | // for(short iclass=0;iclass<nclass;++iclass) |
| 1782 | // probImage.writeData(probOut[iclass],iline,iclass); |
| 1783 | // } |
| 1784 | // if(entropy_opt.size()){ |
| 1785 | // entropyImage.writeData(entropy,iline); |
| 1786 | // } |
| 1787 | // imgWriter.writeData(classOut,iline); |
| 1788 | // if(!verbose_opt[0]){ |
| 1789 | // progress=static_cast<float>(iline+1.0)/imgWriter.nrOfRow(); |
| 1790 | // MyProgressFunc(progress,pszMessage,pProgressArg); |
| 1791 | // } |
| 1792 | // } |
| 1793 | // //write active learning points |
| 1794 | // if(active_opt.size()){ |
| 1795 | // for(int iactive=0;iactive<activePoints.size();++iactive){ |
| 1796 | // std::map<string,double> pointMap; |
| 1797 | // for(int iband=0;iband<imgWriter.nrOfBand();++iband){ |
| 1798 | // double value; |
| 1799 | // readData(value,static_cast<int>(activePoints[iactive].posx),static_cast<int>(activePoints[iactive].posy),iband); |
| 1800 | // ostringstream fs; |
| 1801 | // fs << "B" << iband; |
| 1802 | // pointMap[fs.str()]=value; |
| 1803 | // } |
| 1804 | // pointMap[label_opt[0]]=0; |
| 1805 | // double x, y; |
| 1806 | // imgWriter.image2geo(activePoints[iactive].posx,activePoints[iactive].posy,x,y); |
| 1807 | // std::string fieldname="id";//number of the point |
| 1808 | // activeWriter.addPoint(x,y,pointMap,fieldname,++nactive); |
| 1809 | // } |
| 1810 | // } |
| 1811 | |
| 1812 | // // imgWriter.close(); |
| 1813 | // if(mask_opt.size()) |
| 1814 | // maskReader.close(); |
| 1815 | // if(priorimg_opt.size()) |
| 1816 | // priorReader.close(); |
| 1817 | // if(prob_opt.size()) |
| 1818 | // probImage.close(); |
| 1819 | // if(entropy_opt.size()) |
| 1820 | // entropyImage.close(); |
| 1821 | // if(classBag_opt.size()) |
| 1822 | // classImageBag.close(); |
| 1823 | // // imgWriter.close(); |
| 1824 | // } |
| 1825 | // if(cm.nReference()){ |
| 1826 | // std::cout << cm << std::endl; |
| 1827 | // cout << "class #samples userAcc prodAcc" << endl; |
| 1828 | // double se95_ua=0; |
| 1829 | // double se95_pa=0; |
| 1830 | // double se95_oa=0; |
| 1831 | // double dua=0; |
| 1832 | // double dpa=0; |
| 1833 | // double doa=0; |
| 1834 | // for(short iclass=0;iclass<cm.nClasses();++iclass){ |
| 1835 | // dua=cm.ua_pct(cm.getClass(iclass),&se95_ua); |
| 1836 | // dpa=cm.pa_pct(cm.getClass(iclass),&se95_pa); |
| 1837 | // cout << cm.getClass(iclass) << " " << cm.nReference(cm.getClass(iclass)) << " " << dua << " (" << se95_ua << ")" << " " << dpa << " (" << se95_pa << ")" << endl; |
| 1838 | // } |
| 1839 | // std::cout << "Kappa: " << cm.kappa() << std::endl; |
| 1840 | // doa=cm.oa(&se95_oa); |
| 1841 | // std::cout << "Overall Accuracy: " << 100*doa << " (" << 100*se95_oa << ")" << std::endl; |
| 1842 | // } |
| 1843 | // if(active_opt.size()) |
| 1844 | // activeWriter.close(); |
| 1845 | |
| 1846 | // for(int ibag=0;ibag<nbag;++ibag){ |
| 1847 | // // svm_destroy_param[ibag](¶m[ibag]); |
| 1848 | // svm_destroy_param(¶m[ibag]); |
| 1849 | // free(prob[ibag].y); |
| 1850 | // free(prob[ibag].x); |
| 1851 | // free(x_space[ibag]); |
| 1852 | // svm_free_and_destroy_model(&(svm[ibag])); |
| 1853 | // } |
| 1854 | // return(CE_None); |
| 1855 | // } |
| 1856 | // catch(BadConversion conversionString){ |
| 1857 | // std::cerr << "Error: did you provide class pairs names (-c) and integer values (-r) for each class in training vector?" << std::endl; |
| 1858 | // return(CE_Failure); |
| 1859 | // } |
| 1860 | // catch(string predefinedString){ |
| 1861 | // std::cout << predefinedString << std::endl; |
| 1862 | // return(CE_Failure); |
| 1863 | // } |
| 1864 | // } |