| 1 | /********************************************************************** |
| 2 | jlsvmogr_lib.cc: classify vector dataset 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 "VectorOgr.h" |
| 27 | #include "base/Optionjl.h" |
| 28 | #include "base/PosValue.h" |
| 29 | #include "algorithms/ConfusionMatrix.h" |
| 30 | #include "algorithms/svm.h" |
| 31 | #include "apps/AppFactory.h" |
| 32 | |
| 33 | namespace svm{ |
| 34 | enum SVM_TYPE {C_SVC=0, nu_SVC=1,one_class=2, epsilon_SVR=3, nu_SVR=4}; |
| 35 | enum KERNEL_TYPE {linear=0,polynomial=1,radial=2,sigmoid=3}; |
| 36 | } |
| 37 | |
| 38 | #define Malloc(type,n) (type *)malloc((n)*sizeof(type)) |
| 39 | |
| 40 | using namespace std; |
| 41 | using namespace app; |
| 42 | |
| 43 | /** |
| 44 | * @param app application specific option arguments |
| 45 | * @return output Vector |
| 46 | **/ |
| 47 | shared_ptr<VectorOgr> VectorOgr::classifySVM(app::AppFactory& app){ |
| 48 | std::shared_ptr<VectorOgr> ogrWriter=VectorOgr::createVector(); |
| 49 | classifySVM(*ogrWriter, app); |
| 50 | return(ogrWriter); |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * @param ogrWriter output classified vector dataset |
| 55 | * @param app application specific option arguments |
| 56 | * @return CE_None if successful, CE_Failure if failed |
| 57 | **/ |
| 58 | void VectorOgr::classifySVM(VectorOgr& ogrWriter, app::AppFactory& app){ |
| 59 | //--------------------------- command line options ------------------------------------ |
| 60 | Optionjl<std::string> model_opt("model", "model", "Model filename for trained classifier."); |
| 61 | Optionjl<unsigned int> band_opt("b", "band", "Band index (starting from 0, either use band option or use start to end)"); |
| 62 | // Optionjl<std::string> bandNames_opt("bn", "bandname", "Band name(s) to use. Leave empty to use all bands"); |
| 63 | Optionjl<unsigned int> bstart_opt("sband", "startband", "Start band sequence number"); |
| 64 | Optionjl<unsigned int> bend_opt("eband", "endband", "End band sequence number"); |
| 65 | // Optionjl<double> offset_opt("offset", "offset", "Offset value for each spectral band input features: refl[band]=(DN[band]-offset[band])/scale[band]", 0.0); |
| 66 | // 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); |
| 67 | 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)"); |
| 68 | Optionjl<string> output_opt("o", "output", "Filename of classified vector dataset"); |
| 69 | Optionjl<string> ogrformat_opt("f", "oformat", "Output ogr format","SQLite"); |
| 70 | Optionjl<std::string> option_opt("co", "co", "Creation option for output file. Multiple options can be specified."); |
| 71 | Optionjl<string> copyFields_opt("copy", "copy", "copy these fields from input to output vector dataset"); |
| 72 | Optionjl<short> verbose_opt("v", "verbose", "Verbose level",0,2); |
| 73 | // Optionjl<string> cmformat_opt("cmf","cmf","Format for confusion matrix (ascii or latex)","ascii"); |
| 74 | // Optionjl<std::string> label_opt("label", "label", "Attribute name for reference class label used for validation.","label"); |
| 75 | // Optionjl<string> classname_opt("c", "class", "List of class names."); |
| 76 | // Optionjl<short> classvalue_opt("r", "reclass", "List of class values (use same order as in class opt)."); |
| 77 | |
| 78 | band_opt.setHide(1); |
| 79 | // bandNames_opt.setHide(1); |
| 80 | bstart_opt.setHide(1); |
| 81 | bend_opt.setHide(1); |
| 82 | option_opt.setHide(1); |
| 83 | verbose_opt.setHide(2); |
| 84 | |
| 85 | bool doProcess;//stop process when program was invoked with help option (-h --help) |
| 86 | try{ |
| 87 | doProcess=model_opt.retrieveOption(app); |
| 88 | copyFields_opt.retrieveOption(app); |
| 89 | ogrformat_opt.retrieveOption(app); |
| 90 | option_opt.retrieveOption(app); |
| 91 | priors_opt.retrieveOption(app); |
| 92 | // Advanced options |
| 93 | band_opt.retrieveOption(app); |
| 94 | // bandNames_opt.retrieveOption(app); |
| 95 | bstart_opt.retrieveOption(app); |
| 96 | bend_opt.retrieveOption(app); |
| 97 | // offset_opt.retrieveOption(app); |
| 98 | // scale_opt.retrieveOption(app); |
| 99 | output_opt.retrieveOption(app); |
| 100 | verbose_opt.retrieveOption(app); |
| 101 | // cmformat_opt.retrieveOption(app); |
| 102 | // label_opt.retrieveOption(app); |
| 103 | // classname_opt.retrieveOption(app); |
| 104 | // classvalue_opt.retrieveOption(app); |
| 105 | |
| 106 | if(!doProcess){ |
| 107 | cout << endl; |
| 108 | std::ostringstream helpStream; |
| 109 | helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl; |
| 110 | throw(helpStream.str());//help was invoked, stop processing |
| 111 | } |
| 112 | |
| 113 | if(model_opt.empty()){ |
| 114 | std::ostringstream errorStream; |
| 115 | errorStream << "Error: model is not defined, please use option --model" << std::endl; |
| 116 | throw(errorStream.str()); |
| 117 | } |
| 118 | |
| 119 | if(verbose_opt[0]>=1) |
| 120 | std::cout << "model file: " << model_opt[0] << std::endl; |
| 121 | |
| 122 | char **papszOptions=NULL; |
| 123 | for(std::vector<std::string>::const_iterator optionIt=option_opt.begin();optionIt!=option_opt.end();++optionIt) |
| 124 | papszOptions=CSLAddString(papszOptions,optionIt->c_str()); |
| 125 | |
| 126 | bool initWriter=true; |
| 127 | if(ogrWriter.open(output_opt[0],ogrformat_opt[0])!=OGRERR_NONE) |
| 128 | initWriter=false; |
| 129 | |
| 130 | std::vector<double> offset; |
| 131 | std::vector<double> scale; |
| 132 | map<string,short> classValueMap; |
| 133 | vector<std::string> nameVector; |
| 134 | vector<std::string> bandNames; |
| 135 | |
| 136 | struct svm_model* theModel=svm_load_model(model_opt[0].c_str(),offset,scale,classValueMap,nameVector,bandNames); |
| 137 | |
| 138 | unsigned int nclass=theModel->nr_class; |
| 139 | unsigned int nband=bandNames.size()?bandNames.size():offset.size();//todo: find a more elegant way to define number of bands (in model?) |
| 140 | |
| 141 | if(verbose_opt[0]){ |
| 142 | std::cout << "nclass: " << nclass << std::endl; |
| 143 | std::cout << "nband: " << nband << std::endl; |
| 144 | std::map<std::string,short>::const_iterator mapit=classValueMap.begin(); |
| 145 | std::cout << "classValueMap:" << std::endl; |
| 146 | while(mapit!=classValueMap.end()){ |
| 147 | std::cout << mapit->first << ": " << mapit->second << std::endl; |
| 148 | ++mapit; |
| 149 | } |
| 150 | std::cout << "nameVector:" << std::endl; |
| 151 | for(int index=0;index<nameVector.size();++index) |
| 152 | std::cout << nameVector[index] << std::endl; |
| 153 | std::cout << "bandNames:" << std::endl; |
| 154 | for(int index=0;index<bandNames.size();++index) |
| 155 | std::cout << bandNames[index] << std::endl; |
| 156 | } |
| 157 | |
| 158 | //normalize |
| 159 | vector<double> priors; |
| 160 | if(priors_opt.size()){//priors from argument list |
| 161 | priors.resize(priors_opt.size()); |
| 162 | double normPrior=0; |
| 163 | for(unsigned short iclass=0;iclass<priors_opt.size();++iclass){ |
| 164 | priors[iclass]=priors_opt[iclass]; |
| 165 | normPrior+=priors[iclass]; |
| 166 | } |
| 167 | //normalize |
| 168 | for(unsigned short iclass=0;iclass<priors_opt.size();++iclass) |
| 169 | priors[iclass]/=normPrior; |
| 170 | } |
| 171 | |
| 172 | //convert start and end band options to vector of band indexes |
| 173 | if(bstart_opt.size()){ |
| 174 | if(bend_opt.size()!=bstart_opt.size()){ |
| 175 | string errorstring="Error: options for start and end band indexes must be provided as pairs, missing end band"; |
| 176 | throw(errorstring); |
| 177 | } |
| 178 | band_opt.clear(); |
| 179 | for(int ipair=0;ipair<bstart_opt.size();++ipair){ |
| 180 | if(bend_opt[ipair]<=bstart_opt[ipair]){ |
| 181 | string errorstring="Error: index for end band must be smaller then start band"; |
| 182 | throw(errorstring); |
| 183 | } |
| 184 | for(unsigned int iband=bstart_opt[ipair];iband<=bend_opt[ipair];++iband) |
| 185 | band_opt.push_back(iband); |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | if(band_opt.size()){ |
| 190 | //sort bands |
| 191 | // std::sort(band_opt.begin(),band_opt.end()); |
| 192 | if(nband!=band_opt.size()){ |
| 193 | string errorstring="Error: index for end band must be smaller then start band"; |
| 194 | throw(errorstring); |
| 195 | } |
| 196 | } |
| 197 | else{ |
| 198 | unsigned short iband=0; |
| 199 | while(band_opt.size()<nband) |
| 200 | band_opt.push_back(iband++); |
| 201 | } |
| 202 | |
| 203 | // map<string,short> classValueMap; |
| 204 | // vector<std::string> nameVector; |
| 205 | // if(classname_opt.size()){ |
| 206 | // assert(classname_opt.size()==classvalue_opt.size()); |
| 207 | // for(unsigned int iclass=0;iclass<classname_opt.size();++iclass) |
| 208 | // classValueMap[classname_opt[iclass]]=classvalue_opt[iclass]; |
| 209 | // } |
| 210 | |
| 211 | const char* pszMessage; |
| 212 | void* pProgressArg=NULL; |
| 213 | GDALProgressFunc pfnProgress=GDALTermProgress; |
| 214 | float progress=0; |
| 215 | if(!verbose_opt[0]) |
| 216 | pfnProgress(progress,pszMessage,pProgressArg); |
| 217 | |
| 218 | // cm.clearResults(); |
| 219 | //notice that fields have already been set by readDataImageOgr (taking into account appropriate bands) |
| 220 | // for(int ivalidation=0;ivalidation<vectorCollection.size();++ivalidation){ |
| 221 | int nvalidation=1; |
| 222 | for(int ivalidation=0;ivalidation<nvalidation;++ivalidation){ |
| 223 | if(verbose_opt[0]) |
| 224 | cout << "number of layers in input ogr file: " << getLayerCount() << endl; |
| 225 | for(int ilayer=0;ilayer<getLayerCount();++ilayer){ |
| 226 | if(verbose_opt[0]) |
| 227 | cout << "processing input layer " << ilayer << endl; |
| 228 | if(initWriter){ |
| 229 | if(ogrWriter.pushLayer(getLayerName(ilayer),getProjection(ilayer),getGeometryType(),papszOptions)!=OGRERR_NONE){ |
| 230 | ostringstream fs; |
| 231 | fs << "push layer to ogrWriter with polygons failed "; |
| 232 | fs << "layer name: "<< getLayerName(ilayer) << std::endl; |
| 233 | throw(fs.str()); |
| 234 | } |
| 235 | // ogrWriter.pushLayer(getLayer()->GetName(),getProjection(),getGeometryType(),NULL); |
| 236 | if(copyFields_opt.size()){ |
| 237 | if(verbose_opt[0]) |
| 238 | std::cout << "copy fields" << std::endl; |
| 239 | ogrWriter.copyFields(*this,copyFields_opt,ilayer,ilayer); |
| 240 | } |
| 241 | if(verbose_opt[0]) |
| 242 | std::cout << "creating field class" << std::endl; |
| 243 | if(classValueMap.size()) |
| 244 | ogrWriter.createField("class",OFTInteger,ilayer); |
| 245 | else |
| 246 | ogrWriter.createField("class",OFTString,ilayer); |
| 247 | } |
| 248 | |
| 249 | //make sure to use resize and setFeature instead of pushFeature when in processing in parallel!!! |
| 250 | ogrWriter.resize(getFeatureCount(ilayer),ilayer); |
| 251 | |
| 252 | unsigned int nFeatures=getFeatureCount(ilayer); |
| 253 | progress=0; |
| 254 | pfnProgress(progress,pszMessage,pProgressArg); |
| 255 | #if JIPLIB_PROCESS_IN_PARALLEL == 1 |
| 256 | #pragma omp parallel for |
| 257 | #else |
| 258 | #endif |
| 259 | for(unsigned int ifeature=0;ifeature<getFeatureCount(ilayer);++ifeature){ |
| 260 | OGRFeature *poFeature=cloneFeature(ifeature,ilayer); |
| 261 | if(verbose_opt[0]>1) |
| 262 | std::cout << "feature " << ifeature << std::endl; |
| 263 | if( poFeature == NULL ){ |
| 264 | cout << "Warning: could not read feature " << ifeature << " in layer " << getLayerName(ilayer) << endl; |
| 265 | continue; |
| 266 | } |
| 267 | OGRFeature *poDstFeature = NULL; |
| 268 | poDstFeature=ogrWriter.createFeature(ilayer); |
| 269 | if( poDstFeature->SetFrom( poFeature, TRUE ) != OGRERR_NONE ){ |
| 270 | OGRFeature::DestroyFeature( poFeature ); |
| 271 | OGRFeature::DestroyFeature( poDstFeature ); |
| 272 | std::ostringstream errorStream; |
| 273 | errorStream << "Error: Unable to translate feature " << poFeature->GetFID() << "from layer " << ogrWriter.getLayerName(ilayer).c_str() << std::endl; |
| 274 | throw(errorStream.str()); |
| 275 | } |
| 276 | // poDstFeature->SetGeometry(poFeature->GetGeometryRef()); |
| 277 | std::vector<float> validationFeature; |
| 278 | std::vector<float> probOut(nclass);//posterior prob for each (internal) class |
| 279 | for(int iField=0;iField<m_features[ilayer][ifeature]->GetFieldCount();++iField){ |
| 280 | std::string fieldname=m_features[ilayer][ifeature]->GetFieldDefnRef(iField)->GetNameRef(); |
| 281 | if(bandNames.size()){ |
| 282 | if(find(bandNames.begin(),bandNames.end(),fieldname)!=bandNames.end()){ |
| 283 | double theValue=m_features[ilayer][ifeature]->GetFieldAsDouble(iField); |
| 284 | // validationFeature.push_back((theValue-offset[iband])/scale[iband]); |
| 285 | validationFeature.push_back(theValue); |
| 286 | } |
| 287 | } |
| 288 | else if(fieldname!="fid"){ |
| 289 | double theValue=m_features[ilayer][ifeature]->GetFieldAsDouble(iField); |
| 290 | validationFeature.push_back(theValue); |
| 291 | } |
| 292 | } |
| 293 | vector<double> result(nclass); |
| 294 | struct svm_node *x; |
| 295 | x = (struct svm_node *) malloc((validationFeature.size()+1)*sizeof(struct svm_node)); |
| 296 | for(int iband=0;iband<validationFeature.size();++iband){ |
| 297 | x[iband].index=iband+1; |
| 298 | x[iband].value=(validationFeature[iband]-offset[iband])/scale[iband]; |
| 299 | } |
| 300 | |
| 301 | x[validationFeature.size()].index=-1;//to end svm feature vector |
| 302 | double predict_label=0; |
| 303 | if(theModel->param.probability>0){ |
| 304 | predict_label = svm_predict(theModel,x); |
| 305 | for(short iclass=0;iclass<nclass;++iclass){ |
| 306 | if(iclass==static_cast<short>(predict_label)) |
| 307 | result[iclass]=1; |
| 308 | else |
| 309 | result[iclass]=0; |
| 310 | } |
| 311 | } |
| 312 | else{ |
| 313 | assert(svm_check_probability_model(theModel)); |
| 314 | predict_label = svm_predict_probability(theModel,x,&(result[0])); |
| 315 | } |
| 316 | if(verbose_opt[0]>1){ |
| 317 | std::cout << "predict_label: " << predict_label << std::endl; |
| 318 | for(int iclass=0;iclass<result.size();++iclass) |
| 319 | std::cout << result[iclass] << " "; |
| 320 | std::cout << std::endl; |
| 321 | } |
| 322 | |
| 323 | //calculate posterior prob and calculate max class prob |
| 324 | float max=0;//max probability |
| 325 | std::string classOut="Unclassified"; |
| 326 | for(short iclass=0;iclass<nclass;++iclass){ |
| 327 | if(priors_opt.size()) |
| 328 | probOut[iclass]=priors[iclass]*result[iclass]; |
| 329 | else |
| 330 | probOut[iclass]=result[iclass]; |
| 331 | if(verbose_opt[0]>1) |
| 332 | std::cout << "feature " << ifeature << " probOut " << iclass << ": " << probOut[iclass] << std::endl; |
| 333 | if(probOut[iclass]>max){ |
| 334 | max=probOut[iclass]; |
| 335 | if(classValueMap.size()) |
| 336 | classOut=nameVector[iclass];//classOut=classValueMap[nameVector[iclass]]; |
| 337 | else |
| 338 | classOut=type2string<short>(iclass); |
| 339 | } |
| 340 | } |
| 341 | if(verbose_opt[0]>1) |
| 342 | std::cout << "feature " << ifeature << " classOut " << classOut << std::endl; |
| 343 | |
| 344 | free(x); |
| 345 | |
| 346 | if(classValueMap.size()) |
| 347 | poDstFeature->SetField("class",classValueMap[classOut]); |
| 348 | else |
| 349 | poDstFeature->SetField("class",classOut.c_str()); |
| 350 | //todo: might not be needed due to SetFrom |
| 351 | poDstFeature->SetFID( poFeature->GetFID() ); |
| 352 | // int labelIndex=poFeature->GetFieldIndex(label_opt[0].c_str()); |
| 353 | // if(labelIndex>=0){ |
| 354 | // string classRef=poFeature->GetFieldAsString(labelIndex); |
| 355 | // if(classRef!="0"){ |
| 356 | // if(classValueMap.size()) |
| 357 | // cm.incrementResult(type2string<short>(classValueMap[classRef]),type2string<short>(classValueMap[classOut]),1); |
| 358 | // else |
| 359 | // cm.incrementResult(classRef,classOut,1); |
| 360 | // } |
| 361 | // } |
| 362 | |
| 363 | //make sure to use setFeature instead of pushFeature when in processing in parallel!!! |
| 364 | ogrWriter.setFeature(ifeature,poDstFeature,ilayer); |
| 365 | if(!verbose_opt[0]){ |
| 366 | progress=static_cast<float>(ifeature+1.0)/nFeatures; |
| 367 | pfnProgress(progress,pszMessage,pProgressArg); |
| 368 | } |
| 369 | // OGRFeature::DestroyFeature( poFeature ); |
| 370 | // OGRFeature::DestroyFeature( poDstFeature ); |
| 371 | }//get next feature |
| 372 | }//next layer |
| 373 | } |
| 374 | // if(cm.nReference()){ |
| 375 | // std::cout << cm << std::endl; |
| 376 | // cout << "class #samples userAcc prodAcc" << endl; |
| 377 | // double se95_ua=0; |
| 378 | // double se95_pa=0; |
| 379 | // double se95_oa=0; |
| 380 | // double dua=0; |
| 381 | // double dpa=0; |
| 382 | // double doa=0; |
| 383 | // for(short iclass=0;iclass<cm.nClasses();++iclass){ |
| 384 | // dua=cm.ua_pct(cm.getClass(iclass),&se95_ua); |
| 385 | // dpa=cm.pa_pct(cm.getClass(iclass),&se95_pa); |
| 386 | // cout << cm.getClass(iclass) << " " << cm.nReference(cm.getClass(iclass)) << " " << dua << " (" << se95_ua << ")" << " " << dpa << " (" << se95_pa << ")" << endl; |
| 387 | // } |
| 388 | // std::cout << "Kappa: " << cm.kappa() << std::endl; |
| 389 | // doa=cm.oa(&se95_oa); |
| 390 | // std::cout << "Overall Accuracy: " << 100*doa << " (" << 100*se95_oa << ")" << std::endl; |
| 391 | // } |
| 392 | |
| 393 | svm_free_and_destroy_model(&(theModel)); |
| 394 | } |
| 395 | catch(BadConversion conversionString){ |
| 396 | std::cerr << "Error: did you provide class pairs names (-c) and integer values (-r) for each class in training vector?" << std::endl; |
| 397 | throw; |
| 398 | } |
| 399 | catch(string predefinedString){ |
| 400 | std::cout << predefinedString << std::endl; |
| 401 | throw; |
| 402 | } |
| 403 | } |