1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
|
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef otbNeuralNetworkMachineLearningModel_hxx
#define otbNeuralNetworkMachineLearningModel_hxx
#include <fstream>
#include "otbNeuralNetworkMachineLearningModel.h"
#include "itkMacro.h" // itkExceptionMacro
namespace otb
{
template <class TInputValue, class TOutputValue>
NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::NeuralNetworkMachineLearningModel()
:
m_ANNModel(cv::ml::ANN_MLP::create()),
m_TrainMethod(CvANN_MLP_TrainParams::RPROP),
m_ActivateFunction(CvANN_MLP::SIGMOID_SYM),
m_Alpha(1.),
m_Beta(1.),
m_BackPropDWScale(0.1),
m_BackPropMomentScale(0.1),
m_RegPropDW0(0.1),
m_RegPropDWMin(FLT_EPSILON),
m_TermCriteriaType(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS),
m_MaxIter(1000),
m_Epsilon(0.01)
{
this->m_ConfidenceIndex = true;
this->m_IsRegressionSupported = true;
}
/** Sets the topology of the NN */
template <class TInputValue, class TOutputValue>
void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::SetLayerSizes(const std::vector<unsigned int> layers)
{
const unsigned int nbLayers = layers.size();
if (nbLayers < 3)
itkExceptionMacro(<< "Number of layers in the Neural Network must be >= 3")
m_LayerSizes = layers;
}
/** Converts a ListSample of VariableLengthVector to a CvMat. The user
* is responsible for freeing the output pointer with the
* cvReleaseMat function. A null pointer is resturned in case the
* conversion failed.
*/
template <class TInputValue, class TOutputValue>
void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::LabelsToMat(const TargetListSampleType* labels, cv::Mat& output)
{
unsigned int nbSamples = 0;
if (labels != nullptr)
{
nbSamples = labels->Size();
}
// Check for valid listSample
if (nbSamples > 0)
{
// Build an iterator
typename TargetListSampleType::ConstIterator labelSampleIt = labels->Begin();
TargetValueType classLabel;
for (; labelSampleIt != labels->End(); ++labelSampleIt)
{
// Retrieve labelSample
typename TargetListSampleType::MeasurementVectorType labelSample = labelSampleIt.GetMeasurementVector();
classLabel = labelSample[0];
if (m_MapOfLabels.count(classLabel) == 0)
{
m_MapOfLabels[classLabel] = -1;
}
}
unsigned int nbClasses = m_MapOfLabels.size();
m_MatrixOfLabels = cv::Mat(1,nbClasses, CV_32FC1);
unsigned int itLabel = 0;
for (auto& kv : m_MapOfLabels)
{
classLabel = kv.first;
kv.second = itLabel;
m_MatrixOfLabels.at<float>(0,itLabel) = classLabel;
++itLabel;
}
// Sample index
unsigned int sampleIdx = 0;
labelSampleIt = labels->Begin();
output.create(nbSamples, nbClasses, CV_32FC1);
output.setTo(-m_Beta);
// Fill the cv matrix
for (; labelSampleIt != labels->End(); ++labelSampleIt, ++sampleIdx)
{
// Retrieve labelSample
typename TargetListSampleType::MeasurementVectorType labelSample = labelSampleIt.GetMeasurementVector();
classLabel = labelSample[0];
unsigned int indexLabel = m_MapOfLabels[classLabel];
output.at<float>(sampleIdx, indexLabel) = m_Beta;
}
}
}
template <class TInputValue, class TOutputValue>
void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::CreateNetwork()
{
// Create the neural network
const unsigned int nbLayers = m_LayerSizes.size();
if (nbLayers == 0)
itkExceptionMacro(<< "Number of layers in the Neural Network must be >= 3")
cv::Mat layers = cv::Mat(nbLayers, 1, CV_32SC1);
for (unsigned int i = 0; i < nbLayers; i++)
{
layers.row(i) = m_LayerSizes[i];
}
m_ANNModel->setLayerSizes(layers);
m_ANNModel->setActivationFunction(m_ActivateFunction, m_Alpha, m_Beta);
}
template <class TInputValue, class TOutputValue>
void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::SetupNetworkAndTrain(cv::Mat& labels)
{
// convert listsample to opencv matrix
cv::Mat samples;
otb::ListSampleToMat<InputListSampleType>(this->GetInputListSample(), samples);
this->CreateNetwork();
int flags = (this->m_RegressionMode ? 0 : cv::ml::ANN_MLP::NO_OUTPUT_SCALE);
m_ANNModel->setTrainMethod(m_TrainMethod);
m_ANNModel->setBackpropMomentumScale(m_BackPropMomentScale);
m_ANNModel->setBackpropWeightScale(m_BackPropDWScale);
m_ANNModel->setRpropDW0(m_RegPropDW0);
// m_ANNModel->setRpropDWMax( );
m_ANNModel->setRpropDWMin(m_RegPropDWMin);
// m_ANNModel->setRpropDWMinus( );
// m_ANNModel->setRpropDWPlus( );
m_ANNModel->setTermCriteria(cv::TermCriteria(m_TermCriteriaType, m_MaxIter, m_Epsilon));
m_ANNModel->train(cv::ml::TrainData::create(samples, cv::ml::ROW_SAMPLE, labels), flags);
}
/** Train the machine learning model for classification*/
template <class TInputValue, class TOutputValue>
void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::Train()
{
// Transform the targets into a matrix of labels
cv::Mat matOutputANN;
if (this->m_RegressionMode)
{
// MODE REGRESSION
otb::ListSampleToMat<TargetListSampleType>(this->GetTargetListSample(), matOutputANN);
}
else
{
// MODE CLASSIFICATION : store the map between internal labels and output labels
LabelsToMat(this->GetTargetListSample(), matOutputANN);
}
this->SetupNetworkAndTrain(matOutputANN);
}
template <class TInputValue, class TOutputValue>
typename NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::TargetSampleType
NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::DoPredict(const InputSampleType& input, ConfidenceValueType* quality,
ProbaSampleType* proba) const
{
TargetSampleType target;
// convert listsample to Mat
cv::Mat sample;
otb::SampleToMat<InputSampleType>(input, sample);
cv::Mat response; //(1, 1, CV_32FC1);
m_ANNModel->predict(sample, response);
float currentResponse = 0;
float maxResponse = response.at<float>(0, 0);
if (this->m_RegressionMode)
{
// MODE REGRESSION : only output first response
target[0] = maxResponse;
return target;
}
// MODE CLASSIFICATION : find the highest response
float secondResponse = -1e10;
target[0] = m_MatrixOfLabels.at<TOutputValue>(0);
unsigned int nbClasses = m_MatrixOfLabels.size[1];
for (unsigned itLabel = 1; itLabel < nbClasses; ++itLabel)
{
currentResponse = response.at<float>(0, itLabel);
if (currentResponse > maxResponse)
{
secondResponse = maxResponse;
maxResponse = currentResponse;
target[0] = m_MatrixOfLabels.at<TOutputValue>(itLabel);
}
else
{
if (currentResponse > secondResponse)
{
secondResponse = currentResponse;
}
}
}
if (quality != nullptr)
{
(*quality) = static_cast<ConfidenceValueType>(maxResponse) - static_cast<ConfidenceValueType>(secondResponse);
}
if (proba != nullptr && !this->m_ProbaIndex)
itkExceptionMacro("Probability per class not available for this classifier !");
return target;
}
template <class TInputValue, class TOutputValue>
void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::Save(const std::string& filename, const std::string& name)
{
cv::FileStorage fs(filename, cv::FileStorage::WRITE);
fs << (name.empty() ? m_ANNModel->getDefaultName() : cv::String(name)) << "{";
m_ANNModel->write(fs);
if (!m_MatrixOfLabels.empty())
{
fs << "class_labels" << m_MatrixOfLabels;
}
fs << "}";
fs.release();
}
template <class TInputValue, class TOutputValue>
void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::Load(const std::string& filename, const std::string& name)
{
cv::FileStorage fs(filename, cv::FileStorage::READ);
cv::FileNode model_node(name.empty() ? fs.getFirstTopLevelNode() : fs[name]);
m_ANNModel->read(model_node);
model_node["class_labels"] >> m_MatrixOfLabels;
fs.release();
}
template <class TInputValue, class TOutputValue>
bool NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::CanReadFile(const std::string& file)
{
std::ifstream ifs;
ifs.open(file);
if (!ifs)
{
std::cerr << "Could not read file " << file << std::endl;
return false;
}
while (!ifs.eof())
{
std::string line;
std::getline(ifs, line);
if (line.find(CV_TYPE_NAME_ML_ANN_MLP) != std::string::npos || line.find(m_ANNModel->getDefaultName()) != std::string::npos)
{
return true;
}
}
ifs.close();
return false;
}
template <class TInputValue, class TOutputValue>
bool NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::CanWriteFile(const std::string& itkNotUsed(file))
{
return false;
}
template <class TInputValue, class TOutputValue>
void NeuralNetworkMachineLearningModel<TInputValue, TOutputValue>::PrintSelf(std::ostream& os, itk::Indent indent) const
{
// Call superclass implementation
Superclass::PrintSelf(os, indent);
}
} // end namespace otb
#endif
|