KSquare Utilities
KKMLL::ModelKnn Class Reference

#include <ModelKnn.h>

+ Inheritance diagram for KKMLL::ModelKnn:

Public Types

typedef ModelKnnModelKnnPtr
 
- Public Types inherited from KKMLL::Model
typedef ModelModelPtr
 
enum  ModelTypes : int {
  ModelTypes::Null = 0, ModelTypes::OldSVM = 1, ModelTypes::SvmBase = 2, ModelTypes::KNN = 3,
  ModelTypes::UsfCasCor = 4, ModelTypes::Dual = 5
}
 

Public Member Functions

 ModelKnn ()
 
 ModelKnn (FactoryFVProducerPtr _factoryFVProducer)
 
 ModelKnn (const KKStr &_name, const ModelParamKnn &_param, FactoryFVProducerPtr _factoryFVProducer)
 
 ModelKnn (const ModelKnn &_madel)
 
virtual ~ModelKnn ()
 
virtual ModelKnnPtr Duplicate () const
 
virtual ModelTypes ModelType () const
 
ModelParamKnnPtr Param ()
 
virtual MLClassPtr Predict (FeatureVectorPtr example, RunLog &log)
 
virtual void Predict (FeatureVectorPtr example, MLClassPtr knownClass, MLClassPtr &predClass1, MLClassPtr &predClass2, kkint32 &predClass1Votes, kkint32 &predClass2Votes, double &probOfKnownClass, double &predClass1Prob, double &predClass2Prob, kkint32 &numOfWinners, bool &knownClassOneOfTheWinners, double &breakTie, RunLog &log)
 
virtual ClassProbListPtr ProbabilitiesByClass (FeatureVectorPtr example, RunLog &log)
 
virtual void ProbabilitiesByClass (FeatureVectorPtr example, const MLClassList &_mlClasses, kkint32 *_votes, double *_probabilities, RunLog &log)
 
virtual void ProbabilitiesByClass (FeatureVectorPtr _example, const MLClassList &_mlClasses, double *_probabilities, RunLog &_log)
 Derives predicted probabilities by class. More...
 
void ReadXML (XmlStream &s, XmlTagConstPtr tag, VolConstBool &cancelFlag, RunLog &log)
 To be implemented by derived classes; the parent classes fields will be updated by the derived class calling ReadXMLModelToken. More...
 
virtual void TrainModel (FeatureVectorListPtr _trainExamples, bool _alreadyNormalized, bool _takeOwnership, VolConstBool &_cancelFlag, RunLog &_log)
 Performs operations such as FeatureEncoding, and Normalization. The actual training of models occurs in the specific derived implementation of 'Model'. More...
 
void WriteXML (const KKStr &varName, ostream &o) const
 
- Public Member Functions inherited from KKMLL::Model
 Model ()
 
 Model (FactoryFVProducerPtr _factoryFVProducer)
 Use this when you are planning on creating a empty model without parameters. More...
 
 Model (const KKStr &_name, const ModelParam &_param, FactoryFVProducerPtr _factoryFVProducer)
 Construct a instance of 'Model' using the parameters specified in '_param'. More...
 
 Model (const Model &_madel)
 Copy Constructor. More...
 
virtual ~Model ()
 Frees any memory allocated by, and owned by the Model. More...
 
bool AlreadyNormalized () const
 
virtual KKStr Description () const
 
const FeatureEncoder2Encoder () const
 
FactoryFVProducerPtr FactoryFVProducer () const
 
virtual FeatureNumListConstPtr GetFeatureNums () const
 
virtual kkint32 MemoryConsumedEstimated () const
 
MLClassListPtr MLClasses () const
 
MLClassListPtr MLClassesNewInstance () const
 
virtual KKStr ModelTypeStr () const
 
const KKStrName () const
 
void Name (const KKStr &_name)
 
virtual bool NormalizeNominalAttributes () const
 
ModelParamPtr Param () const
 
virtual void PredictRaw (FeatureVectorPtr example, MLClassPtr &predClass, double &dist)
 
virtual FeatureVectorPtr PrepExampleForPrediction (FeatureVectorPtr fv, bool &newExampleCreated)
 Every prediction method in every class that is inherited from this class should call this method before performing there prediction. Such things as Normalization and Feature Encoding. More...
 
virtual void ProbabilitiesByClassDual (FeatureVectorPtr example, KKStr &classifier1Desc, KKStr &classifier2Desc, ClassProbListPtr &classifier1Results, ClassProbListPtr &classifier2Results, RunLog &log)
 Only applied to ModelDual classifier. More...
 
virtual void RetrieveCrossProbTable (MLClassList &classes, double **crossProbTable, RunLog &log)
 
const KKStrRootFileName () const
 
void RootFileName (const KKStr &_rootFileName)
 
virtual FeatureNumListConstPtr SelectedFeatures () const
 
const KKB::DateTimeTimeSaved () const
 
double TrainingTime () const
 
void TrainingTimeEnd ()
 Derived classes call this method to stop the clock for 'trainingTime'. More...
 
void TrainingTimeStart ()
 Derived classes call this method to start the clock for 'trainingTime'. More...
 
double TrianingPrepTime () const
 
bool ValidModel () const
 
void WriteModelXMLFields (std::ostream &o) const
 The "WriteXML" method in Derived classes call this method to include the parents classes fields in the XML data. More...
 
virtual void WriteXML (const KKStr &varName, std::ostream &o) const =0
 

Additional Inherited Members

- Static Public Member Functions inherited from KKMLL::Model
static ModelPtr CreateAModel (ModelTypes _modelType, const KKStr &_name, const ModelParam &_param, FactoryFVProducerPtr _factoryFVProducer, VolConstBool &_cancelFlag, RunLog &_log)
 A factory method that will instantiate the appropriate class of training model based off '_modelType'. More...
 
static ModelTypes ModelTypeFromStr (const KKStr &_modelingTypeStr)
 
static KKStr ModelTypeToStr (ModelTypes _modelingType)
 
- Protected Member Functions inherited from KKMLL::Model
void AddErrorMsg (const KKStr &errMsg, kkint32 lineNum)
 
void AllocatePredictionVariables ()
 
void DeAllocateSpace ()
 
void NormalizeProbabilitiesWithAMinumum (kkint32 numClasses, double *probabilities, double minProbability)
 
void ReadXMLModelPost (RunLog &log)
 
XmlTokenPtr ReadXMLModelToken (XmlTokenPtr t, RunLog &log)
 Will process any tokens that belong to 'ModelParam' and return NULL ones that are not will be passed back. More...
 
void ReduceTrainExamples (RunLog &log)
 Reduces the Training Images down to the size dictated by the 'examplesPerClass' parameter. More...
 
- Protected Attributes inherited from KKMLL::Model
bool alreadyNormalized
 
MLClassListPtr classes
 
MLClassIndexListPtr classesIndex
 
double * classProbs
 
double ** crossClassProbTable
 
kkint32 crossClassProbTableSize
 
FeatureEncoder2Ptr encoder
 
VectorKKStr errors
 
FactoryFVProducerPtr factoryFVProducer
 
FileDescPtr fileDesc
 
NormalizationParmsPtr normParms
 
kkint32 numOfClasses
 
ModelParamPtr param
 
KKStr rootFileName
 
FeatureVectorListPtr trainExamples
 
bool validModel
 
kkint32votes
 
bool weOwnTrainExamples
 

Detailed Description

Definition at line 10 of file ModelKnn.h.

Member Typedef Documentation

Definition at line 13 of file ModelKnn.h.

Constructor & Destructor Documentation

ModelKnn::ModelKnn ( )

Definition at line 35 of file ModelKnn.cpp.

References KKMLL::Model::Model().

35  :
36  Model (),
37  param (NULL)
38 {
39 }
ModelKnn::ModelKnn ( FactoryFVProducerPtr  _factoryFVProducer)

Definition at line 43 of file ModelKnn.cpp.

References KKMLL::Model::Model().

43  :
44  Model (_factoryFVProducer),
45  param (NULL)
46 {
47 }
ModelKnn::ModelKnn ( const KKStr _name,
const ModelParamKnn _param,
FactoryFVProducerPtr  _factoryFVProducer 
)

Definition at line 52 of file ModelKnn.cpp.

References KKMLL::Model::Model(), and KKMLL::Model::param.

Referenced by KKMLL::Model::CreateAModel().

55  :
56  Model (_name, _param, _factoryFVProducer),
57  param (NULL)
58 {
59  param = dynamic_cast<ModelParamKnnPtr> (Model::param);
60 }
ModelParamPtr param
Definition: Model.h:412
ModelKnn::ModelKnn ( const ModelKnn _madel)

Definition at line 65 of file ModelKnn.cpp.

References KKMLL::Model::Model(), and KKMLL::Model::param.

Referenced by Duplicate().

65  :
66  Model (_model),
67  param (NULL)
68 {
69  param = dynamic_cast<ModelParamKnnPtr> (Model::param);
70 }
ModelParamPtr param
Definition: Model.h:412
ModelKnn::~ModelKnn ( )
virtual

Definition at line 74 of file ModelKnn.cpp.

75 {
76 
77 }

Member Function Documentation

ModelKnnPtr ModelKnn::Duplicate ( ) const
virtual

Implements KKMLL::Model.

Definition at line 82 of file ModelKnn.cpp.

References ModelKnn().

83 {
84  return new ModelKnn (*this);
85 }
virtual ModelTypes KKMLL::ModelKnn::ModelType ( ) const
inlinevirtual

Implements KKMLL::Model.

Definition at line 32 of file ModelKnn.h.

References KKMLL::Model::KNN.

ModelParamKnnPtr ModelKnn::Param ( )

Definition at line 88 of file ModelKnn.cpp.

89 {
90  return param;
91 }
MLClassPtr ModelKnn::Predict ( FeatureVectorPtr  example,
RunLog log 
)
virtual

Implements KKMLL::Model.

Definition at line 94 of file ModelKnn.cpp.

97 {
98  return NULL;
99 }
void ModelKnn::Predict ( FeatureVectorPtr  example,
MLClassPtr  knownClass,
MLClassPtr predClass1,
MLClassPtr predClass2,
kkint32 predClass1Votes,
kkint32 predClass2Votes,
double &  probOfKnownClass,
double &  predClass1Prob,
double &  predClass2Prob,
kkint32 numOfWinners,
bool &  knownClassOneOfTheWinners,
double &  breakTie,
RunLog log 
)
virtual

Implements KKMLL::Model.

Definition at line 103 of file ModelKnn.cpp.

117 {
118 } /* Predict */
ClassProbListPtr ModelKnn::ProbabilitiesByClass ( FeatureVectorPtr  example,
RunLog log 
)
virtual

Implements KKMLL::Model.

Definition at line 123 of file ModelKnn.cpp.

References KKMLL::Model::classesIndex, KKMLL::ClassProb::ClassProb(), KKMLL::ClassProbList::ClassProbList(), KKB::KKStr::Concat(), KKMLL::MLClassIndexList::GetMLClass(), KKB::KKException::KKException(), KKMLL::Model::numOfClasses, KKMLL::Model::PrepExampleForPrediction(), and KKMLL::ClassProbList::PushOnBack().

126 {
127  if (!classesIndex)
128  {
129  KKStr errMsg = "ModelKnn::ProbabilitiesByClass ***ERROR*** (classLabelAssigments == NULL)";
130  log.Level (-1) << endl << endl << errMsg << endl << endl;
131  throw KKException (errMsg);
132  }
133 
134  bool newExampleCreated = false;
135  FeatureVectorPtr encodedExample = PrepExampleForPrediction (example, newExampleCreated);
136 
137  // double y = SVM289::svm_predict_probability (svmModel, *encodedExample, classProbs, votes);
138 
139  if (newExampleCreated)
140  {
141  delete encodedExample;
142  encodedExample = NULL;
143  }
144 
145  ClassProbListPtr results = new ClassProbList ();
146  kkint32 idx;
147  for (idx = 0; idx < numOfClasses; idx++)
148  {
149  MLClassPtr ic = classesIndex->GetMLClass (idx);
150  results->PushOnBack (new ClassProb (ic, 0.0, 0.0f));
151  }
152 
153  return results;
154 } /* ProbabilitiesByClass */
HTMLReport &__cdecl endl(HTMLReport &htmlReport)
Definition: HTMLReport.cpp:240
__int32 kkint32
Definition: KKBaseTypes.h:88
virtual void PushOnBack(ClassProbPtr cp)
Definition: ClassProb.cpp:212
Represents a "Class" in the Machine Learning Sense.
Definition: MLClass.h:52
RunLog & Level(kkint32 _level)
Definition: RunLog.cpp:220
kkint32 numOfClasses
Definition: Model.h:410
MLClassPtr GetMLClass(kkint16 classIndex)
Locates the MLClass that was assigned classIndex.
Definition: MLClass.cpp:1636
virtual FeatureVectorPtr PrepExampleForPrediction(FeatureVectorPtr fv, bool &newExampleCreated)
Every prediction method in every class that is inherited from this class should call this method befo...
Definition: Model.cpp:574
Used to record probability for a specified class; and a list of classes.
Definition: ClassProb.h:25
Represents a Feature Vector of a single example, labeled or unlabeled.
Definition: FeatureVector.h:59
MLClassIndexListPtr classesIndex
Definition: Model.h:392
void ModelKnn::ProbabilitiesByClass ( FeatureVectorPtr  example,
const MLClassList _mlClasses,
kkint32 _votes,
double *  _probabilities,
RunLog log 
)
virtual

Implements KKMLL::Model.

Definition at line 159 of file ModelKnn.cpp.

165 {
166 }
void ModelKnn::ProbabilitiesByClass ( FeatureVectorPtr  _example,
const MLClassList _mlClasses,
double *  _probabilities,
RunLog _log 
)
virtual

Derives predicted probabilities by class.

Will get the probabilities assigned to each class by the classifier. The '_mlClasses' parameter dictates the order of the classes. That is the probabilities for any given index in '_probabilities' will be for the class specified in the same index in '_mlClasses'.

Parameters
[in]_exampleFeatureVector object to calculate predicted probabilities for.
[in]_mlClassesList image classes that caller is aware of. This should be the same list that was used when constructing this Model object. The list must be the same but not necessarily in the same order as when Model was 1st constructed.
[out]_probabilitiesAn array that must be as big as the number of classes as in mlClasses. The probability of class in mlClasses[x] will be returned in probabilities[x].

Implements KKMLL::Model.

Definition at line 169 of file ModelKnn.cpp.

174 {
175 } /* ProbabilitiesByClass */
void ModelKnn::ReadXML ( XmlStream s,
XmlTagConstPtr  tag,
VolConstBool cancelFlag,
RunLog log 
)
virtual

To be implemented by derived classes; the parent classes fields will be updated by the derived class calling ReadXMLModelToken.

Implements KKMLL::Model.

Definition at line 225 of file ModelKnn.cpp.

References KKMLL::Model::AddErrorMsg(), KKB::KKStr::Concat(), KKB::XmlStream::GetNextToken(), KKB::KKStr::KKStr(), KKMLL::ModelParam::ModelParamTypeStr(), KKMLL::Model::param, KKMLL::Model::ReadXMLModelPost(), KKMLL::Model::ReadXMLModelToken(), and KKB::XmlToken::VarName().

230 {
231  XmlTokenPtr t = s.GetNextToken (cancelFlag, log);
232  while (t && (!cancelFlag))
233  {
234  t = ReadXMLModelToken (t, log);
235  if (t)
236  {
237  const KKStr& varName = t->VarName ();
238 
239  if ((varName.EqualIgnoreCase ("Param")) && (typeid (*t) == typeid (XmlElementModelParamKnn)))
240  {
241  delete param;
242  param = dynamic_cast<XmlElementModelParamKnnPtr> (t)->TakeOwnership ();
243  }
244  else
245  {
246  KKStr errMsg (256);
247  errMsg << "Invalid XmlElement Encountered: Section: " << t->SectionName () << " VarName: " << varName;
248  log.Level (-1) << endl << errMsg << endl << endl;
249  AddErrorMsg (errMsg, 0);
250  }
251  }
252  delete t;
253  t = s.GetNextToken (cancelFlag, log);
254  }
255 
256  delete t;
257  t = NULL;
258 
259  if (!param)
260  param = dynamic_cast<ModelParamKnnPtr> (Model::param);
261 
262  if (Model::param == NULL)
263  {
264  KKStr errMsg (128);
265  errMsg << "ModelKnn::ReadXML ***ERROR*** Base class 'Model' does not have 'param' defined.";
266  AddErrorMsg (errMsg, 0);
267  log.Level (-1) << endl << errMsg << endl << endl;
268  }
269 
270  else if (typeid (*Model::param) != typeid(ModelParamKnn))
271  {
272  KKStr errMsg (128);
273  errMsg << "ModelKnn::ReadXML ***ERROR*** Base class 'Model' param parameter is of the wrong type; found: " << Model::param->ModelParamTypeStr ();
274  AddErrorMsg (errMsg, 0);
275  log.Level (-1) << endl << errMsg << endl << endl;
276  }
277 
278  else
279  {
280  param = dynamic_cast<ModelParamKnnPtr> (Model::param);
281  }
282 
283  ReadXMLModelPost (log);
284 } /* ReadXML */
HTMLReport &__cdecl endl(HTMLReport &htmlReport)
Definition: HTMLReport.cpp:240
ModelParam derived classes will implement their "XmlElement" helper class via this template...
Definition: ModelParam.h:260
XmlTokenPtr ReadXMLModelToken(XmlTokenPtr t, RunLog &log)
Will process any tokens that belong to &#39;ModelParam&#39; and return NULL ones that are not will be passed ...
Definition: Model.cpp:884
ModelParamPtr param
Definition: Model.h:412
void AddErrorMsg(const KKStr &errMsg, kkint32 lineNum)
Definition: Model.cpp:239
bool EqualIgnoreCase(const KKStr &s2) const
Definition: KKStr.cpp:1250
virtual const KKStr & SectionName() const
Definition: XmlStream.h:265
RunLog & Level(kkint32 _level)
Definition: RunLog.cpp:220
XmlElementModelParamTemplate< ModelParamKnn > XmlElementModelParamKnn
Definition: ModelParamKnn.h:68
void ReadXMLModelPost(RunLog &log)
Definition: Model.cpp:987
virtual KKStr ModelParamTypeStr() const
Definition: ModelParam.h:108
virtual XmlTokenPtr GetNextToken(VolConstBool &cancelFlag, RunLog &log)
Definition: XmlStream.cpp:116
virtual const KKStr & VarName() const
Definition: XmlStream.h:269
void ModelKnn::TrainModel ( FeatureVectorListPtr  _trainExamples,
bool  _alreadyNormalized,
bool  _takeOwnership,
VolConstBool _cancelFlag,
RunLog _log 
)
virtual

Performs operations such as FeatureEncoding, and Normalization. The actual training of models occurs in the specific derived implementation of 'Model'.

Performs operations such as FeatureEncoding, and Normalization; the actual training of models occurs in the specific implementation of 'Model'.

Parameters
[in]_trainExamplesTraining data that classifier will be built from. If the examples need to be normalized or encoded and we are not taking ownership then a duplicate list of examples will be created that this method and class will be free to modify.
[in]_alreadyNormalizedIndicates if contents of '_trainExamples' are normalized already; if not they will be normalized.
[in]_takeOwnershipThis instance of Model will take ownership of '_examples' and is free to modify its contents.
Parameters
_takeOwnershipModel will take ownership of these examples

Reimplemented from KKMLL::Model.

Definition at line 180 of file ModelKnn.cpp.

References KKMLL::Model::TrainModel(), and KKMLL::Model::validModel.

186 {
187  _log.Level (20) << "ModelKnn::TrainModel alreadyNormalized[" << _alreadyNormalized << "] _takeOwnership[" << _takeOwnership << "]." << endl;
188 
189  try
190  {
191  Model::TrainModel (_trainExamples, _alreadyNormalized, _takeOwnership, _cancelFlag, _log);
192  }
193  catch (const KKException& e)
194  {
195  validModel = false;
196  throw e;
197  }
198 } /* TrainModel */
HTMLReport &__cdecl endl(HTMLReport &htmlReport)
Definition: HTMLReport.cpp:240
RunLog & Level(kkint32 _level)
Definition: RunLog.cpp:220
bool validModel
Definition: Model.h:426
virtual void TrainModel(FeatureVectorListPtr _trainExamples, bool _alreadyNormalized, bool _takeOwnership, VolConstBool &_cancelFlag, RunLog &_log)
Performs operations such as FeatureEncoding, and Normalization. The actual training of models occurs ...
Definition: Model.cpp:467
void ModelKnn::WriteXML ( const KKStr varName,
ostream &  o 
) const

Definition at line 202 of file ModelKnn.cpp.

References KKB::XmlTag::AddAtribute(), KKB::KKStr::Empty(), KKB::XmlTag::tagEnd, KKB::XmlTag::tagStart, KKMLL::Model::WriteModelXMLFields(), KKMLL::ModelParamKnn::WriteXML(), KKB::XmlTag::WriteXML(), and KKB::XmlTag::XmlTag().

205 {
206  XmlTag startTag ("ModelParamDual", XmlTag::TagTypes::tagStart);
207  if (!varName.Empty ())
208  startTag.AddAtribute ("VarName", varName);
209  startTag.WriteXML (o);
210  o << endl;
211 
212  WriteModelXMLFields (o); // Write the base class data fields 1st.
213  if (param)
214  param->WriteXML ("Param", o);
215 
216  XmlTag endTag ("ModelParamDual", XmlTag::TagTypes::tagEnd);
217  endTag.WriteXML (o);
218  o << endl;
219 } /* WriteXML */
HTMLReport &__cdecl endl(HTMLReport &htmlReport)
Definition: HTMLReport.cpp:240
void WriteModelXMLFields(std::ostream &o) const
The "WriteXML" method in Derived classes call this method to include the parents classes fields in th...
Definition: Model.cpp:854
bool Empty() const
Definition: KKStr.h:241
virtual void WriteXML(const KKStr &varName, ostream &o) const

The documentation for this class was generated from the following files: