Direct Graphical Models  v.1.7.0
TrainEdge.cpp
1 #include "TrainEdge.h"
2 
3 #include "TrainEdgePotts.h"
4 #include "TrainEdgePottsCS.h"
5 #include "TrainEdgePrior.h"
6 #include "TrainEdgeConcat.h"
7 
8 #include "TrainNodeNaiveBayes.h"
9 #include "FeaturesConcatenator.h"
10 
11 #include "macroses.h"
12 
13 namespace DirectGraphicalModels
14 {
15  // Factory method
16  std::shared_ptr<CTrainEdge> CTrainEdge::create(byte edgeRandomModel, byte nStates, word nFeatures)
17  {
18  switch (edgeRandomModel)
19  {
20  case EdgeRandomModel::Potts: return std::make_shared<CTrainEdgePotts>(nStates, nFeatures);
21  case EdgeRandomModel::PottsCS: return std::make_shared<CTrainEdgePottsCS>(nStates, nFeatures);
22  case EdgeRandomModel::Prior: return std::make_shared<CTrainEdgePrior>(nStates, nFeatures);
23  case EdgeRandomModel::Concat: return std::make_shared<CTrainEdgeConcat<CTrainNodeBayes, CDiffFeaturesConcatenator>>(nStates, nFeatures);
24  default:
25  DGM_ASSERT_MSG(false, "Unknown type of the edge random model");
26  }
27  }
28 
29  Mat CTrainEdge::getEdgePotentials(const Mat &featureVector1, const Mat &featureVector2, const vec_float_t &vParams, float weight) const
30  {
31  Mat res = calculateEdgePotentials(featureVector1, featureVector2, vParams);
32  if (weight != 1.0f) pow(res, weight, res);
33 
34  // Normalization
35  for (byte y = 0; y < m_nStates; y++) {
36  float *pRes = res.ptr<float>(y);
37  float Sum = 0;
38  for (byte x = 0; x < m_nStates; x++) Sum += pRes[x];
39  if (Sum == 0) continue;
40  for (byte x = 0; x < m_nStates; x++) pRes[x] *= 100 / Sum;
41  } // y
42 
43  return res;
44  }
45 
46  // returns the matrix filled with ones, except the diagonal values wich are set to <values>
47  Mat CTrainEdge::getDefaultEdgePotentials(const vec_float_t &values)
48  {
49  size_t nStates = values.size();
50  Mat res(static_cast<int>(nStates), static_cast<int>(nStates), CV_32FC1, Scalar(1.0f));
51  for (byte s = 0; s < nStates; s++) res.at<float>(s, s) = values[s];
52  return res;
53  }
54 }
Mat getEdgePotentials(const Mat &featureVector1, const Mat &featureVector2, const vec_float_t &vParams, float weight=1.0f) const
Returns the edge potential, based on the feature vectors.
Definition: TrainEdge.cpp:29
virtual Mat calculateEdgePotentials(const Mat &featureVector1, const Mat &featureVector2, const vec_float_t &vParams) const =0
Calculates the edge potential, based on the feature vectors.
static std::shared_ptr< CTrainEdge > create(byte edgeRandomModel, byte nStates, word nFeatures)
Factory method returning edge trainer object.
Definition: TrainEdge.cpp:16
static Mat getDefaultEdgePotentials(float val, byte nStates)
Returns the data-independent edge potentials.
Definition: TrainEdge.h:74
byte m_nStates
The number of states (classes)