/********************************************************************** jlann_lib.cc: classify raster image using Artificial Neural Network Author(s): Pieter.Kempeneers@ec.europa.eu Copyright (C) 2016-2020 European Union (Joint Research Centre) This file is part of jiplib. jiplib is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jiplib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with jiplib. If not, see . ***********************************************************************/ #include #include #include #include #include "Jim.h" #include "VectorOgr.h" // #include "ImgReaderOgr.h" // #include "ImgWriterOgr.h" #include "base/Optionjl.h" #include "base/PosValue.h" #include "algorithms/ConfusionMatrix.h" #include "floatfann.h" #include "algorithms/myfann_cpp.h" using namespace std; using namespace app; std::string VectorOgr::trainANN(app::AppFactory& app){ confusionmatrix::ConfusionMatrix cm; //--------------------------- command line options ------------------------------------ // Optionjl model_opt("model", "model", "Model filename to save trained classifier."); // Optionjl tlayer_opt("tln", "tln", "Sample layer name(s)"); // Optionjl attribute_opt("af", "af", "Attribute filter"); Optionjl label_opt("label", "label", "Attribute name for class label in training vector file.","label"); Optionjl balance_opt("bal", "balance", "Balance the input data to this number of samples for each class", 0); Optionjl random_opt("random", "random", "Randomize training data for balancing", true, 2); Optionjl 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); // Optionjl band_opt("b", "band", "Band index (starting from 0, either use band option or use start to end)"); // Optionjl bstart_opt("sband", "startband", "Start band sequence number"); // Optionjl bend_opt("eband", "endband", "End band sequence number"); Optionjl bandNames_opt("bn", "bandname", "Band name(s) to use. Leave empty to use all bands"); Optionjl offset_opt("offset", "offset", "Offset value for each spectral band input features: refl[band]=(DN[band]-offset[band])/scale[band]", 0.0); Optionjl 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); Optionjl cv_opt("cv", "cv", "N-fold cross validation mode",0); Optionjl cmformat_opt("cmf","cmf","Format for confusion matrix (ascii or latex)","ascii"); Optionjl nneuron_opt("nn", "nneuron", "number of neurons in hidden layers in neural network (multiple hidden layers are set by defining multiple number of neurons: -n 15 -n 1, default is one hidden layer with 5 neurons)", 5); Optionjl connection_opt("\0", "connection", "connection rate (default: 1.0 for a fully connected network)", 1.0); Optionjl learning_opt("l", "learning", "learning rate (default: 0.7)", 0.7); Optionjl weights_opt("w", "weights", "weights for neural network. Apply to fully connected network only, starting from first input neuron to last output neuron, including the bias neurons (last neuron in each but last layer)", 0.0); Optionjl maxit_opt("\0", "maxit", "number of maximum iterations (epoch) (default: 500)", 500); Optionjl classname_opt("c", "class", "List of class names."); Optionjl classvalue_opt("r", "reclass", "List of class values (use same order as in class opt)."); Optionjl verbose_opt("v", "verbose", "Verbose level",0,2); random_opt.setHide(1); minSize_opt.setHide(1); // band_opt.setHide(1); // bstart_opt.setHide(1); // bend_opt.setHide(1); connection_opt.setHide(1); learning_opt.setHide(1); weights_opt.setHide(1); maxit_opt.setHide(1); verbose_opt.setHide(2); bool doProcess;//stop process when program was invoked with help option (-h --help) try{ // doProcess=model_opt.retrieveOption(app); doProcess=label_opt.retrieveOption(app); // tlayer_opt.retrieveOption(app); // attribute_opt.retrieveOption(app); balance_opt.retrieveOption(app); random_opt.retrieveOption(app); minSize_opt.retrieveOption(app); // band_opt.retrieveOption(app); // bstart_opt.retrieveOption(app); // bend_opt.retrieveOption(app); bandNames_opt.retrieveOption(app); offset_opt.retrieveOption(app); scale_opt.retrieveOption(app); cv_opt.retrieveOption(app); cmformat_opt.retrieveOption(app); nneuron_opt.retrieveOption(app); connection_opt.retrieveOption(app); learning_opt.retrieveOption(app); weights_opt.retrieveOption(app); maxit_opt.retrieveOption(app); classname_opt.retrieveOption(app); classvalue_opt.retrieveOption(app); verbose_opt.retrieveOption(app); // memory_opt.retrieveOption(app); if(!doProcess){ cout << endl; std::ostringstream helpStream; helpStream << "short option -h shows basic options only, use long option --help to show all options" << std::endl; throw(helpStream.str());//help was invoked, stop processing } FANN::neural_net net;//the neural network // if(model_opt.empty()){ // std::string errorString="Error: filename to save model is empty"; // throw(errorString); // } unsigned int nclass=0; unsigned int nband=0; map > trainingMap; vector< Vector2d > trainingPixels;//[class][sample][band] map classValueMap; vector nameVector; if(classname_opt.size()){ assert(classname_opt.size()==classvalue_opt.size()); for(unsigned int iclass=0;iclass >::iterator mapit=trainingMap.begin(); while(mapit!=trainingMap.end()){ //delete small classes if((mapit->second).size()second); if(verbose_opt[0]>1) std::cout << mapit->first << ": " << (mapit->second).size() << " samples" << std::endl; ++mapit; } nclass=trainingPixels.size(); if(classname_opt.size()) assert(nclass==classname_opt.size()); nband=trainingPixels[0][0].size(); //balance training data if(balance_opt[0]>0){ while(balance_opt.size()balance_opt[iclass]){ while(trainingPixels[iclass].size()>balance_opt[iclass]){ int index=rand()%trainingPixels[iclass].size(); trainingPixels[iclass].erase(trainingPixels[iclass].begin()+index); } } else{ int oldsize=trainingPixels[iclass].size(); for(int isample=trainingPixels[iclass].size();isample offset; vector scale; //set scale and offset offset.resize(nband); scale.resize(nband); for(int iband=0;ibandtrainingPixels[iclass][isample][iband]) theMin=trainingPixels[iclass][isample][iband]; if(theMax >::iterator mapit=trainingMap.begin(); mapit=trainingMap.begin(); bool doSort=true; while(mapit!=trainingMap.end()){ nameVector.push_back(mapit->first); if(classValueMap.size()){ //check if name in training is covered by classname_opt (values can not be 0) if(classValueMap[mapit->first]>0){ if(cm.getClassIndex(type2string(classValueMap[mapit->first]))<0){ cm.pushBackClassName(type2string(classValueMap[mapit->first]),doSort); } } else{ std::string errorString="Error: names in classname option are not complete, please check names in training vector and make sure classvalue is > 0"; throw(errorString); } } else cm.pushBackClassName(mapit->first,doSort); ++mapit; } if(classname_opt.empty()){ //std::cerr << "Warning: no class name and value pair provided for all " << nclass << " classes, using string2type instead!" << std::endl; for(int iclass=0;iclass " << string2type(cm.getClass(iclass)) << std::endl; classValueMap[cm.getClass(iclass)]=string2type(cm.getClass(iclass)); } } //Calculate features of training set vector< Vector2d > trainingFeatures(nclass); for(short iclass=0;iclass=1) std::cout << "calculating features for class " << iclass << std::endl; if(random_opt[0]) srand(time(NULL)); nctraining=trainingPixels[iclass].size(); if(nctraining<=0) nctraining=1; assert(nctraining<=trainingPixels[iclass].size()); if(verbose_opt[0]>1) std::cout << "nctraining (class " << iclass << "): " << nctraining << std::endl; trainingFeatures[iclass].resize(nctraining); for(int isample=0;isample=1){ std::cout << "number of features: " << nFeatures << std::endl; std::cout << "creating artificial neural network with " << nneuron_opt.size() << " hidden layer, having " << std::endl; for(unsigned int ilayer=0;ilayer